简体   繁体   中英

Connection refused for PHP curl() when starting PHP webserver via exec()

I'm attempting to start PHP's built-in webserver at the beginning of some unit tests. The goal is for the same script to start the webserver and then connect to it to verify our curl wrapper libraries behave appropriately.

Script:

<?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]);
?>

When I run the above script I get this error:

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

Notes:

  • The webserver does start, if I remove the kill at the end of the script I can see the webserver running in the processlist
  • If I start up PHP's webserver on the command line my PHP script can connect to it
  • If I start up PHP's webserver from another PHP script the above script can connect to it
  • curl from the command line can connect to the PHP webserver started

I can only guess that there's something being blocked or happening when PHP's webserver is started by a process that then attempts to connect to it?

PHP 5.4.15

CentOS release 5.6 (Final)

I think that you rush! You start the webserver in background using "&"

Then you try to connect, but in that moment, your web server is not fully started, so it's not listening!

<?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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM