1

I have a PHP 'if' condition, which if true, than I'd like to redirect the user to somewhere else with javascript. However it doesn't seems to work, as it redirects me always, no matter if the condition is true or not.

<?php
if (isset($_SESSION['lol'])) {
    ?><script type="text/javascript">
<!--
window.location = "http://www.test.org"
//-->
</script><?php
}
?>

How is it possible? Or how could I make it to work?

5
  • you have a syntax errroR (isset($_SESSION['lol'])) - missing a closing bracket Commented Apr 8, 2013 at 15:15
  • Why redirect with JS indead of using header("Location: http://www.test.org"); Commented Apr 8, 2013 at 15:16
  • Sorry it was just a typo. Edited. Commented Apr 8, 2013 at 15:16
  • Also, why don't you do a php header redirect? header("Location: http://www.test.org") Commented Apr 8, 2013 at 15:16
  • @Jon I want to get the HTTP_HEADER info to contain where I got redirected from. And as I see header('test.org') is not giving me header info. Commented Apr 8, 2013 at 15:17

2 Answers 2

3

Just redirect in PHP instead:

<?
    if (isset($_SESSION['lol']) {
        header("Location: test.org");
    }
?>

EDIT: But if you wanted to use your current code, you need to echo the script tag:

<?
    if (isset($_SESSION['lol'])) {
        echo "<script>window.location.href = 'test.org';</script>";
    }
?>
Sign up to request clarification or add additional context in comments.

2 Comments

I want my browaser to pass the HTTP_HEADER to the landing page. (test.org)
I see. If Javascript will do that (I'm not sure), then you can use my second snippet of code.
0

Regardless of how easy the Javascript approach might seem, you should do the redirect in PHP:

<?php
    header('Location: http://test.org');
    exit;
?>

First, there may be cases when javascript isn't working (it may be intentionally turned off, the user might be using an incompatible browser, the user might have browser plugins such as NoScript installed, etc.)

Also, you should stop code execution after the redirect (that's why there's exit in my example) so that a malicious visitor couldn't ignore the redirect and just read the page content anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.