Find an Available Port for a PHP Server

PHP 5.4 comes with an embedded server for development purposes. This is what I expected for several months, because so far I had to parse a PHP script that listens for incoming connections and processes them (because I do not want to go into the problems and overhead of installing a real server).

The main thing I can worry about: how can I assign a port?

In my PHP script, I used this:

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

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

I'm just wondering if any such function exists on the embedded PHP server, and if so, what should be access to the command line.

+8
php
source share
2 answers

Answering my own question (again), I used the following batch of 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= 
+1
source share

From PHP docs :

Example # 1 Starting a web server

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

There you have it - the server runs on port 8000.

0
source share

All Articles