PHP Built-In Server Can't cURL

4.2k Views Asked by At

I have a relatively simple script like the following:

<?php
$url = "localhost:2222/test.html";

echo "*** URL ***\n";
echo $url . "\n";
echo "***********\n";
echo "** whoami *\n";
echo exec('whoami');
echo "* Output **\n";

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$output = curl_exec($ch); 

curl_close($ch);

echo $output;

When I execute it on the command line, it works - I get the meager results from within test.html.

When I run this script by loading up the built-in PHP server and browsing to the script, it hangs. No output to the screen, nothing written to the logs.

I read that sometimes user permissions can get in the way, so I tried doing whoami to ensure that the user that ran the built-in PHP server is the same as the one who executed the script on the command line; which they are.

safe_mode is off, disable_functions is set to nothing. I can exec other commands successfully (like the whoami).

What else should I check for? Does the built-in PHP server count as someone other user when it fulfills a request perhaps?

3

There are 3 best solutions below

3
On BEST ANSWER

The PHP built-in development web server is a very simple single threaded test server. It cannot handle two requests at once. You're trying to retrieve a file from itself in a separate request, so you're running into a deadlock. The first request is waiting for the second to complete, but the second request cannot be handled while the first is still running.

0
On

Since PHP 7.4 the environment variable PHP_CLI_SERVER_WORKERS allows concurrent requests by spawning multiple PHP workers on the same port on the built-in web server. It is considered experimental, see the docs.

Using it, the PHP script can send requests to itself which is already being served, without halting.

PHP_CLI_SERVER_WORKERS=10 php -S ...

Works with Laravel as well:

PHP_CLI_SERVER_WORKERS=10 php artisan serve
1
On

I think problem in your $url. It may be look like this $url = "http://localhost:2222/test.html"; or $url = "http://localhost/test.html"; I think it's solve your problem. Thanks for your question. Best of luck.