0

我试图在一些单元测试开始时启动 PHP 的内置网络服务器。目标是让同一个脚本启动网络服务器,然后连接到它以验证我们的 curl 包装器库的行为是否正确。

脚本:

<?php
    echo "Starting server...\n";
    exec("php -S localhost:8000 -t /path/to/files > /dev/null & echo $!", $output);


    $ch = curl_init("http://localhost/");
    curl_setopt($ch, CURLOPT_PORT, 8000);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);

    if(curl_errno($ch))
    {
            echo 'Curl error: ' . curl_error($ch);
    }

    // Close handle
    curl_close($ch);

    echo "PID: ".$output[0]."\n";
    exec('kill '.$output[0]);
?>

当我运行上面的脚本时,我得到了这个错误:

Curl error: Failed connect to localhost:8000; Connection refused

笔记:

  • 网络服务器确实启动了,如果我删除kill脚本末尾的 ,我可以看到网络服务器在进程列表中运行
  • 如果我在命令行上启动 PHP 的网络服务器,我的 PHP 脚本可以连接到它
  • 如果我从另一个PHP 脚本启动 PHP 的网络服务器,上面的脚本可以连接到它
  • curl从命令行可以连接到 PHP webserver 启动

我只能猜测当 PHP 的网络服务器由一个然后尝试连接它的进程启动时,有什么被阻止或发生了?

PHP 5.4.15

CentOS 5.6 版(最终版)

4

1 回答 1

2

我觉得你着急!您使用“&”在后台启动网络服务器

然后你尝试连接,但在那一刻,你的网络服务器还没有完全启动,所以它没有在监听!

<?php
    echo "Starting server...\n";
    exec("php -S localhost:8000 -t /path/to/files > /dev/null & echo $!", $output);


// sleep 1-5 seconds
sleep (5);

$ch = curl_init("http://localhost/");
curl_setopt($ch, CURLOPT_PORT, 8000);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

if(curl_errno($ch))
{
        echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);

echo "PID: ".$output[0]."\n";
exec('kill '.$output[0]);
于 2013-08-02T16:53:14.453 回答