Friday, September 22, 2006

How can I send variables from a PHP script to another URL using POST method without using forms and hidden variables?

Question :
How can I send variables from a PHP script to another URL using POST method without using forms and hidden variables?

Answer :
You can do this by opening an HTTP socket connection and send HTTP POST commands.
Example:

// Generate a request header
$RequestHeader =
"POST $URI HTTP/1.1\n".
"Host: $Host\n".
"Content-Type: application/x-www-form-urlencoded\n".
"Content-Length: $ContentLength\n\n".
"$RequestBody\n";

// Open the connection to the host
$socket = fsockopen($Host, 80, &$errno, &$errstr);
if (!$socket)

$Result["errno"] = $errno;
$Result["errstr"] = $errstr;
return $Result;
}
$idx = 0;
fputs($socket, $RequestHeader);
while (!feof($socket))

$Result[$idx++] = fgets($socket, 128);
}
//-------------------------------------------
?>


Or you can use the php cURL functions. this is mostly used for sending the Credit Card details over the secure channel.

$URL="www.testsite.com/test.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://$URL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Data1=blah&Data2=blah");curl_exec ($ch);
curl_close ($ch);
?>

This will have an effect of posting your data to the $URL site, without any header hacking.

To use cURL you need to recompile PHP with cURL support.

No comments: