Home > other >  Redirect Using JavaScript and PHP
Redirect Using JavaScript and PHP

Time:05-06

I am using below code for redirect users.

<?php
$redirect_to = "https://google.com";
$redirect = "https://yahoo.com";
echo "<script>location.href = '".$redirect_to."';</script>";
header("Location: $redirect");
exit();
?>

I prefer to use javascript redirect, but in somecase when user have not javascript enabled in his browser, I am using PHP redirect as backup redirect but sometime I am getting header already sent error on php redirect code and sometime I am not getting that error.

if I use exit() after redirect by javascript, I will not able to redirect user if he have javascript disabled in his browser.

my question is there any way to stop php code if javascript redirect was success? I am not getting idea what I have to do for handle my situation. Let me know if any expert can help me to solve puzzle.

Thanks!

CodePudding user response:

Well, you are a web developer using PHP and Javascript.

One thing to remember, PHP code always runs first on the server. It's a server-side language, so no matter how you arrange your lines of code, your php code will finish running. Then, the client source code (HTML, CSS, JavaScript) is sent to the browser and executed on it (Client-side).

And next, the job of redirecting is always on the client side, the server doesn't actually redirect people to another site. What actually happens is that your php source code generates a redirect command that sends the browser for a redirect. Another thing, in php, any work related to the header() function needs to be executed before any content is generated. That is, it must run at the top, before any method echo, exit, print,... or content block.

When deploying a php application, if you already use header("Location: ....") then it makes no sense to use javascript directives, as the browser will prioritize handling the redirect in the header first! ! The source code should really be:

<?php
$redirect = "https://yahoo.com";
header("Location: $redirect");
?>

Another way if you still prefer using javascript redirects and are compatible with javascript disabled, that is to use the tag meta[http-equiv="refresh"]. Refer to the following example:

<?php
$redirect_to = "https://google.com";
?>
<meta http-equiv="refresh" content="5;URL='<?php echo $redirect_to; ?>'" />
<script>location.href = "<?php echo $redirect_to; ?>";</script>

The number 5 appears in the content of the meta specifying the countdown (seconds) the browser will redirect when the page has finished loading. When the page cannot execute javascript, after 5 seconds the page will redirect.

  • Related