tags:

views:

815

answers:

2

Hello, I'd like to have one server make an http post request to another server. Can I do this with a basic php install (Dreamhost in my case)? If so, please point me in the right direction! thanks, -Morgan

+5  A: 

I'd use Curl, if I were you.

Edit: And it looks like it's supported on DH.

Oli
thanks Oli. I was leaning that way already. I'll do it.
morgancodes
I'd also recommend Curl, especially of you need to pass lots of parameters etc. It is also worth remembering that most of PHP's file functions will happily open URL's as well as local files.
rikh
A: 

http://blog.brezovsky.net/en-text-3.html

    function httpSocketConnection($host, $method, $path, $data)
    {
        global $Db;


        $method = strtoupper($method);        

        if ($method == "GET")
        {
            $path.= '?'.$data;
        }    

        $filePointer = fsockopen($host, 80, $errorNumber, $errorString);

        if (!$filePointer) 
        {
            throw new Exception("Chyba spojeni $errorNumber $errorString");
        }

        $requestHeader = $method." ".$path."  HTTP/1.1\r\n";
        $requestHeader.= "Host: ".$host."\r\n";
        $requestHeader.= "User-Agent:      Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
        $requestHeader.= "Content-Type: application/x-www-form-urlencoded\r\n";

        if ($method == "POST")
        {
            $requestHeader.= "Content-Length: ".strlen($data)."\r\n";
        }

        $requestHeader.= "Connection: close\r\n\r\n";

        if ($method == "POST")
        {
            $requestHeader.= $data;
        }            

        fwrite($filePointer, $requestHeader);

        $responseHeader = '';
        $responseContent = '';

        do 
        {
            $responseHeader.= fread($filePointer, 1); 
        }
        while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));


        if (!strstr($responseHeader, "Transfer-Encoding: chunked"))
        {
            while (!feof($filePointer))
            {
                $responseContent.= fgets($filePointer, 128);
            }
        }
        else 
        {

            while ($chunk_length = hexdec(fgets($filePointer))) 
            {
                $responseContentChunk = '';


                $read_length = 0;

                while ($read_length < $chunk_length) 
                {
                    $responseContentChunk .= fread($filePointer, $chunk_length - $read_length);
                    $read_length = strlen($responseContentChunk);
                }

                $responseContent.= $responseContentChunk;

                fgets($filePointer);

            }

        }




        return chop($responseContent);

    }
l_39217_l
None of the standard php stream-reading/writing commands have URL access on Dreamhost (AFAIK) for security reasons.
Oli
Using the http stream wrapper would seem a lot more sensible if that stuff was enabled, anyhow.
Ciaran McNulty