RemeJuan
RemeJuan

Reputation: 863

Check for localhost and ignore port

I managed to find a php script to check for localhost, but using webmatrix there is always a port appended to the url and the port changes from site to site.

<?php if ($_SERVER['HTTP_HOST'] == 'localhost:62036')  { ?>
<style>
    #introContent {display:none !important;}
</style>
<?php } ?>

Current project is almost done, but will come in handy with the next ones being able to disable certain styles and functions within the testing environment. I tried a modification of above using strpos but that did not work and am not sure how to correctly use substring. Being able to drop the port will make it simpler when carrying over to other projects, 1 less thing to forget to update.

Some help would be greatly appreciated

Upvotes: 1

Views: 243

Answers (1)

Rudi Visser
Rudi Visser

Reputation: 21979

To solve your problem in a crude way, you could simply take the first part of the string like so:

<?php
$host = $_SERVER['HTTP_HOST'];
$colPos = strpos($host, ':');
$host = $colPos !== false ? substr($host, 0, $colPos) : $host;

if ($host == 'localhost') { ?>

However, a better way would be to use constants to set your environment name, such as DEV, PRODUCTION etc.

You can do this like so... In a config.php (or globally included file):

<?php
define('ENVIRONMENT', 'DEV'); // or PRODUCTION

.. then in your main file:

<?php if (ENVIRONMENT == 'DEV') { ?>

Upvotes: 2

Related Questions