Can the php -S command be used to setup remote access to application?

44 Views Asked by At

I have a school project where I need to host and run a php program. I have having difficulties getting it to run as expected in Apache, however, when I run it with php -S, it runs like a champ. I would like to host this where it is accessible on an external IP. I suspect that php -S will only allow access from the local machine.

I would like to use php -s xxx.xxx.xxx.xxx:80. I would like to confirm that php -S will not do that. I would be glad to hear of other alternatives.

1

There are 1 best solutions below

0
Álvaro González On

To answer the question, yes, you can. The built-in web server requires to provide a host + port combination (there's no default) and it doesn't implement any active check to reject non-local addresses:

$ php -S 192.168.0.15:8080
[Fri Sep  8 10:37:37 2023] PHP 8.1.2-1ubuntu2.14 Development Server (http://192.168.0.15:8080) started

On some operating system like Linux you will need administrator privileges to open protected ports (those below 1024):

$ php -S 192.168.0.15:80
[Fri Sep  8 10:38:38 2023] Failed to listen on 192.168.0.15:80 (reason: Permission denied)
$ sudo php -S 192.168.0.15:80
[Fri Sep  8 10:38:41 2023] PHP 8.1.2-1ubuntu2.14 Development Server (http://192.168.0.15:80) started

Your firewall, if any, needs to allow incoming connections. As usual, if you need access from outside your local network you will have to define an appropriate redirection in your router, so incoming connections to a specific protocol/port are redirected to your computer, and also provide your end users with either your public IP address or a domain name that points to it. Note that IPv4 are scarce, so some hosting providers share addresses between several customers (Carrier-grade NAT, aka CGNAT), thus don't allow external access to your router.

Additional caveats:

  • This is a developer tool and, according to its creators, should not be used on a public network.

  • It won't handle concurrent requests by default. For that, you need to set the PHP_CLI_SERVER_WORKERS environment variable to the number of desired workers before starting the server. This feature is experimental and not available on Windows.

  • Your computer needs to be turned on, with a console open running the command. If it crashes or closes, you need to be there to run it again. There're ways to automate this, but this is certainly a scenario the tool was not designed for.

Should you do this? In your use case, absolutely not. Just fix your code/setup to work in Apache. Fixing configuration problems is part of the learning process. You cannot ditch a tool every time it doesn't work on first attempt.