Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php call with cURL in windows azure

Tags:

php

curl

azure

currently I am having a problem trying to use Azure as an SMTP server. I am trying to create a simple contact form that will send an email when you hit send. The PHP code is simple and works on another server as it's from a previous project, but I need to use Microsoft Azure server now and from what I read I need to use either cURL or a sendmail API call. Does anyone know how to do this as I can't seem to get it to work. This is the code that Microsoft say you need to use to get cURL to work,

// Generate curl request
 $session = curl_init($request);

 // Tell curl to use HTTP POST
 curl_setopt ($session, CURLOPT_POST, true);

 // Tell curl that this is the body of the POST
 curl_setopt ($session, CURLOPT_POSTFIELDS, $params);

// Tell curl not to return headers, but do return the response
 curl_setopt($session, CURLOPT_HEADER, false);
 curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

 // obtain response
 $response = curl_exec($session);
 curl_close($session);

 // print everything out
 print_r($response);

I imagine this is much simpler then I can see, but where exactly do I put my php code in this cURL code to get it to work? Is there anything else I am missing on the azure side of things as well? I have sendmail installed on my account already which was all they said I needed.

here is my php code anyway if it helps

$url = 'https://api.sendgrid.com/';
 $user = '[email protected]';
 $pass = 'password7'; 

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => '[email protected]',
      'subject' => 'testing from curl',
      'html' => 'testing body1',
      'text' => 'testing body2',
      'from' => '[email protected]',
   );

 $request = $url.'api/mail.send.json';

 if ($_POST["submit"]) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
        $from = 'Contact Form'; 
        $to = '[email protected]'; 
        $subject = 'Message from Contact Form ';

        $body = "From: $name\n E-Mail: $email\n Message:\n $message";

        // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$_POST['message']) {
            $errMessage = 'Please enter your message';
        }
        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $errHuman = 'Your anti-spam is incorrect';
        }

// If there are no errors, send the email
if (!$errName || !$errEmail || !$errMessage || !$errHuman) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
    } else {
        $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
    }
}
    }
like image 873
Dexter Whelan Avatar asked Jan 02 '15 14:01

Dexter Whelan


1 Answers

Who wants to see some bad coding practices??? So, after much hair pulling and research I figured out a way to get my PHP form to work. I will edit the code with self explaining variables so read through the code and hopefully it should become clear why things are in certain places. Remember this is only useful if you have a windows azure server and you need a php form to work on the server for some reason. You need to install sendmail on your windows portal then you follow the steps to get the url, the password and the username. this all goes into your php file like so. (well, mine works but theres a few redundant bits of code in there, nothing dangerous just me saying I give up, it works, I'll rework it at a later date)

   $url = 'https://api.sendgrid.com/';
 $user = 'this is provided user attribute';
 $pass = 'password1'; 

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => '[email protected]',
      'subject' => 'subject of the email',
      'html' => 'I am the HTML parameter',
      'text' => 'I am the text parameter',
      'from' => $email,
   );

 $request = $url.'api/mail.send.json';

 if ($_POST["submit"]) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
        $from = "From: Contact Form";
        $mobile = $_POST['number'];

        $to = '[email protected]'; 
        $subject = 'Message for subject line of email';

        $humanBool=66;

        $body = "From: $name\n E-Mail: $email\n Message:\n $message";

        // now we go through some validation of the parts in the form 
        // to check everything was entered. In hindsight HTML 5 
        // 'required' attribute is much easier and fulfills exactly 
        // what I did here anyway.
        // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$_POST['message']) {
            $errMessage = 'Please enter your message';
        }
        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $errHuman = 'Your anti-spam is incorrect';
        }else{
          $humanBool = 66;
        }

        // If there are no errors in the data fields i.e. missing data
        if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
          //and the human anti spam field is correct.
            if($humanBool == 66){
              //do the email sending magic.
              //create url for api call
              // ready for that repetitive code?
                $url = 'https://api.sendgrid.com/';
                //create array params for api call
                //these params are what appear in the email that arrives into your email account.
                $params = array(
                    'api_user'  => $user,
                    'api_key'   => $pass,
                    'to'        => '[email protected]',
                    'subject'   => 'Subject',
                    'html'      => "From: $name\n\r Message:\r\n $message",
                    'text'      => 'this is the text element',
                    'from'      => $email,
                  );

                // I don't why I concatenated this but one of the 
                // resources I used while researching said to do it. It 
                // worked, it's also unneccessary. $request is just 
                // https://api.sendgrid.com/api/mail.send.json. I think 
                // the founder of that article is just having a private 
                // joke at people using his code for help.

                //concatenate api url to url above
                $request =  $url.'api/mail.send.json';

                //debugging
                //$error = error_get_last();
                //echo this to see what errors are happening in the file

                // Repetitive code.....
                $url2 = 'https://api.sendgrid.com/api/mail.send.json';


                // Okay queue magic time. I'll explain it as overview
                // here and you guys can step through after the 
                // explanation. 1) magic. 2) Sorcery. I don't quite get 
                // all of it so my explanation would be poor but I
                // will say HOW it works overall. All previous arrays
                // and variables are packaged up in one pack and then
                // a service is called and they are sent as $result 



                // use key 'http' even if you send the request to https://
                $options = array(
                    'http' => array(
                        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                        'method'  => 'POST',
                        'content' => http_build_query($params),
                    ),
                );
                $context  = stream_context_create($options);
                $result = file_get_contents($url2, false, $context);

                // debugging code if something goes wrong 
                // var_dump($result);
                $result='<div class="alert alert-success">Thank You! I will be in touch</div>';

                // this is here to reset the page and clear the fields
                // of the form once mail has been sent.
                $page = $_SERVER['PHP_SELF'];
                $sec = "3";
                header("Refresh: $sec; url=$page");

            }else{
                  $result='<div class="alert alert-danger">Human checked failed</div>';
            }


          }else{
              $result='<div class="alert alert-danger">Validation error</div>';
          }
}


?>
// after this goes the HTML form here is one box from the form as its 
// all the same no need to repeat it all I think.

<div class="form-group">

                        <div class="col-xs-10 col-xs-offset-1">
                            <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" style="text-transform:capitalize" value="<?php echo htmlspecialchars($_POST['name']); ?>" required>
                            <?php echo "<p class='text-danger'>$errName</p>";?>
                        </div>

Now that I have this worked out please feel free to take my code for your own uses if you need to. I thoroughly recommend you don't use windows azure for this sort of thing and just get a different server where the php 'mail' function works which is much easier, I also found other problems with windows azure to do with iFrames stopping responsive design layouts (check your page source if that happens and see if theres a link in your page source, follow the link and see if that solves your responsive problem) And as always if anyone has any questions about the code above please feel free to email me I'll usually get back to you within a day.

Dex

like image 120
Dexter Whelan Avatar answered Oct 08 '22 20:10

Dexter Whelan