Skip to main content
Articles

Simple PHP Mobile Website Redirect-Code

0
0

Just a reminder to myself:

PHP redirection can be achieved by using the header() function. To redirect to another page, create an index.php file in the directory you want to redirect from and use the following code:


<?php
header('Location: http://www.redirect.to.url.com/');
exit;
?>
Where ‘http://www.redirect.to.url.com/’ is the URL you wish the users to be redirected to. This can also be a file, like so:


<?php
header('Location: anotherDirectory/anotherFile.php');
exit;
?>

Files can be of any type, including but not limited to HTML, python, PHP, CGI, Perl, and compiled CGI programs.

Side note: die() or exit()

The redirects sometimes doesn’t work in pre HTTP/1.1 user agents. Long story short, use this, it’s more secure.


<?php
header('Location: http://www.redirect.to.url.com/');
exit;
?>

If you experience a 302 redirect, your browser typically caches the page for the session only. Additionally, search engines do not typically transfer page rank to the new location. This is why the 302 redirect is ideal for performing site maintenance or other temporary use cases.


<?php
header('Location: https://www.examplecom/', true, 302);
exit;
?>

To set a permanent PHP redirect, you can use the status code 301. Because this code indicates an indefinite redirection, the browser automatically redirects the user using the old URL to the new page address. It also informs search engines that the page isn’t available anymore but is replaced with the new one.

<?php
header('Location: https://www.examplecom/', true, 301);
exit;
?>


<?php
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

if ($detect->isMobile()) {
    header('Location: yourpage.php');
    exit(0);
}

Mobile redirect only using JavaScript


<script type="text/javascript">
if (screen.width <= 767) { // Target Screen Width
document.location = "https://google.com";
}
</script>

Corner Icon Render
Corner Icon Render How Can I Help You?