Snippet. PHP. Make a GET Request from PHP

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

function http_get($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 GET string
    $get = array();
    foreach ($data as $field=>$value) {
	$get[] = $field.'='.urlencode(stripslashes($value));
    }
    $get = implode("&",$get);
    // END: Prepare the GET string

    // START: Prepare header
    if($get!='')$path .= '?'.$get;
    $header = "GET ".$path." 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 .= "Connection: close\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: 23 Nov 2024