A page on my web site is taking too long to load – about 2 seconds. After using microtime throughout the code I have worked out where it is taking too long and request help on how to speed it up.
The code I use for finding times is
echo "<BR>3 - ".(microtime(true)-$startTime); #How long it takes for this page to do
$sqldb=open_database(); #Open the database
echo "<BR>4 - ".(microtime(true)-$startTime); #How long it takes for this page to do
and my results are
3 - 5.1140758991241
4 - 6.1172299385071
So from this I deduce that the function to open the database is taking 1 second.
The function used to open the database is
//This function is to open the database
function open_database() {
//Now we will connect to the database
$sqldb=mysql_connect($_SESSION['hostname'], $_SESSION['dbusername'], $_SESSION['password']) OR die ('Unable to connect to database! Please try again later.');
mysql_select_db($_SESSION['dbname'], $sqldb); #Select which database we wish to use - in this case the customer one
if(empty($sqldb)) { //If there is no database then we have an error - MASSIVE ERROR!
header('Location:'.$_SESSION['web_site'].'/error.php');
die();
}
return($sqldb);
}
Note that SESSION varibles are used in the mysql_connect so I only have to change one variable when I update to the production server. Hostname is ‘locaLhost’ on the pre-production server.
So my question is – Why is opening the database taking so long? Please note that because I am in pre-production stage the database is very small.
Sessions are stored in the file system and reading from the file system also takes time. If they were stored in the php code then they would be immediately available to the script. That’s probably part of your problem.
Let me offer a possible solution. Create 2 new files.
dbconfig.prod.php
dbconfig.dev.php
Put your database configuration information into each of these files for the correct environment. On the dev server symbolically link dbconfig.dev.php to dbconfig.php on the production server symbolically link dbconfig.prod.php to dbconfig.php Then in your version control ignore dbconfig.php
Now you don’t have to do something non standard like sessions for database config storage, and it may solve your timing problem. Though IMO 1 second is not a while lot of extra time.