Articles JavaScript PHP PHP Code SEO Simple CSS Code Style & Scripts

PHP Headers for your Web Application

Hi friends, In this post i would like to share my knoweldge about redirection , 404 ( Page not found error message) ,service not avialable(503), CSS , Javascript , For the images and application type ( PDF ,…).
For above requirements we can use php headers to solve the issues.

PHP Headers for your Web Application by Anil Kumar Panigrahi
PHP Headers for your Web Application by Anil Kumar Panigrahi

1) 301 moved permanently (redirect):

<?php
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.domain.com');
die();
?>

 

2) 302 moved temporarily(redirect):

<?php
header('Location: http://www.domain.com');
die();
?>

 

3) 404 Page Not Found:

<?php
header('HTTP/1.1 404 Not Found');
?>

 

4) Service not avaliable:

<?php
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 60');
?>

 

5) CSS:

<?php
header('Content-Type: text/css');
?>

 

6) Javascript header:

<?php
header('Content-Type: application/javascript');
?>

 

7) Images:

7.1) For JPEG(jpg):

<?php
header('Content-Type: image/jpeg');
?>

7.2) For PNG:

<?php
header('Content-Type: image/png');
?>

7.3)For BMP:

<?php
header('Content-Type: image/bmp');
?>

 

8 ) PDF (output pdf with php):

<?php
header('Content-Type: application/pdf');
echo file_get_contents('filename.pdf');
?>

 

9) Cache (force browsers not to cache files):

<?php
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header ('Pragma: no-cache');
?>

 

10) Download dialog:

<?php
header('Content-Disposition: attachment; filename=' . urlencode($f));  
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');            
header('Content-Length: ' . filesize($f));
echo file_get_contents($f);
?>

 

11) Authentication (force the browser to pop up a Username/Password input window) – only available when PHP is running as an Apache module:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="The Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'If cancel is pressed this text shows';
    die();
} else {
//always escape your data//
$user='user_name';
$pass='password';
   if($_SERVER['PHP_AUTH_USER']==$user && $_SERVER['PHP_AUTH_PW']==$pass){
    echo 'Authorized';
}
}
?>

2 thoughts on “PHP Headers for your Web Application”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.