Today we are going to learn about sending post request using curl in php.You can learn about basics of curl in my last article about using curl library in php “what-is-curl-in-php“.
Process of sending post request using curl in php
Find a form to submit using post method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<form method="post" action="index.php#contact"> <p>Name</p> <p> <input type="text" name="userName" placeholder="Enter Name"> </p> <p>Email-id</p> <p> <input type="text" name="userEmailid" placeholder="Enter Email-id"> </p> <p>Message</p> <p> <textarea name="userMessage" placeholder="Write Message"></textarea> </p> <p> <input type="submit" name="sendmessage" value="Send Message"> </p> </form> |
Get the url where the form get submitted.
http://tusharsharma.in/index.php#contact
Get form fields name.
userName,userEmailid,userMessage,sendmessage
In above images, i used firebug to check the post request.In first image, i filled the form and opened firebug and click on persist button so that i can see post request. In second image, i have looked for form fields and also you can check the post data string in the image. By using following code, I will send a message by submitting a form i.e. sending data in post using curl.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $url = "http://tusharsharma.in/index.php#contact"; $ch = curl_init(); // this will initalize a curl session curl_setopt($ch, CURLOPT_URL,$url); // set url for http request curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); // used to get request output as string $data_to_post = array( 'sendmessage' => urlencode("Send Message"), 'userEmailid' => urlencode("tushar121191@gmail.com"), 'userMessage' => urlencode("Hey Tushar, how are you bro.I just started learning sending post data using curl and i m enjoying your post."), 'userName' => urlencode("John Doe"), ); $data_string = rawurldecode(http_build_query($data_to_post)); //"sendmessage=Send+Message&userEmailid=tushar121191%40gmail.com&userMessage=Hey+Tushar%2C+how+are+you+bro.I+just+started+learning+sending+post+data+using+curl+and+i+m+enjoying+your+post.&userName=John+Doe" curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string); curl_exec($ch); curl_close($ch); ?> |
When i check my mail, hurrah, i got the message.
That’s all for today, hope you enjoy and do try at home.