How to POST with PHP and fsockopen

by admin on July 24, 2009 · 0 comments

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.1rn");
    fputs($fp, "Host: $hostrn");
    fputs($fp, "Content-type: application/x-www-form- urlencodedrn");
    fputs($fp, "Content-length: " . strlen($data) . "rn");
    if ($useragent) {
        fputs($fp, "User-Agent: MSIErn");
    }
    fputs($fp, "Connection: closernrn");
    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;
}

Previous post:

Next post: