lStoilov
lStoilov

Reputation: 1339

Conditional JS Redirect

I am having a problem with php header redirect not working on safari

if (!isset($lang))
{
header('Location: http://domain.com/en/home');
}

I have read that this could be done with JS fairly simple, but no idea how to do it with the condition if $lang is set.

Should, I just execute the js within the "php if", or there is a better/clever way to do it.

Thanks.

Upvotes: 0

Views: 118

Answers (4)

Osama Mohamed
Osama Mohamed

Reputation: 697

You can use echo to print HTML tag <script> and put your JavaScript code inside this tag.

if (!isset($lang)){
   echo "
       <script>
          window.location = "http://domain.com/en/home";
       </script>
    ";
}

Upvotes: 1

Man Programmer
Man Programmer

Reputation: 5356

You can try with ob_start()

ob_start()//Define at the top of the php page.
if (!isset($lang))
{
header('Location: http://domain.com/en/home');
exit;
}

Upvotes: 1

6339
6339

Reputation: 475

Using Java Script

if (!isset($lang))
{
  ?>

    <script>
    location.href = "http://domain.com/en/home";
    </script>

  <?php
}

Upvotes: 1

Alex Tartan
Alex Tartan

Reputation: 6836

First off, you should stop the php execution if you set a redirect header:

if (!isset($lang))
{
     header('Location: http://domain.com/en/home');
     exit;
}

Note: for this to work properly, you need to set this header before any other and before setting any doctype. Also, the exit prevents anything else from being sent to the broswer (content, other headers, etc). Mixing headers can result in unwanted behavior.

Secondly, you can do:

if (!isset($lang))
{
     ?>
     <script>
     window.location = "http://domain.com/en/home";
     </script>
     <?php
}  

Upvotes: 1

Related Questions