user5349142
user5349142

Reputation: 127

Socket error on HTTPS but not on HTTP | PHP

I have a background script running via socket as follows

   if (strstr($_SERVER['PHP_SELF'], "/")) { 
        $location = array(); 
        $location = explode("/", $_SERVER['PHP_SELF']); 
        $folder = $location[count($location) - 2]; 
    } 
    else { 
        $folder = $_SERVER['PHP_SELF']; 
    }

    //script, runs in background
    $host = HOST;
    $remote_house = 'https://'.$host.'/'.$folder.'/controllers/background';

    $socketcon = fsockopen($host, 80);

    if($socketcon) {   
        $socketdata = "GET $remote_house/".$scriptName." HTTPS 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n"; 
        fwrite($socketcon, $socketdata); 
        fclose($socketcon);
    }

This is working properly on localhost and online with HTTP but it fails to work on HTTPS with this error.

HTTP/1.0 400 Bad request Cache-Control: no-cache Connection: close Content-Type: text/html 400 Bad request Your browser sent an invalid request.

Any idea?

Upvotes: 0

Views: 1851

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123300

$socketdata = "GET $remote_house/".$scriptName." HTTPS 1.1\r\n...

This is both an invalid HTTP and an invalid HTTPS request. First, it should be HTTP/1.1 not HTTPS 1.1. And for HTTPS you need to first create a SSL/TLS connection to the peer and then you can send your HTTP request over this connection.

$remote_house = 'https://'.$host.'/'.$folder.'/controllers/background';

Moreover, the path component in the request should not contain the full URL but only the path, i.e. '/'.$folder.'/controllers/background'.

$socketcon = fsockopen($host, 80);

And for HTTPS you need to connect to port 443 not 80 and then do a SSL/TLS handshake there before sending the HTTP request.

Upvotes: 1

Related Questions