title: How Do I use curl_post_async() to Run PHP Script in the Background?
body: <p>I expected the followingcode would create a file, test.txt, in the same directory of the loading script when the page is accessed. But it doesn't. Nothing happens. Could somebody tell what is wrong with this code? Does it work fine in your environment?</p>
  
  <pre><code>&lt;?php
  
  if (isset($_POST['cache']) &amp;&amp; $_POST['cache'] === true) {
      $file = dirname(__FILE__) . '/test.txt';
      $current = time() . ": John Smith\r\n";
      file_put_contents($file, $current,FILE_APPEND);
      return;
  } 
  
  curl_post_async(selfurl(), array('cache' =&gt; true));
  echo 'writing a log in the background.&lt;br /&gt;';
  return;
  
  
  function curl_post_async($url, $params) {
      //http://stackoverflow.com/questions/124462/asynchronous-php-calls
      foreach ($params as $key =&gt; &amp;$val) {
        if (is_array($val)) $val = implode(',', $val);
          $post_params[] = $key.'='.urlencode($val);
      }
      $post_string = implode('&amp;', $post_params);
  
      $parts=parse_url($url);
  
      $fp = fsockopen($parts['host'],
          isset($parts['port'])?$parts['port']:80,
          $errno, $errstr, 30);
  
      $out = "POST ".$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";
      if (isset($post_string)) $out.= $post_string;
  
      fwrite($fp, $out);
      fclose($fp);
  }
  function selfurl() {
      // http://www.weberdev.com/get_example.php3?ExampleID=4291
      $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
      $protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
      $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
      return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
  }
  function strleft($s1, $s2) {
      return substr($s1, 0, strpos($s1, $s2));
  } 
  ?&gt;
  </code></pre>