faqts : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

828 of 938 people (88%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Using PHP, how do I send a http POST without using a form?
How can I add a file to the $data? As in a form containg an <input type=file>

Feb 27th, 2008 00:02
dman, Gerhardt, Philip Olson, Knud van Eeden, Daniel Dickey, bob everett, Mark Wright, http://www.ttnr.org


There are a few functions floating around out there but essentially it 
comes down to using fsockopen().  User functions posttohost() and 
sendtohost() exist, here's the sendtohost() code which can be also 
seen at:

  http://dodds.net/~cardinal/sendtohost.txt

Note that the above URL contains some errors. All HTTP headers must 
end with \r\n. Most webservers will accept just the linefeed 
character, but you should always follow the standard if possible

More info available at: http://www.faqs.org/rfcs/rfc2616.html

Here's a slightly modified version of sendtohost():

/* sendToHost
 * ~~~~~~~~~~
 * Params:
 *   $host      - Just the hostname.  No http:// or 
                  /path/to/file.html portions
 *   $method    - get or post, case-insensitive
 *   $path      - The /path/to/file.html part
 *   $data      - The query string, without initial question mark
 *   $useragent - If true, 'MSIE' will be sent as 
                  the User-Agent (optional)
 *
 * Examples:
 *   sendToHost('www.google.com','get','/search','q=php_imlib');
 *   sendToHost('www.example.com','post','/some_script.cgi',
 *              'param=First+Param&second=Second+param');
 */

function sendToHost($host,$method,$path,$data,$useragent=0)
{
    // Supply a default method of GET if the one passed was empty
    if (empty($method)) {
        $method = 'GET';
    }
    $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);
    }

    while (!feof($fp)) {
        $buf .= fgets($fp,128);
    }
    fclose($fp);
    return $buf;
}

And for good measure:
  http://www.php.net/fsockopen

Related tutorials/scripts:
  http://snoopy.sourceforge.net/
  http://www.zend.com/zend/spotlight/mimocsumissions.php

Keywords/typos: posttohost post2host post_to_host senttohost send2host