Matrix001
Matrix001

Reputation: 1272

Server Redirect with php and javascript

I call this function from another page

  Redirect($loc);

and I want it to redirect my server..

function Redirect($loc) 
{    
   echo ("<script type=\"text/javascript\">var timeout=1; setTimeout(\"window.location.replace('" . $loc . "')\", timeout*1000 );</script>");    
} 

I have two questions. one is the script in the function is correct? second, how do I pass it a url, assuming I am using the localhost and I want my applicaton to be portable. So I my file is called Registration.php and it is in the Users folder of my site, how do I contruct a url?

Upvotes: 0

Views: 326

Answers (2)

Rudi Visser
Rudi Visser

Reputation: 21989

Is there any particular reason that you're using Javascript to redirect? What if the client has Javascript disabled?

A better way to perform redirection would be to do it server-side like such:

function redirect($location)
{
    header('Location: ' . $location);
    die();
}

That will send the location header to the browser thus redirect it immediately, saving you bandwidth and the possibility that Javascript is disabled on the client side.

Note that as this is a header, you will need to either call this method before you have output any data (with echo or otherwise), or use output buffering so as to not have to change your application much.


As described in comment to cover a relative URL, you could use a constant storing your web root which would work like this (replace line):

header('Location: ' . WEB_ROOT . $location);

Example usage:

<?php
define('WEB_ROOT', '/');
function redirect($location) 
{
    header('Location: ' . WEB_ROOT . $location);
    die();
}
redirect('Users/Registration.php');

Upvotes: 1

user973254
user973254

Reputation:

This is more suitable for redirection than yours, to make you application portable use relative paths, not absolute ones

function redirect($where = '') {
    if(!empty($where)) {
        echo '<script type="text/javascript">window.location = "' . $where . '";</script>';
        exit(); // to prevent script execution if user switched off JS
    }       
}

Upvotes: 1

Related Questions