Online Shopping : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to
Did You Find This Entry Useful?

844 of 958 people (88%) answered Yes
Recently 9 of 10 people (90%) answered Yes


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>

Mar 24th, 2009 16:55
chat alarab, healthy man, dman, Gerhardt, Philip Olson, Knud van Eeden, Daniel Dickey, bob everett, Mark Wright,

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:
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:
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('','get','/search','q=php_imlib');
 *   sendToHost('','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);
    return $buf;
And for good measure:
Related tutorials/scripts:
Keywords/typos: posttohost post2host post_to_host senttohost send2host