How do I Redirect url With PHP Script?


How do I redirect url with PHP script? How can I use a PHP script to redirect user from the url they entered to a
different web page/url? Yes, you can do these adding a small php snippets in your header section.

Here I have share a small PHP (PHP Hypertext Preprocessor) snippets which will help you to redirect your url to another url By using PHP’s “header” function. The header function is a PHP specific function and can not be used outside of PHP.

Redirect One Page to Another

<?php
 header("HTTP/1.1 301 Moved Permanently");
 header("Location: http://example.com/new/page/");
 exit();
?>

or

<?php header("Location: http://example.com/new/page/", true, 301); ?>

Redirect from file to directory root

<?php
if(isset($_SERVER['HTTPS']) and 'on' === $_SERVER['HTTPS']) {
    $location = 'https://';
} else {
    $location = 'http://';
}
// Get the servers base URL
$location .= $_SERVER['SERVER_NAME'] . '/';
// Get the current URI without a file name in it
$location .= dirname($_SERVER['REQUEST_URI']) . '/';
header('Location: ' . $location);
exit();
?>

I took the PHP tags so don’t forget to remove those in if you need to. Thanks Brad Knutson for this important PHP Redirect snippets.

Masum Billah has written 326 articles

Hi I am Md. Masum Billah Contributor of this website. I always like to share various things with other. In this website I am sharing web design related tips and tricks, necessary web development tools, source codes for beginner and advance web developer. You may join with us to help other who want to learn web design and development. Thank you for stay with.

Recommended Articles

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>