9

PHP 5.4 comes with a built-in server for development purposes. This is the kind of thing I've been waiting for months, because up until now I've had to sort of hack together a PHP script that listens for incoming connections and handles them (because I don't want to go to the trouble and overhead of installing an actual server).

The main thing left for me to worry about is: how can I have a port assigned?

In my PHP script, I used to do this:

socket_bind($sock,"localhost",0) or die("Could not bind socket");
socket_getsockname($sock,$ip,$port);

$port would then be the port number assigned by the OS based on what is available.

I was just wondering if any such feature existed in PHP's built-in server and, if so, what the command line should be to access it.

hakre
  • 193,403
  • 52
  • 435
  • 836
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • +1 for the interesting question, but for what it's worth, running an off-the-shelf server sounds *way* easier to me than hacking together a PHP script to do the same thing. – Brad Mar 26 '12 at 14:40
  • 1
    It probably would have been, but it was an extremely good exercise on networking ;) – Niet the Dark Absol Mar 26 '12 at 14:43
  • WebMatrix comes loaded with drivers for almost all features, and its fairly small install too. http://microsoft.com/web/webmatrix. Thats what i use to demo my local developments. – rackemup420 Mar 26 '12 at 14:44

2 Answers2

1

Answering my own question (again), I used the following batch script to find an available port and start the server:

@echo off
for /L %%a in (8000,1,8100) do netstat /a /n | find "%%a" | find "LISTENING" >NUL || set tmp_phpserver=%%a&& goto found
echo No free ports found in range 8000-8100...
pause
exit
:found
echo Starting server on port %tmp_phpserver%
start "PHP server %~p1 on localhost:%tmp_phpserver%" /min php -S localhost:%tmp_phpserver%
echo Server started
timeout 3
start http://localhost:%tmp_phpserver%/%~nx1
set tmp_phpserver=
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

From the PHP docs:

Example #1 Starting the web server

 $ cd ~/public_html
 $ php -S localhost:8000

There you have it - the server is running on port 8000.

yrosen
  • 364
  • 2
  • 4
  • 3
    That'll fail if something else happens to be using port 8000 at the moment (like another PHP dev server). –  Mar 27 '12 at 19:06