What is wrong with having a dynamic configuration file in PHP? - php

I have recently taken to converting my websites files into ones that work on any path. I am working on using Virtual Hosts to be able to maintain the same .htaccess file as on the main production server. My initialize file that includes all my models is written dynamically to find out the exact system file path and update the website accordingly so I can upload the whole website anywhere.
The trouble lies in the config file. Depending on whether I am on dev or on prod, I connect to a differert database. Therefore I have a small check first to see if I am running a local server. I do this by storing my naming conventions for my dev in an array and by looping through the array to see if the HTTP_HOST matches a value.
Example:
$dev_names = array('localhost','.dev');
However, when I mentioned this on Chat the other day, a respected user told me that he never does this. Instead he has 2 config files and includes the right one at the right time? I didn't get though what was wrong with my approach?
Can you point out to me the flaws in my plan to help me understand the experts?
(PS. For a bonus you can give me a quick run down on how a bootstrap works, heard that word being thrown around, not sure if it is written in PHP or whatever.)

I dont see anything wrong with your approach, and I cannot think of a good reason not to do it.
Personally I do this in my php file;
if ($_SERVER['SERVER_NAME'] == 'localhost')
{
define('ENVIRONMENT', 'development');
}
else
{
define('ENVIRONMENT', 'production');
}
And then all my configs hang off that. Works extremely well - means I literally have zero config changes when moving between Dev & production

I suspect what he was getting at is that your attempt to make your site portable isn't in fact all that portable. If you move it to a new server you'll have to edit your configuration file.
Specifically this becomes an issue when you're checking the config file into some sort of version control system and will be affecting someone else.
Ideally, you'll use something like this:
<?php // global config file which is checked into VCS
$SETTING = "FOO";
#include "config/local_settings.php"; // overrides go here
?>
You put all your local setting overrides in the local file, and don't commit it to the VCS. It's perfectly common to commit something like local_settings_example.php though, to give other users a heads-up as to what they need to customise. You can fill it with commented examples if you're feeling generous.

