如何使用curl_post_async()在后台运行PHP脚本


How Do I use curl_post_async() to Run PHP Script in the Background?

当访问页面时,我希望以下代码会在加载脚本的同一目录中创建一个文件test.txt。但事实并非如此。什么也没发生。有人能告诉我这个代码出了什么问题吗?它在你的环境中运行良好吗?

<?php
if (isset($_POST['cache']) && $_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' => true));
echo 'writing a log in the background.<br />';
return;

function curl_post_async($url, $params) {
    //http://stackoverflow.com/questions/124462/asynchronous-php-calls
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $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));
} 
?>

问题

脚本中的错误在以下中

if (isset($_POST['cache']) && $_POST['cache'] === true) {
    $file = dirname(__FILE__) . '/test.txt';
    $current = time() . ": John Smith'r'n";
    file_put_contents($file, $current,FILE_APPEND);
    return;
}

$_POST['cache'] === true将尝试验证与boolean具有相同类型的cache,但当使用当前方法在http上发布时,$_POST['cache']将实际输出1

解决方案

if (isset($_POST['cache'])) {
    if ($_POST['cache'] == true) {
        $file = dirname(__FILE__) . '/test.txt';
        $current = time() . ": John Smith'r'n";
        file_put_contents($file, $current, FILE_APPEND);
    }
    return ;
}