PHP Code

How to POST with PHP and fsockopen

There are many instances where you're developing a web application and need to retrieve a remote web page with PHP. Usually, the easiest way is to use fopen or fsockopen. But the default method of these functions is the GET method. But if you're retrieving a web page that is obtained by submitting a remote form, you may need to POST to that form. Here's a function that allows that:


function sendToHost($host,$method="GET",$path,$data,$useragent=0)
{
    $method = strtoupper($method);
    $fp = fsockopen($host, 80);
    if ($method == 'GET') {
        $path .= '?' . $data;
    }
    fputs($fp, "$method $path HTTP/1.1\r\n");
    fputs($fp, "Host: $host\r\n");
    fputs($fp, "Content-type: application/x-www-form- urlencoded\r\n");
    fputs($fp, "Content-length: " . strlen($data) . "\r\n");
    if ($useragent) {
        fputs($fp, "User-Agent: MSIE\r\n");
    }
    fputs($fp, "Connection: close\r\n\r\n");
    if ($method == 'POST') {
        fputs($fp, $data);
    }

    $cookie = "";
    while (!feof($fp)) {
        $line = fgets($fp, 1024);
        if (preg_match('/^set-cookie:\s*PHPSESSID=([a-z0-9]+)/i', $line, $matches)) 
        	$cookie = $matches[1];
        $buf .= $line;
    }
    fclose($fp);
    //header("Location: http://" . $host . '/' . $path . "?PHPSESSID=$cookie"); // alternately transfer to remote host after submitted form
    return $buf;
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image