Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-17-2012, 01:34 AM   PM User | #1
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Switch between local and live

I believe that many people will comment and uncomment blocks (or individual lines) of code when switching between local and live running of their pages. This can be a pain. I use the following code and just change a value from true to false when moving to the remote/live site:
PHP Code:
<?php
if (!defined('LOCAL')) {
    
define('LOCAL'true);      // set this to true or false
}
if (!
defined('DB_USER')) {
    if (
LOCAL) {
        
DEFINE('DB_USER''Andrew');
        
DEFINE('DB_PASSWORD''Password1');
        
DEFINE('DB_HOST''localhost');
        
DEFINE('DB_NAME''AndyDB');
        
DEFINE('EMAIL''andy@somemail.com'); 
        
DEFINE('BASE_URL''http://localhost:80/AndysProject/');
    } else {
        
DEFINE('DB_USER''user2');
        
DEFINE('DB_PASSWORD''Password2');
        
DEFINE('DB_HOST''www.some.com');
        
DEFINE('DB_NAME''db2');
        
DEFINE('EMAIL''host@someother.com'); 
        
DEFINE('BASE_URL''http://andyshost.com/');
    }
}
?>
I store this in a config.php file that is included in relevant pages.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS

Last edited by AndrewGSW; 12-17-2012 at 01:37 AM..
AndrewGSW is offline   Reply With Quote
Old 12-17-2012, 10:40 AM   PM User | #2
idalatob
Regular Coder

 
Join Date: Sep 2007
Location: Grahamstown, South Africa
Posts: 237
Thanks: 6
Thanked 17 Times in 17 Posts
idalatob is on a distinguished road
Here's a cool way of doing it too:

//in your php config file
PHP Code:
defined('APPLICATION_ENV')
    || 
define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

