Archive

Posts Tagged ‘header’

Creating A 404 Page In PHP

April 2nd, 2008 No comments

Setting up a 404 page on your site will help users when they navigate to a page that doesn’t exist. Rather than dropping them into a scary server message you can give them a nice friendly error page. The first step is to make sure that if the user generates a 404 error they are given a nice page. Add this line to your .htaccess file.

ErrorDocument 404 404.html

Now when a user hits a non existent page they will see you nice error page. However, you sometimes will want to produce a 404 page when the server doesn’t give out a 404 error, for example, if you have the following URL.

http://www.example.com/index.php?id=123

If the id of 123 didn’t exist then the page would still show something, and the server wouldn’t give a 404 error as the page does, in fact, exist. You will therefore need to be clever in your script so that if the id exists you return a normal header, and if it doesn’t you return a 404 header. To produce a 404 header from a PHP script you need to use the header() function in the following way.

header("HTTP/1.0 404 Not Found");

So to integrate this into the rest of the site you would do something like this. The function idExists would be a call to a database or something that checks to see that the id is present on the system.

if(idExists($_GET['id']){
 // run normal page function
}else{
 header("HTTP/1.0 404 Not Found");
 // print off page with not found information
}

Make sure you put the header() function above any echo or print statements or you will produce an error message.

Categories: PHP Tags: , , ,

PHP Page Redirection

March 12th, 2008 No comments

To redirect to a different page using PHP you can use the header() function with the parameter ‘Location: ‘ and the destination of the redirect.

header('Location: http://www.talkincode.com');

However, if any headers are sent before this function call then the script will fail. To get around this you can either ensure that nothing is printed out on the page, or if that is not possible for some reason then you can use a JavaScript redirect. The headers_sent() function will allow you to see if any headers have been sent to the browser yet, if they have then you will need to use the JavaScript redirect like this:

location.href='http://www.talkincode.com';

You will want to redirect a user even if they have JavaScript turned off so you can also put in a noscript tag with a meta refresh tag. A meta refresh is a HTML tag that tells browsers to refresh the page, with the content tag being the amount of time to wait before the refresh. Adding the URL parameter into the content tells the browser to refresh to a different URL, essentially a redirect.

<meta http-equiv="refresh" content="0;URL=http://www.talkincode.com" />

Here is the full version.

$url = 'http://www.talkincode.com';
if(headers_sent()) {
 // redirect using JavaScript if it has, meta redirects if not
 echo '<script type="text/javascript">location.href=\''.$url.'\'</script><noscript><meta http-equiv="refresh" content="0;URL='.$url.'" /></noscript>';
}else{
 // otherwise use the php way.
 header('Location:'.$url);
 exit();
};

It is still possible for a user to stop any meta redirects, this should redirect 99% of users to another page if headers have already been sent, but your best bet is to use the header() function whenever possible.

Force File Download With PHP

February 19th, 2008 No comments

When you supply files that web browsers can open they are usually opened inside the browser, rather than being downloaded. This can be annoying, especially where PDF documents are involved. You could supply the files in a compressed format in order to force users to download them, but this is also annoying as the user then has to uncompress the file.

You can force the web browser to supply the file as a download by using the header() function in PHP. The following little bit of code will take any filename and supply it as a download.

<?php
$file = $_GET['file'];
header('Content-type: octet/stream');
header('Content-disposition: attachment; filename='.$file.';');
header('Content-Length: '.filesize($file));
readfile($file);
exit;
?>

All you have to do is link to this script with the argument being the file name you want your users to be able to download.

<a href="forcefile.php?file=talkincode-image.png" title="Download">PNG Image</a>

Here is an example link that downloads an image.

The benefit of doing things this way means that you can also put some tracking elements into the start of the file to record what and when the file was downloaded.

However, be very careful here. In it’s current state the script will allow users to download ANY file within the directory you have the script in, just by supplying the name. This is a big security feature as a use could get hold of your database password file quite easily. To get around this you can restrict the file type to either jpg, gif, png or pdf by using the following code.

<?php
$file = $_GET['file'];
$ext = substr($file,-3);
if($ext=='jpg' || $ext=='gif' || $ext=='png' || $ext=='pdf'){
 header('Content-type: octet/stream');
 header('Content-disposition: attachment; filename='.$file.';');
 header('Content-Length: '.filesize($file));
 readfile($file);
 exit;
}
?>

Finally, it is best to check to see if the file exists before trying to get users to download it. It is doesn’t then they will get a file full off PHP error codes.

<?php
$file = $_GET['file'];
if(file_exists($file)){
 $ext = substr($file,-3);
 if($ext=='jpg' || $ext=='gif' || $ext=='png' || $ext=='pdf'){
  header('Content-type: octet/stream');
  header('Content-disposition: attachment; filename='.$file.';');
  header('Content-Length: '.filesize($file));
  readfile($file);
  exit;
 }
}else{
 echo 'File not found!';
}
?>

Categories: PHP Tags: , , , ,

Using PHP To Generate CSS

January 31st, 2008 No comments

Generating CSS with PHP has several benefits. For example, you can keep all of your colour declarations as PHP variables so if you need to change any colours it only takes a small edit and not a find/replace operation.

Getting PHP to generate CSS requires just two steps. The first thing to do is to open your CSS file and insert the following line at the top. This tells the browser that the file is CSS.
<?php header("Content-type: text/css"); ?>

The next step is to change the file extension on your CSS file from css to php. This will tell the server to parse the file as a PHP script and not a plain CSS file. This is a necessary step unless you have direct access to your web server and can set CSS files to be parsed as PHP, but I don’t suggest that you do this as it will slow down the server when it serves normal CSS files. Once you have changed the extension you need to change the link to have the same connection.

<link rel="stylesheet" type="text/css" media="screen" href="style.php">

You are now ready to start putting PHP into your CSS files. Take the following CSS file.
body{
  background:#fff;
  color:#333;
}
h1,h2,h3,h4{
  color:#00840;
}

The first thing we might do is to standardise the colour declarations.

<?php
  header("Content-type: text/css");
  $white = '#fff';
  $dkgray = '#333';
  $dkgreen = '#008400';
?>
body{
  background:<?php echo $white; ?>;
  color:<?php echo $dkgray; ?>;
}
h1,h2,h3,h4{
  color:<?php echo $dkgreen; ?>;
}

A better way to use colours is to call the variable by the function rather than the value of the colour. So using the previous example I will rename the colours so that we use the function.

<?php
  header("Content-type: text/css");
  $background = '#fff';
  $text = '#333';
  $heading = '#008400';
?>
body{
  background:<?php echo $background; ?>;
  color:<?php echo $text; ?>;
}
h1,h2,h3,h4{
  color:<?php echo $heading; ?>;
}

Categories: PHP Tags: , , , , ,

Redirecting The Page In PHP

January 13th, 2008 No comments

To redirect the current page to a different location you use the header() function in the following way:
header("http:www.talkincode.com")
You can use this function when you want to point the user to a different page. If you are writing a login script then this function would be useful to show the user a certain page depending on them entering the correct user information.
To send a code along with the redirect (for example, a 301) you can use the optional parameters. The second parameter is a boolean value that determines if this header call should replace any headers of a similar name. For example, if you send a header called "Cache-Control" and then send another header later on with the same name then the second parameter determines if the value is replaced or appended. If the value is true then the previous value is overwritten, if the value is false then the value is appended to the list of headers being sent.
The third parameter is the code to be issued along with the header. So to create a 301 redirect do the following.
header("http:www.talkincode.com",false,301)
The is a problem with the headers() function is that it will cause errors if any output has already been sent to the browser, including other headers. To get around this you can use the headers_sent() function, which checks to see if any headers have been sent. If they have then it returns true, if not then false is returned.
So with this in mind we can create a neat little check to redirect the page in both cases. If headers have already been sent then the JavaScript property location.href can be used to redirect the page in the same way.
// set up redirect URL
$url = "http://www.talkincode.com";
if(headers_sent()){
  // redirect using JavaScript if it has
  echo "<script type='text/javascript'>location.href='$url';</script>";
  exit();
}else{
  // otherwise use the php way.
  header("Location:".$url);
  exit();
}

This works as long as the user has JavaScript turned on, if they don’t then you might have to just provide them with a link to allow them to progress.