A simple HTTP client for PHP
A simple HTTP client for PHP that uses curl:
1 class HTTP { 2 static function get($url, $headers=null) { 3 $ch = curl_init(); 4 curl_setopt($ch, CURLOPT_URL, $url); 5 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 6 curl_setopt($ch, CURLOPT_HEADER, true); 7 8 if($headers) { 9 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 10 } 11 12 // Execute request 13 $response = curl_exec($ch); 14 15 // Split headers and body 16 list($header_text, $body) = explode("\r\n\r\n", $response, 2); 17 $header_lines = explode("\r\n", $header_text); 18 19 // Extract HTTP status 20 $header_line = array_shift($header_lines); 21 if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@', $header_line, $matches)) { 22 $status = $matches[1]; 23 } 24 25 // Extract HTTP headers 26 $headers = array(); 27 foreach ($header_lines as $header_line) { 28 list($header, $value) = explode(': ', $header_line, 2); 29 $headers[$header] = $value; 30 } 31 32 $info = curl_getinfo($ch); 33 34 curl_close($ch); 35 36 $status = $info['http_code']; 37 38 return new Response($status, $body, $headers, $info); 39 } 40 }
Even supports reading response headers.
1 class Response { 2 public function Response($code, $body, $headers, $info=null) { 3 $this->code = $code; 4 $this->body = $body; 5 $this->headers = $headers; 6 $this->info = $info; 7 } 8 }
How to use file_get_contents with a proxy
1 $url = 'http://www'; 2 3 $proxy = 'tcp://xxx:8080'; 4 5 $context = array( 6 'http' => array( 7 'proxy' => $proxy, 8 'request_fulluri' => True, 9 ), 10 ); 11 12 $context = stream_context_create($context); 13 14 $body = file_get_contents($url, False, $context);
The code was found here. Note that it doesn’t seem to work with HTTPS.
How to convert a string to a timestamp and then back to a string with PHP
1 $r = date_parse("8:16:12 01.02.2008"); 2 $d = mktime($r['hour'], $r['minute'], $r['second'], $r['month'], $r['day'], $r['year']); 3 echo date("H:i:s d.m.Y", $d);
Prints out the following:
1 8:16:12 01.02.2008
How to set a cookie, remove a cookie and get the value of a cookie in PHP
PHP cookie management is a good example of how incredibly badly designed PHP is:
Set a cookie that expires when browser is closed
Note that you most probably want to set the path, which we do here:
1 $value = 0; 2 $expires = 0; 3 setcookie('cookie_name', $value, $expires, '/');
Remove cookie
1 setcookie ('cookie_name', FALSE, time()-10000);
Get cookie value
1 $_COOKIE['cookie_name']
How to debug memory allocation problems in PHP with Xdebug
Xdebug is a good tool for finding the root cause of memory allocation problems such as the one shown here:
1 Fatal error: Allowed memory size of X bytes exhausted (tried to allocate X bytes)
First install Xdebug by following the Xdebug installation instructions.
Next surround the code you suspect is causing the problem with the following function calls:
1 xdebug_start_trace('/tmp/mytrace'); 2 ... 3 Bad bad PHP code 4 ... 5 xdebug_stop_trace();