Cancel a header(refresh) - php

Is it possible to cancel this after calling it:
<?php
// Start output while creating profile
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<1; $i++)
{
// Redirect user and download the profile
header('Refresh: .02; download.php');
echo "You're profile is being created, please wait...";
ob_flush();
flush();
sleep(1);
}
ob_end_flush();
// Start creating the profile
// Start this after the code above due to the long execution time
if(!createProfile())
{
// If createProfile returns false, cancel redirect and stop execution
cancelRedirect();
// Inform the user about the problem
echo 'Error!';
exit;
}
?>
The intention is that the header()-function is called, then the script does something and if the result is not as expected the redirect to "download.php" should be cancelled.

This is not possible but the reverse is possible:
<?php
if (doSomething()) {
header('Refresh: 1; download.php');
}
?>

Related

PHP refresh page if certain slug or ID

I'm trying to get a page refresh once after a set amount of seconds only on a set page.
So something like
if is_page('test.php') {
refresh page 5000(once);
} else
continue
You can do this by jQuery
like
window.setTimeout(function() {location.href="URL of test.php"}, 5000);
in PHP you can:
if(is_page('test.php') && !isset($_GET['r'])){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
}
NOTE: This can only be done if the headers have not already been sent http://php.net/manual/ro/function.headers-sent.php otherwise you will end up with a warning and the refresh will not work. A workaround would be:
if(is_page('test.php') && !isset($_GET['r'])){
if(!headers_sent()){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
} else {
echo '<meta http-equiv="refresh" content="5" ; url=http://zasite.com/test.php?r=1>';
}
}
OR - PHP with Gyandeep Sharma's JS answer
if(is_page('test.php') && !isset($_GET['r'])){
if(!headers_sent()){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
} else {
echo '<script>window.setTimeout(function () {location.href="http://zasite.com/test.php?r=1";}, 5000);</script>';
}
}

Write text with echo() after reloading page with header()

I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results&timestamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.

PHP Timed redirect not redirecting?

Have this code on my site to redirect users back to the homepage once logged out and destroys their session. Was working perfectly before when I was using my other hosting account to host the site, but now I've changed the host, it doesn't seem to work anymore ? It isn't actually doing anything. It does destroy session but doesn't redirect? The domain has remained the same and everything so I don't understand what is wrong here? Any ideas?
<?
session_start();
if(!isset($_REQUEST['logmeout'])){
echo "<strong><font color=green>Are you sure you want to logout?</font></strong><br />";
echo "<a href=logout.php?logmeout>Yes</a> | <a href=javascript:history.back()>No</a>";
}
else {
session_destroy();
if(!session_is_registered('first_name')){
echo "<center><font color=red><strong>You have now been logged out.</strong></font></center><br />";
echo "<center>You will be redirected in 3 second...</center><br />";
/* Redirect browser */
header('Refresh: 3;url=http://www.basecentre.co.uk/');
/* Make sure that code below does not get executed when we redirect. */
exit;
}
}
?>
TRY THIS
echo "<meta http-equiv='refresh' content='0;url=http://www.yoursite.com'>";
OR
use flush() before header call
Your previous hosting may have had automatic output buffering enabled.
To avoid "headers already sent" errors please change
echo "<center><font color=red><strong>You have now been logged out.</strong></font></center><br />";
echo "<center>You will be redirected in 3 second...</center><br />";
/* Redirect browser */
header('Refresh: 3;url=http://www.basecentre.co.uk/');
to
/* Redirect browser */
header('Refresh: 3;url=http://www.basecentre.co.uk/');
echo "<center><font color=red><strong>You have now been logged out.</strong></font></center><br />";
echo "<center>You will be redirected in 3 second...</center><br />";
And note that the header() function is occurring before the echo of any content.
You can't do header after any output. There's a setting in the php.ini to change this, but otherwise, it's better practice to send your headers before any output.
But, it looks like you're trying to give them a notification before they get redirected anywhere. To preserve this, just do it with javascript the same way you did on the other one..
echo "<center><font color=red><strong>You have now been logged out.</strong></font></center><br />";
echo "<center>You will be redirected in <span id="time">3<span> second...</center><br />";
//And then echo the redirect script.
echo <<<JAVASCRIPT
<script>
var count = 3;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
window.location.pathname = '/user/index';
}
document.getElementById("time").innerHTML = count;
}
window.onload = timer();
</script>
JAVASCRIPT;

URL opening in all browsers even when user not logged in?

My url is opening in all browsers even when I am using sessions. Ex abc.com/123.php without users logged in. This opens up in all browsers. I am using this code.All codes are in < php open/close tags ok codes which ia m using are
<?php
session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
// session timed out, last request is longer than 10 minutes ago
unset($_SESSION);
session_destroy();
header("location:userlogin.php");
}
} else {
$_SESSION['LAST_REQUEST_TIME'] = time();
}
if($_SESSION['username']=="");
?>
I am not sure that this compiles well. Because there are a couple of problems.
Be careful with this line of code:
if($_SESSION['username']=="");
This means that true part of this if statement finishes at semicolon.
Second thing is that your else part is never executed but printed as regular HTML.
I would write it like this:
<?php
session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
// session timed out, last request is longer than 10 minutes ago
unset($_SESSION);
session_destroy();
header("location:userlogin.php");
}
} else {
$_SESSION['LAST_REQUEST_TIME'] = time();
}
if(isset($_SESSION['username'])) {
?>
///////SOME HTML CODE/////
<?php
} else {
header("location:to_some_login_page.php");
}
?>
And I believe that is what you intended to to with closing <?php tag.
Also for readability I suggest you to do just this:
if ($_SESSION['username']!="") {
header("location:to_some_login_page.php");
}
So you don't even need else part, because as soon as header is set, he will be redirected.
Because your
else {
header("location:to_some_login_page.php");
}
is outside of <?php ?>
Try This:
<?php
session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
// session timed out, last request is longer than 10 minutes ago
unset($_SESSION);
session_destroy();
header("location:userlogin.php");
}
else {
$_SESSION['LAST_REQUEST_TIME'] = time();
}
if($_SESSION['username']=="");
///////your code/////
}
else {
header("location:to_some_login_page.php");
}
?>

How to redirect with header location in php when using ob_start?

<?php
ob_start();
echo "<body><p>Hello "
if ($condition) {
header( "Location: http://www.google.com/" );
exit;
}
echo " World!</p></body>";
ob_end_flush();
?>
When $condition is true I get this:
<body>Hello
What I want is when $condition will be true then go to Google!!!
I don't know what is happening, can you explain or give me a solution!?
Thanks.
Just add ob_end_clean(); before the header call.
Everything should work, just put an ; after echo "<body><p>Hello" and you will be fine..
If I were you, I would have started what might go wrong first then do the processing.
An example
$exit_condition_1 = some_value1;
$exit_condition_2 = some_value2;
if($exit_condition_1 == false){
//Redirect
//Exit
}
if(!$exit_condition_2){
//Redirect
//Exit
}
//start the buffer ob_start()
//show some HTML
//flash the buffer ob_end_clean()
there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.
An example: lets say that you want to view a product's info and you have a function that will do that
function view_product($product_id){
if(!$product = getProductById($product_id)){
//product does not exist, redirect
}
if(the user does not have enough access rights){
//show a message maybe
//redirect
}
//everything is alright then show the product info
}
To resolve a similar situation where a function was using ob_start() and there was header("Location: http://www.example.com"); after that but erring "already sent...", I replaced the header(... call with
echo "<script> window.location.href = 'https://www.example.com' </script>"
and it worked in that particular case (all that was needed was a just page redirect anyway).

Categories