start blog post

HTTP, HTTPS, and SSL via PHP

Jump to parts of this post:

  1. HTTP with PHP Sockets
  2. Direct SSL Sockets in PHP
  3. HTTPS via cURL

See Also:

HTTP with PHP Sockets 

// don't need to specify http, it's the default protocol
$hostname = "www.google.com";
$port     = 80;

// create and configure the client socket
$fp = fsockopen($hostname, $port); // optional: $error_number, $error_string, $connect_timeout
if ($fp) {
    stream_set_timeout($fp, 30); // seconds to wait for i/o operations
    
    // send request headers
    fwrite($fp, "GET / HTTP/1.1\r\n");
    fwrite($fp, "Host: $hostname\r\n");
    fwrite($fp, $additional_headers); // Accept, User-Agent, Referer, etc.
    fwrite($fp, "Connection: close\r\n");
    
    // read response
  $response = "";
    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }
  echo $response;
    
    // close the socket
    fclose($fp);
}

Direct SSL Sockets in PHP 

You don't have to send request headers in the above example. You can actually connect to some servers and send raw text with fwrite. Because you have to implement the HTTP/HTTPS protocol yourself if you want it, sockets are considered "clean" connections.

// note that "ssl" is the protocol, NOT "https"
$hostname  = "ssl://your-secure-site.com";
$port      = 443;

// create and configure the client socket
$fp = fsockopen($hostname, $port);
if ($fp) {
    stream_set_timeout($fp, 30);
    
  // send data (or build HTTPS headers similar to first example)
  fwrite($fp, "your message goes here");
    
    // read response
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    
    // close the socket
    fclose($fp);
}

HTTPS via cURL 

PHP doesn't directly support attaching client certificates to web requests with fsockopen, so you have to use the cURL library.

$url = "https://your-secure-site.com/secure-service.php";
$port = 443;

// POST data, formatted just like a GET query string
$request = "name=hb&age=27&site=arguments.callee.info";

// the client certificate path MUST be a physical path, not url
$certificate = "C:\\certificates\\test.crt"; // windows example
$certificate = "/etc/pki/tls/private/test.crt"; // unix/linux example
$password = 'mypassword'; // client certificate's key

// more details at http://php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $certificate);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $password);

// fetch response and close the socket
$response = curl_exec($ch);
curl_close($ch);

var tags = [];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

most viewed this week

least viewed this week