PHP redirect without header()
It’s very frustrating when you want to redirect from one page to another, and you get the error:
Warning: Cannot modify header information – headers already sent by (output started at /some/filename.php:12) in /some/filename.php on line 99
The problem is Headers are already sent, or in simple language the output is already sent to browser when your header() function is called. The best solution is not to pass headers (send html/output to browser) till the point header() function is fired.
Another way is to use output buffering. Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script. For using this method, you have to start your file with ob_start(); so that output gets buffered.
But what if you don’t care whether the output is sent or not, you anyway want the redirect to work? This simple function will do the trick for you. It will check if headers are not sent, then it will call the PHP’s header function to redirect. But if the headers are sent, it will use Javascript to redirect to the URL you want.
function redirect($url) | |
{ | |
if (!headers_sent()) | |
{ | |
header('Location: '.$url); | |
exit; | |
} | |
else | |
{ | |
echo '<script type="text/javascript">'; | |
echo 'window.location.href="'.$url.'";'; | |
echo '</script>'; | |
echo '<noscript>'; | |
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />'; | |
echo '</noscript>'; | |
exit; | |
} | |
} |
6 Comments
Leave a comment to ملیس
Welcome to my Blog
Certifications
Honor
Recognition
Contributions
Categories
- Apache (2)
- ChatGPT (1)
- Domain name (2)
- eCommerce (2)
- htaccess (1)
- Humor (3)
- Instagram API (1)
- jQuery (4)
- JSON (1)
- Linux (10)
- Magento (142)
- Magento admin (58)
- Magento Certification (5)
- Magento error (13)
- Magento frontend (68)
- Magento Imagine (2)
- Magento Interview (5)
- Magento Master (2)
- Magento2 (10)
- Mobile (1)
- MySQL (7)
- OpenAI (1)
- OroCRM (2)
- Performance (2)
- PHP (8)
- Prototype JS (3)
- Security (4)
- Wordpress (3)
- XML (2)
I’ve tried using the redirect function – and yes, it overcomes the problem of moving to the next screen – but it would appear the session variables are not maintained
great job! Thank You.
Thanks.. this was very helpful.
wonderful solution! thank you so much
Thanks man you solved my problem!
Needed a way to redirect users to a Thank You page after completing the form in my plugin but AFTER it sends the data through to the API…this worked like a charm! Thank you!