How can I send a user to a different url without redirecting the header?

I am learning PHP and have been looking for this for a while. What I want to achieve is something like this:

if (true/false) { go to this url; } 

Every time I look at terms such as php redirects or php links, etc., in 99% of cases I get something “headers”. I read that redirecting headers can achieve this, but before that the code cannot go, it must be the first on the page, otherwise it will not work.

If so, how can I achieve this?

+6
source share
3 answers

I read that header redirection can achieve this, but code cannot go before that. that it should be the first on the page, otherwise it will not work.

It is not right. There should be no way out. So you have to make sure that before you do echo , print , ?>something<?php (or something else).

 if (true) { header('Location: ' . $url, false, 302); exit; // Ensures, that there is no code _after_ the redirect executed } 

You can prepare everything about it in the official guide . Special:

Remember that header () must be called before sending any actual output, either using regular HTML tags, empty lines in a file, or from PHP. A very common mistake for reading code with include () or require () functions, functions or another file access function, as well as spaces or empty lines that are displayed before calling header (). The same problem exists when using a single PHP / HTML file.

+8
source
 echo '<script type="text/javascript"> document.location = "http://yoururl.com";</script>' 

and this will be executed if this part of the script is executed.

+5
source

You can use this if you need some output before redirecting:

 header("refresh: $time_in_seconds; url=$your_url); 

You should still call this before the output is actually sent. Send the header, then send your output - the page will be "redirected" at the specified time.

Disclaimer: I must admit that I am not sure what this means and cannot find the documents on it, so I cannot recommend it, but I can confirm that it works.

0
source

Source: https://habr.com/ru/post/899166/


All Articles