I can only throw in my 2 cents on a setup I prefer. Mainly to avoid undesired version control overwrites or conflicts. To my point of view, it is the server that should decide if it's a production or development server, not a variable in a script that should be changed. An approach like the example below make it even possible to set an environment for an individual on a complete different development setup.
Starting by setting the variable
$_SERVER['SERVER_ADMIN'];
to check for production or development environments. Locally to your own name with a dummy domain like #dev.elop.loc (e.g. dbf#dev.elop.loc) that would never exist for real. A function like so
// environment development check
function __env_dev($check) {
return substr($_SERVER['SERVER_ADMIN'], -(strlen($check))) === $check;
}
// false = production
// true = development
__env_dev("#dev.elop.loc");
can determine the environment. To my experience, production servers always have a SERVER_ADMIN variable set (if not, they really should, even if it has to be the default you#example.com) to a real address, avoiding default you#example.com. If the support for the live server is in your own service/maintenance, it's not a big deal changing it to a real address to distinguish it from a development server ;)

Related

Setting Bolt Configuration Per Environment

The Bolt documentation mentions setting up configuration files for each environment, but doesn't explain how to make it happen.
When you have multiple environments for the same site, like development, staging, or production, you’ll want parts of the config to be the same, and some different per environment. You’ll probably have different database info and debug settings. This can be accomplished by splitting the config.yml file. Put all settings you share over all environments in the default config.yml, you can commit this in your version control system if wanted. Every setting which is different per environment, or which you do not want in version control (like database info), you put in config_local.yml. First config.yml is loaded and then config_local.yml, so that config_local.yml can override any setting in config.yml.
Of course I have no problem creating an additional config file, but how do I tell Bolt which environment it's running in and which file it ought to load?
Turns out Bolt is completely unaware of its environment. It always loads config.yml followed by config_local.yml, regardless of domain name.
From Config.php, starting at line 226:
protected function parseGeneral()
{
// Read the config and merge it. (note: We use temp variables to prevent
// "Only variables should be passed by reference")
$tempconfig = $this->parseConfigYaml('config.yml');
$tempconfiglocal = $this->parseConfigYaml('config_local.yml');
$general = Arr::mergeRecursiveDistinct($tempconfig, $tempconfiglocal);
The solution to my problem is to never allow config_local.yml to get deployed.
The config_local.yml file is intended for development use so that you can override configuration setting that might be committed to your VCS in production use.

Wordpress Importer showing blank page after clicking the Upload File and Import button

I have been trying to import an .xml file from my old WordPress to a new one. I have the following settings in php.ini:
upload_max_filesize = 64M
post_max_size = 90M
memory_limit = 128M
But when I click on the Upload File and Import button Im getting a blank page. No errors or anything.
Anyone has any idea how to solve this? Thanks.
UPDATE:
After turning on the error display which was suggested below I was able to get the following error:
Fatal error: Class 'DOMDocument' not found in /var/www/html/wp-content/plugins/wordpress-importer/parsers.php on line 61
which I was then able to fix by installing php-xml.
This question in its original form did not provide enough information to justify actually trying to guess the solution.
Therefore I felt the most relevant answer was some general troubleshooting steps that may shed more light on a similar situation - my focus is on tips that may help in this particular situation, but since it is going to be rather lengthy anyway I do include some more general tips as well.
The OP is not actually asking for alternatives to the wordpress import / export function, but since this is a migration gone sour (plus the fact that the wordpress import / export feature leaves a lot to desire), I will try to answer Alans question regarding alternative ways to migrate wordpress between servers / locations / domains as well.
At risk of stating the obvious: This answer is going to be long!
Debugging wordpress errors in general
Step 1. Make sure you can see what goes wrong
Enable debug mode, and make sure display_errors is enabled, and an appropriate error_reporting level is defined. This is vital to any wordpress development.
Open wp-config.php and find this line:
define('WP_DEBUG', false);
Replace it with:
//Switch on wordpress' built-in debug mode
define('WP_DEBUG', true);
/**
* Just a convenient check so you can leave the next few lines unchanged
* for next time you need debugging, and just switch true/false above.
*/
if (WP_DEBUG) {
//Handle all errors regardless of error level
ini_set('error_reporting', -1);
//Display errors directly in the browser
ini_set('display_errors', 'On');
}
...if for some reason the line isn't there already, just insert it somewhere above the line saying.
/* That's all, stop editing! Happy blogging. */
This should allow you to see some more information about most (php-)errors.
Notes:
In most cases, simply setting WP_DEBUG to true will automatically enable display_errors - however I have found the above to cover some edge cases where errors where not shown in spite of WP_DEBUG being true.
On a live (production) site it may be very undesirable to display errors to every visitor, so you may want to:
enable WP_DEBUG conditionally, for example by IP: define('WP_DEBUG', $_SERVER['REMOTE_ADDR'] === '123.123.123.123'); (obviously substituting your actual IP)
log errors instead of displaying them - see the wordpress codex for more information: Debugging in WordPress
If you have low-quality or outdated plugins or themes installed you are very likely to see a lot of output from poorly written functions within those.
If you do see errors referencing one of your plugins as soon as you enable debug mode my recommendation is to either contact the plugin developer regarding the issue, or simply uninstall the plugin and find another one that satisfies your need. Plugins from developers who didn't even care to use debug mode during development are highly likely to also contain security issues and / or be sub standard with regards to future- or third-party compatibility.
Step 2. Reproduce the error
Whatever you did to make the problem happen - do it again. This should give you something to work with, for example by simply pasting it on google and see what comes up. Chances are you're not the first to experience whatever problem your are having.
If you still get no visible errors try to right click the "nothingness" and view the page source in a plaintext editor. Sometimes errors can be hidden inside an attribute, or behind an element on the screen.
You can also try to insert some intentionally broken code in wp-config.php to confirm that errors will in fact be printed. For example type this_function_surely_does_not_exist(); right after the ini_set() directives.
Some hosts restrict the use of ini_set(), so if things still aren't working, but you do not see any errors try to find out how you can set the relevant php.ini settings - it may be in your hosting providers control panel (cPanel, Plesk etc.), you may have direct access to your php.ini via FTP... or they may offer no way to set it (find a different provider at once!)
It is also possible that you cannot change the value, but errors are logged somewhere in your providers panel by default.
If you get a completely white browser window it is likely that you have a fatal error somewhere - or a configuration problem on the server itself. This is outside the scope of this answer, so if the suggestions regarding increasing limits in the next section doesn't work, try to google "WSOD" to get started.
Find actual limits and settings
Do not trust that just because you have a file called php.ini that contains a line saying memory_limit = 128M your memory limit is actually 128M. This can be set in so many different ways that the only reliable way to know is to ask php what its current memory limit is. This is true for most php.ini-settings!
To get a fair idea what your working environment looks like create a file (preferably in the root of your wordpress install) called phpinfo.php, with the following content:
<?php
//Your memory limit
echo 'memory_limit: ' . ini_get('memory_limit') . '<br>';
//Your maximum size of post-data (including file uploads)
echo 'post_max_size: ' . ini_get('post_max_size') . '<br>';
//The maximum file size for uploads
echo 'upload_max_filesize: ' . ini_get('upload_max_filesize') . '<br>';
//Maximum runtime for php scripts (in seconds)
echo 'max_execution_time: ' . ini_get('max_execution_time') . '<br>';
//Current error reporting level
echo 'error_reporting: ' . ini_get('error_reporting') . '<br>';
//Are errors displayed?
echo 'display_errors: ' . ini_get('display_errors') . '<br>';
//Will errors be logged?
echo 'log_errors: ' . ini_get('log_errors') . '<br>';
//Where will errors be logged?
echo 'error_log: ' . ini_get('error_log') . '<br>';
//What is the absolute path of this files parent folder
// = the complete path to your wordpress "root folder"
echo 'root of wordpress: ' . __DIR__ . '<br>';
/**
* If you are curious to see *a lot* of information about your environment
* then uncomment this line too:
*/
//phpinfo();
/**
* This should print whatever is in the error log, but it could potentially
* be huge, so use with caution!
*/
//echo '<pre>' . file_get_contents(ini_get('error_log')) . '</pre><br>';
You should be aware that all of the above values can be changed during execution of a script - and some (poor quality) plugins actually will. I've seen plugins try to increase the memory_limit for instance - which is all fine and dandy, except 6-7 years pass, and a plugin "increasing" the memory limit to 32MB actually messes up the installation, because nowadays 64MB is needed for a pretty basic wordpress install, and 128MB would be a more reasonable minimum for most. The problem with this is that the only way to actually know the values for sure at any given point of execution is to insert the above right at that point.
Some very common reason for errors that happen "on occasion", particularly in connection with imports or file uploads is that either memory_limit, post_max_size or upload_max_filesize is set too low - you can try to increase them using ini_set() calls in wp-config.php:
ini_set('memory_limit', '256M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '64M');
Again your host may completely prevent you from affecting your limits using these functions, but may provide another way for you to set them.
If that doesn't work either, try disabling as many plugins as possible, and as a last resort switch to a default theme - but be prepared to lose widgets and a bunch of settings if things get to that.
If you're still stuck at square one ask a question on Stack Overflow, and be very verbose about exactly what you did before it all went south ;)
Cloning / Migrating / Moving or Backing up a wordpress site
There are a lot of backup / migration plugins out there. If you are inexperienced working with files, databases and the like your best bet is probably to go with one of those. I will not recommend any specific plugin as changes are too frequent and I personally always do it manually - a google search should yield plenty of relevant results though, and I'm sure many of them can get the job done in most situations.
However, if like me, you prefer to do it manually to understand (and control) the process, here is the method I use to move, rename, clone or back up wordpress installations routinely - it should work for almost any standalone installation (ie. if you're trying to move a multisite you should probably go look for another guide).
These instructions should work whether you are
migrating from one server to another - for example development to production
migrating from one domain to another
migrating from a sub-folder to the domain root (or the other way)
taking a backup (just stop half way through the process, and continue where you left off if you ever need to recreate your backup)
The basic steps are:
Get a copy of all files
Get a copy of the entire database
Do necessary corrections in files
Upload files to new server (or same if you are restoring a backup)
Load up the database on the new server
Do necessary corrections in the database
This requires that you have access to:
Your files, for example through FTP or perhaps your hosting provider has a tool that can create an archive containing all your files.
Your database, for example through phpMyAdmin or any tool that can make a complete database dump for you.
All decent hosting plans, and nearly all inexpensive shared hosting plans come with phpMyAdmin and FTP access. VPS', private servers etc. obviously comes with direct file and database access which will be even better (or at least faster).
If you do not have access to the above wherever your site is hosted, it is likely because you bought your site from someone who does not want you to move it away (usually because they designed your website for free or at a very low cost, and need you to stay with them to get back their investment). If that is the case you can try one of the many backup / migration plugins, but chances are they don't even allow you to install plugins, so you'll have to contact them and work out some agreement instead.
(if you do not have access to your database, but you do have access to your files you can install phpMyAdmin yourself - but how to do that is way outside the scope of this answer)
Note that depending on what operation you are actually doing, some steps can be skipped - which you can feel free to do once you understand the process, and why each step is (sometimes) required - but if this is your first time just start from the top and work your way through each step.
Step 1. Get a copy of all files
You'll want to get all files in the "root" of your wordpress installation. That is the folder containing wp-content, wp-admin and wp-includes plus about 15-20 files. Make sure you get hidden files too (for example the file .htaccess will likely be hidden by default if you use FTP - in some cases this file is completely irrelevant, but in others it can be essential, so just make sure you get everything)
If your hosting provider has some sort of file manager you may want to try that first. A lot of file managers offer the option to up- or download folders as a single compressed archive - which will be a lot faster than downloading all files individually.
If you have a VPS or any solution with SSH or some other form of console access, use that and navigate to the "root" of your installation, then zip everything up - something like zip -r my_wp_backup.zip . should do. Download the file using whatever means you have.
If you only have FTP access to your files, it may take a while, but you simply log in with FTP (my favorite FTP client is FileZilla, because it's easy to use, and allows several simultaneous transfers... but any client should be fine). Navigate to the "root" of wordpress and transfer all files to a local folder on your computer (don't forget to show hidden files!)
Step 2. Get a copy of the entire database
If you have access to phpMyAdmin through your provider use that - it is by far the easiest, and I have never had a problem, except with extremely special databases or extremely old versions of phpMyAdmin.
Just log in to phpMyAdmin, select your database, click export and accept the defaults (options are very different depending on the version, but the defaults should be fine for any "normal" wordpress database). This should give you either a file download with a name ending in ".sql" - or a big text-field with huge amount of text in it. If you get the latter just copy it to a regular text file on your local computer - notepad, notepad++ or any other plain text editor will work (ie. don't use word, google docs or any other rich text editor!)
If you don't have access to phpMyAdmin you can either install it (which I'm not going to describe), or you must find some other way to export the database, for example:
If you have console access this command should give you a usable dump: mysqldump -u your_database_username -p your_db_name > my_backup.sql - if you don't know the name of your database, take a look in wp-config.php (also contains your username and password if you don't know those)
If you don't have console access either go explore your providers control panel - surely they have some way to let you make a database dump.
Step 3. Do necessary corrections in files
You should now have a complete backup on your local disk.
If you are just doing a backup you're done - the files and database are ready to be uploaded to the same location, and everything will be restored to the current state.
If you are moving to a different server or a different location on the same server find out:
what your new path is (upload the phpinfo.php file above if your provider doesn't give you any clues)
what your new database username and password is
if you need a special hostname to connect to the database (localhost is sufficient in most cases, but some providers have dedicated mysql-servers that require you to connect to some other hostname)
Correct your wp-config.php file - the relevant lines are:
/** The name of the database for WordPress */
define('DB_NAME', 'your_database_name');
/** MySQL database username */
define('DB_USER', 'your_database_username');
/** MySQL database password */
define('DB_PASSWORD', 'your_database_password');
/** MySQL hostname */
define('DB_HOST', 'localhost');
Though it's rather rare some plugins do write information in files that needs to be updated, so if the absolute path of your wordpress root folder, or the absolute URL of your installation is changing in the process of migrating you should also do a complete search and replace for those:
If the old absolute path of your installation was /var/www/www.example.com/web/blog and your new absolute path is /var/www/blog.example.com/public_html then search-and-replace those throughout all files. Do not include a trailing slash!
If the old URL was http://www.example.com/blog and the new URL is going to be http://blog.example.com do a search for www.example.com/blog replacing with blog.example.com. Do not include http:// and do not include a trailing slash!
Note that if for some reason you are in a situation where you do not know your old absolute path and / or URL you can find them in the database, so do step 5 first, and look in the prefix_options table for the values siteurl (your absolute URL) and upload_path will usually contain your absolute path (plus /wp-content/uploads) - if it doesn't then there will probably be other rows in the table that can tell you what the path was, look for something that starts with /var/www or /home/something.
Step 4. Upload files to new server or new location
As in step 1 your options may vary, but the point is to get all files uploaded to whatever folder is going to be your new root. Use whatever means you have available to do so.
Do not give in to the temptation to "try" the site out after uploading files - though unlikely it can have unforeseen consequences if you visit before all steps are completed!
Step 5. Load up the database on the new server
Again, options vary:
If phpMyAdmin is available simply log in, select your database, click import and upload the file from step 2. Sometimes I even click the SQL tab instead, and just paste the entire content directly in the big text field.
If you have console access you can upload the file and run mysql -u your_database_username -p your_new_db_name < my_backup.sql
Step 6. Do necessary corrections in the database
If you're restoring a backup to the same server and location you are done.
However, if you are migrating to a different server or a different URL you need to be aware that Wordpress itself, as well as a lot of plugins writes your absolute URL in a lot (thousands) of places in the database, and your absolute path is likely to also be present in at least a couple of rows.
You also need to be aware that a lot of plugins, as well as some core wordpress functions use the php function serialize to store complex data easily in the database. That format is very sensitive to changes, so a "regular" search and replace is very (very!) likely to break everything.
Luckily there is a free tool specifically designed with this in mind. I have no affiliation, but I cannot recommend interconnect/it database search and replace enough. It is well-maintained, super user friendly, and I have never personally experienced it mess anything up.
Download it using the link above, unzip it, rename the folder to something_random_for_security and upload it to your wordpress root folder. Then go to http://blog.example.com/something_random_for_security in your browser (obviously substituting relevant parts of the URL).
You'll be presented with a neat graphical interface, and it has probably already filled in your database details for you (by reading your wp-config.php).
At the top of the screen there's a search field and a replace field. Don't mess with anything else, unless of course it actually failed to get your database information automaticall.
Like for files you need to search for:
your old absolute path and replace with your new absolute path (excluding trailing slash)
your old absolute URL and replace with your new absolute URL (excluding protocol http:// and trailing slash)
You can use the "Dry run" button first to see what will be changed, and if any obvious problems might arise - after that just click the "Live run" button and it'll chew through your entire database replacing in a serialize()-safe way where relevant.
Step 6,5 Broken permalinks
If you have moved your site from one folder to another folder (or up or down a level), then permalinks / "pretty URLs" may not work (ie. your front page is fine but everything else is one big error). This is because of the rules in that "hidden" .htaccess-file getting "confused". The fix is very simple - just visit the "Settings" -> "Permalinks" in the wordpress admin... you don't need to make any changes, the file is automatically refreshed as soon as you visit the page.
Done
Check that everything works, then go celebrate...
Your directives are in the wrong format. Try
upload_max_filesize = 64M
post_max_size = 90M
memory_limit = 128M
max_execution_time = 120
If those don't work, ask your webhost; you may not be able to make changes in php.ini.
And try running debug https://codex.wordpress.org/Debugging_in_WordPress to catch PHP errors that may point the way to the issue and solution.
The only way to find out what is causing the blank screen is check your server error log.
And also take reference from here
try this,after making the necessary changes for uploading a file in php or wordpress i.e
post_max_size = 90M
max_execution_time = 120
upload_max_filesize = 64M
memory_limit = 128M
other steps,
1)Increase the PHP memory limit via .htaccess (e.g. php_value memory_limit 64M)..
2)Increase the PHP memory limit via wp-config.php (e.g. efine(‘WP_MEMORY_LIMIT’, ’64MB’);)
finally check,
https://codex.wordpress.org/Importing_Content
These steps may help:
After showing the blank page, the page keeps running in background (you can see this in flight by refreshing the wp_posts table or wp-admin)
Inside wp-includes/deprecated.php there is a function named wp_get_http() with #set_time_limit( 60 );, change this to 0 to disable limitation.
This worked for me:
No images imported
Wordpress Tools > Export did not attach images even though settings state it to be true. The import process on the target site crashes. To fix that I installed the DeMomentSomTres Export plugin on the exporting site that forces the import process on your target site to make a connection to the export site and then pull the images over. That worked well.
No content when editing
However, when editing the imported posts, the content wysiwyg editor box appeared empty even though the text would display on the front end. Initially I thought it was a database issue. Then, I tried deactivating Classic Editor plugin and edited a post. Whaa-la the content appeared in edit mode. Next, after re-activating Classic Editor plugin, the content stuck. All good.
I got the same behavior today while exporting All Posts and Media from a client site using the usual WordPress Importer.
I tried changing the PHP.ini settings suggested in other answers, but that didn't help probably because they can't be overridden. Importer will stop showing the loading icon after 1 minute or two. No errors appeared even when I set DEBUG to true.
However, when I checked the wp-content/uploads folder I could see some of the folders and images were uploaded (check modified date) yet the execution timeout stops the importer before it can finish.
My solution was to keep importing the same file again and again until the whole thing is finally imported. This works fine because WordPress Importer won't import a Media or a Post again if it's already imported/exists.
So even if there is a timeout setting you can't change, multiple attempts will get it done unless you have huge media files exceeding max file size.
Of course, if it's a huge amount of images you should find another solution.

Is there a setting that allows php variables to be set in an included php script and then reused in the main file?

I have just checked out a project from an SVN and have tried to run the project on my local machine using WAMP and virtual hosts. I'm getting a lot of errors saying variables have not been declared and after further investigation have found that they are set in separate PHP files and then have been included into the page throwing the errors.
This works absolutely fine on live but not on my local which makes me think it must be a PHP setting. I've looked in the PHP.ini file but don't really know what I'm looking for.
There are two things I would like to know...
Firstly is there something I can adjust in my PHP.ini file to solve this and secondly, is it a good idea to have this setting(should there be one), as I have always worked with PHP variables, private to the page unless setting a $_SESSION variable.
Hope this makes sense to someone.
I should also mention I'm using windows and the server that runs the file is using Linux.
Thanks in advance
my guess is: your local and remote server have two different include paths set. you can check that by looking at the output of get_include_path()
then, check if paths are correct, you might want to check paths of these files
are they in the same directory? if no, are the paths in include relative or absolute? and how are the paths defined? these info will help you to get your answer. no php.ini setting can probably help you here.

How can we check if we are running the PHP script on localhost?

Is there a way to check if we are running a PHP script on localhost - development server or on live server - production server? Is there any PHP constant, variable, function,etc that can give me this information.
I need this to put different settings for production and development server. Now I parse the URL to see which one it is but I was wondering s there any better way to do that. My concern is that we may change the URL of the script and that may ruin my check.
I am looking few a solution with one config file and IF condition in it depending on which I will define different settings. The only problem is that I do not want to change the IF statement when there are changes on the server settings like hostname, document_root or something else that I am using to identify local/remote host.
And want to SVN update from one source without changing anything to my production server.
And I would like ideally to be able to run and CRON jobs with these settings.
I use the SetEnv in my host definition to locate on which environment i am running (Dev, Stage, Production) :
<VirtualHost *:80>
(all the host info)
SetEnv SERVER_CONTEXT "dev"
</VirtualHost>
And each config file as an extra word in it : config.dev.ini, config.stage.ini, config.prod.ini, etc, ...
It works like a charm.
if($_SERVER["REMOTE_ADDR"]=="127.0.0.1"){
$local = True;
}else{
$local = False;
}
EDIT
You could also check the first part of the address and see if the server is in the local network, the again assuming your server won't be in the local network when in production
I set an environment variable in the Apache configuration and check that. This has the advantage over using a PHP configuration file that all your application code remains exactly the same on PROD, TEST, DEV etc; no need to go and make changes after a check out, as the code just pulls the config from Apache.
To demonstrate, the following can be set in your VirtualHost configuration
SetEnv ENVIRONMENT PROD
In your PHP code, you can then check the environment with
$env = getenv('ENVIRONMENT');
If you feel the need to make this available everywhere, you can then use define, but I don't find it necessary (I use the specified environment to load the appropriate configuration files and create a read-only Singleton configuration, which is then used to check any configuration options; better than if ($env == 'PROD') {} type code, as all that logic is in the config, not in your code).
Use a config file you include with a define in it
define("DEBUG",true); //set to false for live
and use that in your code, e.g.:
if(DEBUG){}
You can try and use the global $_SERVER['SERVER_NAME'] This should tell you the host name of the system that's running the script. You could use this to determine what settings to use (depending on the system).
I don't know that this will output 'localhost' however and you may need to know your actual host name of your development machine.
The server has no idea what environment it is unless you tell it to. What I do is use DEFINE to set the environment. My application code is the same on every instance but the my configuration files change. That way you can use .htaccess file include the configuration files on every script and check to see what they settings are.
I know this word may sound strange to PHP developer, but have you considered build of your project?
In PHP there's nothing to compile, however changing copied files is one of features of any build process. You could specify 2 targets: production and dev. There would be no need for any conditionals, that should work, or may work, but under some circumstances won't.
i always make "config.php" wich i include to other php files...
it contains something like (home file):
$CONFIG['server']="dev";
$CONFIG['db_user']="root";
and thing like that...
so at home i have this one up there and at server where site is running i have another one wich i dont update if not changes to it...
so on server i have something like:
$CONFIG['server']="prod";
$CONFIG['db_user']="lwu9918_admin";
and then in other php files:
include("config.php");
if($CONFIG['server']=="dev"){echo "Development";}
thing like that!
On dev server
* * * * * php -r cronjob.php this_is_dev
On production server
* * * * * php -r cronjob.php this_is_live
In your script
switch ($argv[1])
case 'this_is_dev':
// load your dev configuration
break;
case 'this_is_live':
// load your live configuration
break;
default:
die('invalid server');
break;
}
since is meant for cronjob, the $argv is exist
good luck with Windows :(
you better put the cli running program outside www directory ,for example
c:\iis\www is the public html directory
the cli file should be put under c:\iis instead

What is the best way to determine which server the script is on and therefore the configuration in PHP?

I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on.
At the moment I have a switch() that uses $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] to determine which server it's on. It then sets a few paths, db connection parameters, SMTP paramters and debug settings based on which server it's on. (There maybe additional parameters depending on the site needs.)
This means that I can simply drop the site onto any of the configured servers without having to change any code (specifically the configuration). If it's a new server, then I simply add a new case and it's ready from then on.
We have done loading config files based on the same SERVER_NAME:SERVER_PORT combination, but found that it's another file you have to maintain, plus we weren't sure on the speed of parsing ini files, (although having extra cases for each server may be just as slow).
Another problem we have is when a site is often moved between 2 servers, but we use the same SERVER_NAME and SERVER_PORT on each. This means we need to temporarily comment one case and ensure it doesn't get into the repo.
Another other ideas? It needs to be available on all servers (sometimes SERVER_NAME and SERVER_PORT are not). It would also be nice if it worked with the CLI PHP.
How about using $_SERVER['SERVER_ADDR'] and base your identity off the IP address of the server.
UPDATE: In a virtual host situation, you might also like to concatenate the IP with the document root path like so:
$id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT'];
We use the $_SERVER['HTTP_HOST'] variable to create the filename of a PHP include file which contains all the vhost-specific information (we deploy the same software to a lot of vhosts)
I like this technique, as you can get clever with it to build hierarchies of configurations, e.g. for www.foo.com,
try to load com.config.php
try to load foo.com.config.php
try to load www.foo.com.config.php
Doing it this way lets you set options for all your live sites globally, and tweak individual sites on as as-needed basis. We have our own internal root domain name for developer sandboxes too, so we can enable all the developer level options in internal.config.php
You can also do this in reverse, i.e. try to load www.foo.com.config.php, and only if not found would you try to load foo.com.config.php, and so on. More efficient, but a little less flexible.
Here are some variables you can check:
$_SERVER['HTTP_HOST'];
I use this one for checking which server I'm on when php is running through apache.
$_SERVER['USER'];
$_SERVER['LOGNAME'];
I use these two for when I know I'm running from the console. One of those invariably resolves to a usable username. There seem to be no other host-defining variables in console mode.
This might not help you enough; If you find you still have a hard time being able to uniquely identify what server you are on you can give it a little bit of a "push." In my situation I have a small config file which is unique to each server, basically setting a php variable defining which environment I'm running in (e.g. development or production.) This way you only need to maintain one small, easy to recreate file outside of your source control.
Ive always kept a config.php on my sites, storeing such infomation which may be percificic to that server.
Being php parseing it is nearly (eg the file needs to be opened, closed, etc) as fast as having the code at the top of each script, and much faster than ini and xml config solutions
Centralised location for the sites configuration on each server, so easy to keep upto date (server doesn't change that oftern, updateing the config is simple with an update script).
Can be generated by the script, all my sites have a function that rebuilds the config file useing the $config[] assoc array.
Updates that effect the config file are as simple as "$config['key'] = 'new value';config_update()"
I have been using the following mechanism:
if(__FILE__ === '/Sites/mywebsite.com/includes/config.php')
define('SERVER', 'DEV');
else
define('SERVER', 'PRODUCTION');
My development environment has a rather distinct path structure so this works well, and I don't need to worry if additional domains are added to $_SERVER[HTTP_HOST], or a client that provides an incorrect HTTP_HOST value (although that would be rare ...).
Why don't you have configuration files for each host stored outside of the project directory and read it from the php code?
Having host specific code is not really a good practice.
$posix_uname = function_exists('posix_uname') ? posix_uname() : null;
$this_hostname = !empty($_SERVER["HOSTNAME"]) ? $_SERVER["HOSTNAME"] : $_ENV["HOSTNAME"];
$this_hostname = !empty($this_hostname) ? $this_hostname : $posix_uname['nodename'];
We use environment variables for this (ENVPHP environment variable which will contain the specific server environment - ie. development/test/production). This approach works very well for CLI scripts as well (for CLI you set the OS environment variables, for Apache you can use SetEnv switches in the host configuration). In PHP you access this environment variable using getenv('ENVPHP')...

Categories