Sunday, May 10, 2009

PHP 301 redirect

301 redirect means "moved permanently"

Every website has to have SEO onpage. That means sometimes you need 301 redirects, when you want to replace some url with a new url. How do you get 301 redirect in PHP? Using header function.

Here is a simple example:

header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$new_location);
exit();

This code must be used in the old file, that you want to remove from search engines. $new_location is the new path where the script is being redirected. exit() must be used to stop the script.
Remember to not display anything (any HTML or other text sent to browser) before calling header() function. Or if you do, you can use output buffering to clear the output.

Monday, May 4, 2009

PHP include path

How to set include path



Include path separator differs from one operating system to another. For Windows path separator is ; and for unix separator is :. So how do you make your code create the right include path regardless of your OS?

First, you detect server's OS:

if (stristr(PHP_OS, 'WIN'))
{
$separator = ';';
}
else {
$separator = ':';
}

Then you set your classes path, for example:
$yourpath = './classes';

And then you add this path to include path:

ini_set('include_path', ini_get('include_path') . $separator . $yourpath);

This way, either your server is Windows or a Unix system, it will always include your path using the right separator character, and you don't have to change the code everytime you switch to another OS.