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.

  • # 1 - by fyrye

    Since my previous post got cut off.
    headers are not server side as the order of information goes.
    Client Request->Server Serves (header)->Client receives (process header)->Client Request (Oh the page was moved to here?)->Server Serves.
    Since the header function does not call for the information from the server.
    For example header(“refresh: 1; url=/index.php”);
    Is the same as the meta tag refresh example.
    The difference is that the status and location headers are received by the client prior to meta tags (html)
    A better example of server side redirect would be the include or require functions. In which the server requests the page to send to the client. And can not be blocked by the client like headers/scripts can be.

Comment pages
1 5 6 7 908
Comments are open for an year period. Please, write here on Facebook page.