X-Mann
X-Mann

Reputation: 327

How to change port with PHP and avoid Content or Connection error in Firefox?

I have a server administration page coded in PHP, and one of the features is to change the port on which the admin page is accessed. This is done with a number <input> field in a self-calling form, POST method. When the Submit button is clicked, the code takes the input number, writes it to the Nginx config file for the server as the port number to use, then runs the command to restart Nginx:

exec('sudo service nginx restart > /dev/null &');

The problem is that when this command is run, Firefox throws up a Content error. I have tried to work around the problem, changing to this block of code:

$newAPort = $_POST['admin-port'];
header('Content-Length: 0');
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');
sleep(15);
$newURL = 'http://'.$_SERVER[HTTP_HOST].':'.$newAPort;
header('Location: '.$newURL);

That's some progress, the Firefox error is now "Unable to connect", and the error shows the URL with the old port number. How can I redirect to the new port correctly? I thought the above block of code would do it but it doesn't.

Upvotes: 1

Views: 124

Answers (1)

X-Mann
X-Mann

Reputation: 327

The discussion with CBroe led in the right direction, and after a few more searches on SO and elsewhere, I got a working solution, posted here in case it helps others. The block of code in my question is refactored like so:

$rawHost = $_SERVER['HTTP_HOST']; // Get host
$onlyHost = explode(':', $rawHost)[0]; // Drop port num
$newAPort = $_POST['admin-port'];
header('Refresh:5; url=http://'.$onlyHost.':'.$newAPort, true, 301);
echo '<h3>Please wait a few seconds while the server updates...</h3>';
fastcgi_finish_request();
// Restart Nginx
exec('sudo service nginx restart > /dev/null &');

Upvotes: 1

Related Questions