Simulating a form submit using POST method through CURL

Below piece of code can simulate a form submission through post method.

/******** The below header simulates Chrome Browser ********/

$header[0] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";

$header[1] = "Accept-Language: en-US,en;q=0.8"; 
$header[2] = "Cache-Control: max-age=0";
$header[3] = "Connection: keep-alive";
$header[4] = "Host: www.doamin-name.com";

$header[5] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36";

$header[6] = "Referer: http://www.referrer-domain.com/"; 

/***********  end of header **********************/


$url = "http://www.doamin-name.com/page.php";
$param = "param=value1&submit=Submit"; // params that need to be passed
       
$ch = curl_init() or die(curl_error()); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 

//curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // would be required if the return is going to be a binary file like image. From PHP ver 5.1.3 onwards the return is always binary so need not set this if PHP ver is >= 5.1.3

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //returns the received data in a variable. Must be on if CURLOPT_BINARYTRANSFER is set to 1 or true

//curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']); // if required. This sets Cookies to be sent with the request

$data1=curl_exec($ch) or die(curl_error($ch));
curl_close($ch);

If PHP Session Cookie needs to be retrieved from the result of the above request:

preg_match('/^Set-Cookie:\s*([^;]*)/mi', $data1, $m);
parse_str($m[1], $cookies);

echo $cookies['PHPSESSID'];

Leave a Reply