Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello,

I was wondering if it is possible for some PHP code to tell if it is running from a online web server or from a local host server.
I ask this because commenting out code that will run on a localhost but not an online web server.

For example with MYSQL, my login credentials are completely different from the online MYSQL credentials.
I am using Filezilla for my FTP, Xampp for my localhost and www.000webhost.com from a free online web server. It would be nice just to FTP a working localhost php file to the web server without modifying the code.

Here is what I am thinking.
I use some If, ElseIF statements to achieve this

PHP
<?php

if ($localhost == TRUE) {

   mysql_connect("localhost", "test", "") or die(mysql_error());
   echo "Connected to Localhost<br />";
} 

elseif (($localhost == FALSE) {

   mysql_connect("mysql3.000webhost.com", "username", "password") or die(mysql_error());
   echo "Connected to online server<br />";
}
?>

I don't know if this is the right way of doing this. Can someone please help? thanks.
Posted
Updated 22-Apr-12 15:34pm
v2
Comments
Sergey Alexandrovich Kryukov 22-Apr-12 22:45pm    
How do you calculate $localhost? No, the code makes no sense.
--SA

1 solution

Several ways:
1. (may be unreliable) see if the request URL includes the string 'localhost'
2. In your XAMPP config, set a unique server name, then test $_SERVER['SERVER-NAME'] in PHP
3. Invert the test - see if the BROWSER is local - if $_SERVER['REMOTE_ADDR'] is 127.0.0.1

Cheers,
Peter
 
Share this answer
 
Comments
Mohibur Rashid 25-Apr-12 1:51am    
Good one +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900