using JS : (in <head>
tag)
<script>window.location="https://stackoverflow.com";</script>
using PHP : (in <head>
tag)
header('Location: https://stackoverflow.com');
end();
Which one I should use ? or another ?
and what about using <meta>
?
<meta http-equiv="refresh" content="0;url=https://stackoverflow.com"/>
Many good answers , I don't know which answer I will accept, Thanks so much
Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php .
Using JavaScript via PHP: The windows. location object in JavaScript is used to get the current page address(URL) and to redirect the browser to a new page. The window. location object contains the crucial information about a page such as hostname, href, pathname, port etc.
To set a permanent PHP redirect, you can use the status code 301. Because this code indicates an indefinite redirection, the browser automatically redirects the user using the old URL to the new page address.
The header() function is an inbuilt function in PHP which is used to send a raw HTTP header. The HTTP functions are those functions which manipulate information sent to the client or browser by the Web server, before any other output has been sent.
The result is same for all options. Redirect.
<meta>
in HTML:
window.location
in JS:
if (1 === 1) { window.location.href = 'http://example.com'; }
.header('Location:')
in PHP:
header()
must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent
A better way to set the location in JS is via:
window.location.href = 'https://stackoverflow.com';
Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With