Make asynchronous call in PHP using PHP socket and custom User agent string

Recently I wrote about async calls in PHP. In the provided example from there is one thing missing – User agent string.

Changing User agent string to something unique is handy, when analyzing log file. You can see, if someone is messing with your hidden asynchronous PHP script.

Here is an example, that uses PHP socket to make async call:

function backgroundPost($url){
  $fp = fsockopen($parts[‘host’],
          $errno, $errstr, 30);
  if (!$fp) {
      return false;
  } else {
      $out = "POST ".$parts[‘path’]." HTTP/1.1\r\n";
      $out.= "Host: ".$parts[‘host’]."\r\n";
      $out.= "User-Agent: custom user agent. Not Gecko!\r\n";
      $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
      $out.= "Content-Length: ".strlen($parts[‘query’])."\r\n";
      $out.= "Connection: Close\r\n\r\n";
      if (isset($parts[‘query’])) $out.= $parts[‘query’];
      fwrite($fp, $out);
      return true;
//Example of use

Don’t forget to change “User-Agent” to something more meaningful for you.

The function backgroundPost opens TCP/IP connection to specified $url and makes HTTP POST. Right after data is submitted to the server, we close connection using fclose function, but the background script keeps running. If the background script is on the same server, we have two PHP scripts running simultaneously.

As suggested in the I use ignore_user_abort(true); in the slow_async_script.php, so that PHP or Apache keep my script running even after we have aborted connection to it (using socket close command fclose).

Windows API Function SetFileAttributes silently ignores compressed and encrypted attributes

When you call Windows API function SetFileAttributes, it ignores FILE_ATTRIBUTE_COMPRESSED (0x800) and FILE_ATTRIBUTE_ENCRYPTED (0x4000) values passed as parameters.

Most likely it is implemented in this way, because you can pass value from GetFileAttributes, FindFirstFile and FindNextFile without modifications to SetFileAttributes.

This applies to Windows XP, Windows Server 2003 / 2008, Windows Vista.