if (
APPLICATION_ENV == 'production') {
        
DEFINE('DB_USER''Andrew');
        
DEFINE('DB_PASSWORD''Password1');
        
DEFINE('DB_HOST''localhost');
        
DEFINE('DB_NAME''AndyDB');
        
DEFINE('EMAIL''andy@somemail.com'); 
        
DEFINE('BASE_URL''http://localhost:80/AndysProject/');
} else {
        
DEFINE('DB_USER''user2');
        
DEFINE('DB_PASSWORD''Password2');
        
DEFINE('DB_HOST''www.some.com');
        
DEFINE('DB_NAME''db2');
        
DEFINE('EMAIL''host@someother.com'); 
        
DEFINE('BASE_URL''http://andyshost.com/');

//in your vhosts file

Code:
<VirtualHost 10.0.0.253:80>

    DocumentRoot "/Path/To/Folder"
    ServerName helloworld.local

    # This should be omitted in the production environment
    # Or set to 'production'
    SetEnv APPLICATION_ENV development

    <Directory "/Path/To/Folder">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

</VirtualHost>
This way, you can configure a whole host of different application environments. Useful for multiple developers all with their own way of setting up their DB's, passwords, paths, whatever etc.
idalatob is offline   Reply With Quote
Old 12-17-2012, 10:55 AM   PM User | #3
idalatob
Regular Coder

 
Join Date: Sep 2007
Location: Grahamstown, South Africa
Posts: 237
Thanks: 6
Thanked 17 Times in 17 Posts
idalatob is on a distinguished road
Not that andrew's way isnt awesome! Just chipping in.
idalatob is offline   Reply With Quote
Old 12-18-2012, 12:26 AM   PM User | #4
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Is APPLICATION_ENV specific to certain frameworks or servers? But I suppose it can be assigned in any comparable settings file.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS

Last edited by AndrewGSW; 12-18-2012 at 12:28 AM..
AndrewGSW is offline   Reply With Quote
Old 12-18-2012, 07:19 AM   PM User | #5
idalatob
Regular Coder

 
Join Date: Sep 2007
Location: Grahamstown, South Africa
Posts: 237
Thanks: 6
Thanked 17 Times in 17 Posts
idalatob is on a distinguished road
Its a bit hitched from the Zend Framework.

Its not specific to any particular framework or server. (I suppose you would have to have apache and use virtualhosting)

Whats really cool about this system, is you can chain settings. EG:

Developer
setting_1 = x
setting_2 = y
setting_3 = z

Developer : Developer_1
setting_3 = a
setting_4 = i

So setting something like, APPLICATION_ENV = Developer_1, you can then chain settings and use inheritance. Like css I suppose. Of course, you have to write the logic for all that.

Its also worth taking a look at how big frameworks etc handle their settings. I really like the zend framework approach, which is why I hacked off its setting system.
idalatob is offline   Reply With Quote
Old 12-18-2012, 11:21 PM   PM User | #6
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,513
Thanks: 45
Thanked 439 Times in 428 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
I see my idea has been copied
http://www.codingforums.com/showthread.php?t=247091

Use the $_SERVER['HTTP_HOST'] to determine which system your script is running on. That way you don't even need to set anything to true or false, no constants to define etc.

Just upload all your files (including your mysql config file with no changes for once) and it'll just work straight away. It supports various names / domains for each server (handy if you have subdomains) and can be adjusted for mysqli if needed:

PHP Code:
//Require the file
require_once('mysql.php');

//Open connection and select DB
$MySQL run_mysql($_SERVER['HTTP_HOST']);

//Or
run_mysql($_SERVER['HTTP_HOST']);

//Need to debug this mysql connection? - Set the second parameter to true.
run_mysql($_SERVER['HTTP_HOST'], true); 
This is the mysql.php file:
PHP Code:
 <?php
function load_mysql()
   {
   
//Set Mysql connections here:
   //MySQL Server 1 - Localhost
   
$Mysql['Name'] = array('127.0.0.1''localhost''<computer_name>''192.168.0.1');
   
$Mysql['Host'] = 'localhost';
   
$Mysql['User'] = 'root';
   
$Mysql['Pass'] = 'password';
   
$Mysql['DB'] = 'your_database_name';
   
$Connections[] = $Mysql;
   
   
//MySQL Server 2 - The website
   
$Mysql['Name'] = array('www.your-site.com''yoursite.com''sub.your-site.com');
   
$Mysql['Host'] = 'localhost';
   
$Mysql['User'] = 'your-site-mysql-user';
   
$Mysql['Pass'] = 'password2';
   
$Mysql['DB'] = 'db_name';
   
$Connections[] = $Mysql;

   return 
$Connections;
   }

function 
get_mysql($Name)
   {
   
$Connections load_mysql();

   foreach(
$Connections as $Key => $MySql)
      {
      if (
is_array($MySql['Name']))
         {
         if ((
$Search array_search($Name$MySql['Name'])) !== false)
            {
            return 
$MySql;
            }
         }
      else
         {
         if (
strtolower($Name) == strtolower($MySql['Name']))
            {
            return 
$MySql;
            }
         }
      }
      
    die(
"Database connection for $Name not defined / established.");
   }

function 
run_mysql($Name$Debug false)
   {
   
$Connection get_mysql($Name);

   If (
$Connection != NULL)
      {
      If (
$SQL = @mysql_connect($Connection['Host'], $Connection['User'], $Connection['Pass']))
         {
         
//MySQL Connection Success
         
$Output "Connected to $Connection[Host]<br>\n";

         If (
$Connection['DB'] != '')
            {
            
$Output .= "Database $Connection[DB] supplied<br>\n";

            If (@
mysql_select_db($Connection['DB']))
               {
               
//Table Selection Success
               
$Output .= "Selected $Connection[DB]<br>\n";
               }
            else
               {
               
//Table Selection Failure
               
$Output .= "Database not selected: " .mysql_error() ."<br>\n";
               }
            }
         else
            {
            
$Output .= "Database not supplied<br>\n";
            }
         }
      else
         {
         
//MySQL Connection Failure
         
$Output "Not connected to $Connection[Host]: " .mysql_error() ."<br>\n";
         }
      }

   if (
$Debug)
      {
      print 
$Output;
      }
         
   return 
$SQL;
   }
?>
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.

Last edited by tangoforce; 12-18-2012 at 11:28 PM..
tangoforce is offline   Reply With Quote
Old 12-19-2012, 04:10 PM   PM User | #7
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
I see my idea has been copied
Cheek . It's not quite the same anyway.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-20-2013, 04:36 PM   PM User | #8
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,513
Thanks: 45
Thanked 439 Times in 428 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
You're right, it's better - no need to tell it what server your on as it picks the correct SQL credentials automatically

No need to manually adjust a define statement, no need to change anything really, just upload everything and you're done (You can probably tell I like automation lol)

The only thing mine won't do is work with cron (for obvious reasons being that there is no domain supplied by a http header). That should be relatively easy to overcome though - you could change the script to work from a machine name instead in the $_SERVER array.
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Old 01-20-2013, 07:41 PM   PM User | #9
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
You're right, it's better
Thank you
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 02-10-2013, 08:34 PM   PM User | #10
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,513
Thanks: 45
Thanked 439 Times in 428 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
lol
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:37 AM.


Advertisement
Log in to turn off these ads.