PHP Redirect Vs JavaScript Redirect?
Redirect to another web page is possible through PHP as well as JavaScript. So, which one you will choose?
PHP is server side language, and JavaScript is Client side. So, redirect through JavaScript will be possible on Client-Side.
Redirect on client side means following steps:
User request a Page using an URI,
Server sent a page based on that.
That page will have JavaScript that will redirect user to another page. So, again server will get the request for the new page and then server will give response based on new request.
So, it Client-side -> Server-side -> Client-side -> Server-side -> Client-side.
Redirect on Server-Side means:
Client-side -> Server-side -> Client-side (headers only)* -> Server-side -> Client-side.
Client-side (headers-only) - This indicates that Client (web browser), will still be involved but it will not involve parsing the whole page and executing JavaScript and others. It is just Header sent to Client and client can quickly follow the new location. So, it is fast and more user friendly.
There can be a situation where server-side redirect is not possible then JavaScript redirect may be a only option.
Client-side/JavaScript Redirect:
A. JavaScript only:
<script> window.location = 'http://www.mywebsite.com/new-url.php'; </script>
B. Using HTML Meta Tag, inside HEAD section:
<meta http-equiv="refresh" content="0;url=http://www.mywebsite.com/new-url.php" />
PHP/Server Side Redirect:
Redirect using PHP is done using header() function.
<?php
$loc = 'http://www.mywebsite.com/new-url.php';
header("Location: $loc");
die(0);
?>
Here you have served another page content by redirecting the user to new location because you have changed the page address, the user is looking for or for some other reason. User will smoothly get the content.
Update: I have made correction. Thanks to those who have commented and pointed mistake about the server-side redirects.
Possibly Related posts: