Submit a form post with curl in php

In previous post we covered The working of curl in php. As we saw that cURL is very powerful and can be used to submit an HTML form with its post data.

This is easy and simple and has a lot of ways to do. Here is a little piece of code to do the same. The two curl_setopt() options

'CURLOPT_POST' and 'CURLOPT_POSTFIELDS' with some other options will do all the trick.

Suppose we have to submit this form


  <form method="post" action="http://example.com/post.php">
    <input type="text" name="name"  >
    <input type="text" name="email" >
    <input type="submit" value="Submit" >
  </form>


Now create an array of your form data to be posted like...

$data = array('name' => 'your name', 'email' => 'email@example.com');

Set the url

$url="http://www.example.com/post.php";

The full code is here


    $data = array('name'=>'name','email'=>'email@example.com');
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13";
    $url = "http://www.example.com/post.php";
   
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);    
    $output = curl_exec($ch);
    curl_close($ch);
    
    echo $output;

Submit a form post with curl in php Submit a form post with curl in php Reviewed by JS Pixels on May 25, 2012 Rating: 5

No comments:

Altaf Web. Powered by Blogger.