Skip to content

Instantly share code, notes, and snippets.

@maheshgattani
Last active January 11, 2022 19:26
Show Gist options
  • Save maheshgattani/8835358 to your computer and use it in GitHub Desktop.
Save maheshgattani/8835358 to your computer and use it in GitHub Desktop.
Fire and forget requests in PHP using fsockopen
<?php
/*
This script can be used by a server to make fire and forget requests to any given url.
This script assumes you have access to $_COOKIE and $_SERVER variable passed along via the server.
GET and POST requests are supported.
POST can have an attached file to it.
Author: Mahesh Gattani ([email protected])
*/
// Make a fire and forget GET request
function fnf_get($ssl, $host, $port, $endpoint, $connectTimeout) {
$cookie_str = '';
foreach ($_COOKIE as $k => $v) {
$cookie_str .= urlencode($k) .'='. urlencode($v) .'; ';
}
$sslstr = ($ssl) ? "ssl://" : "";
$request = "GET $endpoint HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
if (!empty($cookie_str)) {
$request .= 'Cookie: '. substr($cookie_str, 0, -2);
}
$request .= "Connection: Close\r\n";
$request .= "\r\n";
$errno = null;
$errstr = null;
$port = $port;
if (($fp = @fsockopen($sslstr.$host, $port, $errno, $errstr, $connectTimeout)) == false) {
return;
}
fputs($fp,$req);
fclose($fp);
}
// Make a fire and forget POST request
function fnf_post($ssl, $host, $port, $endpoint, $connectTimeout, $file, $filetype) {
$filename = basename($file);
$cookie_str = '';
foreach ($_COOKIE as $k => $v)
$cookie_str .= urlencode($k) .'='. urlencode($v) .'; ';
$sslstr = ($ssl) ? "ssl://" : "";
$eol = "\r\n";
$boundary = '137382108507214398510813094781';
$filepreamble = '--' . $boundary . $eol;
$filepreamble .= 'Content-Disposition: form-data; name="' . $filetype . '"; filename="' . $filename . '"' . $eol;
$filepreamble .= 'Content-Type: application/octet-stream' . $eol . $eol;
$fileepilogue = '--' . $boundary . '--';
$clength = strlen($filepreamble) + filesize($file) + strlen($fileepilogue);
$headers = "POST $endpoint HTTP/1.1" . $eol;
$headers .= "Host: $host" . $eol;
if (!empty($cookie_str))
$headers .= 'Cookie: '. substr($cookie_str, 0, -2);
$headers .= $eol;
$headers .= 'Content-Type: multipart/form-data; boundary="' . $boundary . '"' . $eol;
$headers .= 'Content-Length: ' . ($clength + 50) . $eol . $eol;
$errno = null;
$errstr = null;
$port = $_SERVER['SERVER_PORT'];
$connectTimeout = 2;
$fdata = fopen($file,'r');
if (($socket = @fsockopen($sslstr.$host, $port, $errno, $errstr, $connectTimeout)) == false) {
return;
}
fputs($socket,$headers);
fputs($socket,$filepreamble);
//upload file content here
while(!feof($fdata))
{
$rs = fread($fdata,1440);
$nb = strlen($rs);
fwrite($socket,$rs,$nb);
}
fwrite($socket, "\n", 1);
fputs($socket, $fileepilogue);
fclose($socket);
}
@vearutop
Copy link

vearutop commented Jun 1, 2015

This script does not seem to be asyncronous.

@MiguelQueiroz
Copy link

Please, can you elaborate on that, @vearutop ?

@WaseemBashir983
Copy link

hi this is my code but this is not asynchronous it taking same time as without this.
please help to find a solution for asynchronous function call.

$parts=parse_url($url);
$post_string='';
$errno='';
$errstr='';

       //Use SSL & port 443 for secure servers
   //Use otherwise for localhost and non-secure servers
   //For secure server
        if (preg_match("/www.example.com/i", $_SERVER['SERVER_NAME'])) {
          
    $fp = fsockopen('ssl://' . $parts['host'], isset($parts['port']) ? $parts['port'] : 443, $errno, $errstr, 30);
        }
        else{
            
    //For localhost and un-secure server
   $fp = fsockopen($parts['host'], isset($parts['port'])? $parts['port'] : 80, $errno, $errstr, 30);
        }
        
        if(!$fp){

           echo "ERROR: $errno - $errstr<br />\n";  
        }
        else{

        $out = "GET ".$parts['path']." HTTP/1.1\r\n";
        $out.= "Host: ".$parts['host']."\r\n";
        $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out.= "Content-Length: ".strlen($post_string)."\r\n";
        $out.= "Connection: Close\r\n\r\n";

        fgetss($fp, 1024);
        fclose($fp);

@maheshgattani
Copy link
Author

Hi. In https://gist.github.com/maheshgattani/8835358#file-async_request-php-L26 the $req variable is wrong. Thank you for your functions.

Thanks, fixed.

@maheshgattani
Copy link
Author

This script does not seem to be asyncronous.

I assume you mean it is fire and forget. I agree. I have update the names accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment