Snippet. PHP. Make a POST Request from PHP

This great function mimics the browser behavior in PHP and will allow you to make a HTTP POST request to a server and retrieve the response.

function http_post($url,$options=array()){
    // START: Data
    if (strpos($url, '://') === false) {
	$url = 'http://'.$url;
    }
    
    $url = parse_url($url);
    $host=isset($url["host"])?$url["host"]:'';
    $path = isset($url["path"])?$url["path"]:'/';
    $query = isset($url["query"])?$url["query"]:'';
    $query = str_replace(' ', '+', $query);
    $user = isset($url["user"])?$url["user"]:'';
    $pass = isset($url["pass"])?$url["pass"]:'';
    $data = isset($options["data"])?$options["data"]:array();
    // END: Data

    // START: Prepare the POST string
    $post = array();
    foreach ($data as $field=>$value) {
	$post[] = $field.'='.urlencode(stripslashes($value));
    }
    $post = implode("&",$post);
    // END: Prepare the POST string

    // START: Prepare header
    $header = "POST ".$path.'?'.$query." HTTP/1.0\r\n";
    $header .= "Host: ".$host."\r\n";
    $header.= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
    if($user!=''){
	$header .= 'Authorization: Basic '.base64_encode($user.':'.$pass)."\r\n";
    }
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($post) . "\r\n";
    $header .= "Connection: close\r\n\r\n";
    $header .= $post."\r\n\r\n";
    // END: Prepare header

    // START: Send request
    $fp = fsockopen($host,"80",$err_num,$err_str,30);
    if($fp===false){
	echo "No Connection";exit;
    }
    $result="";
    fputs ($fp, $header);
        while(!feof($fp)){
        $result .= fgets($fp, 128);
    }

    fclose($fp);
    // END: Send request
    
    list($http_headers, $http_body) = explode("\r\n\r\n",  $result, 2);

    return $http_body;
}

Updated on: 28 Mar 2024