0

我预计以下代码会在访问页面时在加载脚本的同一目录中创建一个文件 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));
} 
?>
4

1 回答 1

1

问题

您的脚本中的错误如下

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将尝试使用与当前方法cache相同的类型进行验证,boolean但实际上会在使用当前方法发布时$_POST['cache']输出1http

解决方案

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 ;
}
于 2012-09-12T11:16:51.100 回答