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×tamp=" . 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.
Related
When i refresh the page the phpmailer always resends the email.
What i did?
Used the header("Location: home.php");
But how can i do the Location to home.php and show my error message
$error = "Thank you for message!";
if($mail->send()){
header("Location: home.php");
$error = "Thank you for message!";
} else {
$error .= "Error {$mail->ErrorInfo}";
}
the problem is that when i do the header it does not show me the error message...
<div class="text-center impact">
<?php echo $error; ?>
</div>
You can pass a GET-parameter so you can check it when the page reloads. Try this code example:
if($mail->send()){
header("Location: home.php?success");
} else {
$error .= "Error {$mail->ErrorInfo}";
}
And on your page:
<div class="text-center impact">
<?php echo isset($_GET['success']) ? "Thank you for message!" : $error; ?>
</div>
You will not see it, because your browser do redirect immediately, before you can see it.
Super simple solution will be to redirect to:
header("Location: send-confirmation.php");
with the information that message has been sent.
Of course you can do more advanced solution and pass apropiate parameter to home page or to use cookies/session on your phpmailer page to avoid duplicate sending.
You are not passing the $error variable between your pages, so when you echo it, it's not defined and you'll get no output. You need to either pass it through a URL query parameter:
header("Location: home.php?error=" . rawurlencode($error));
and then retrieve it on that page:
echo $_GET['error'];
or alternatively pass it via a session variable (probably the better choice):
$_SESSION['errors'] = $error;
header("Location: home.php");
and then:
echo $_SESSION['error'];
I am trying to redirect my php login page so that if user is authorised, it goes to a page (r_index.php) and if the user isn't authorised they go back to the login page (login.html).
This is my code:
<?php
if ("password"=="$password") { // Start the condition ?>
Manage classes
<?php } // End the condition ?>
<?php if ("password"=="") { ?>
Login
<?php }
?>.
What am I doing wrong? How should I resolve it?
replace your code with this:
<?php
if ("password"== $password) {
header("location:r_index.php");
}
else if ($password=="") {
header("location:login.html");
}
?>
If you want to redirect you should use:
header('Location: http://www.example.com/r_index.php');
in your code.
<?php
$accessGranted = false;
if($password == 'password') {
$accessGranted = true;
}
if($accessGranted) {
header('Location: r_index.php');
}
else {
header('Location: login.html');
}
exit;
Actually your syntax is wrong, else there is no problem of using HTML inside php. It will work well and good.
Just make sure not to put your variable inside quotes, and change the statement as follows:
if($password=="password")
and
if($Password==" ")
Here is my code
<?php
if (!isset($_SESSION)) { session_start(); }
if (!isset($_SESSION['username'])) { header("Location: index.php"); }
ob_start();
if($_POST) {
$id = $_POST['book_id'];
$command = $_POST['command'];
$sourcePage = $_POST['source'];
} else if ($_GET){
$command = $_GET['command'];
$sourcePage = $_GET['source'];
$id = $_GET['book_id'];
} else {
header("Location: index.php");
}
// if command is 2 then show cart content
if($command == 2) {
showCart();
// if command is 1 then add book to cart
} else if($command == 1) {
addToCart($id);
header("Location: $sourcePage");
// if command is 0, then remove book from cart
} else if($command == 0) {
deleteFromCart($id);
header("Location: $sourcePage");
} else if(!isset($command)){
header("Location: index.php");
}
ob_flush();
?>
Why is it that even if I'm not logged in, I'm not redirected?
is it possible that the page is simply refreshing under the condition that $_POST or $_GET exists, falling into one of the later header("Location: ...") commands?
If so, you'd want to fix the problem by adding a die();
if (!isset($_SESSION['username'])) { header("Location: index.php"); die(); }
Using exit() or die functions may fix the problem. But there is only very very limited amount of situations where actually need to use one of these functions.
I think you can enhance if else conditions by putting some more conditions. But this will increase your lines of code.
From my experience, every time there is redirect via headers, its following connected code tends to execute.
For example : if you have an else/else if along with an if(which has the redirect code) then they will also be executed and the redirect never happens. However if you break up the conditions into individual ifs then after entering one if if a redirect is present such that there is no succeeding code after that header code in the if then the redirect will happen.
Better to use die()/exit() all over to avoid discrepancies.
On my index page I have a link to my login.php page with this code:
<?php
if(isset($_SESSION['username'])) {
echo "<div id='logout'><a href='logout.php'>Logout (".$_SESSION['username'].")</a></div>";
} else {
echo "<div id='login'><a href='login.php'>Login (Regular)</a></div>";
}
?>
On the login.php page I have
<?php
include('check.php');
$ref = getenv('HTTP_REFERER');
if (isset($ref)) {
header("Location: " . $ref);
exit;
} else {
header("Location: index.php");
exit;
}
?>
check.php is the code for the login form and it checks the users level to make sure they can access the page. I was told that I need to add a check to see if the referral is login.php, otherwise it will go in an infinite loop and I am of course getting "This webpage has a redirect loop". However, I have no clue how to do this and I can't find any information on how to fix it. Anyone know a quick solution?
You should be able to just do
if (isset($_SERVER['HTTP_REFERER']) && end(explode('/',$_SERVER['HTTP_REFERER'])) != 'login.php') {
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;
} else {
header("Location: index.php");
exit;
}
Note that this is a simplified code - you may need to be a bit smarter than that.
When checking that variables passed via GET and POST are correct, I might have something like this:
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!isset($_POST['new_email']))
header('Location: somepage.php');
else if(empty($_POST['new_email']))
//Report error to user and prompt to try again
else
$newEmail = $_POST['new_email'];
if(!isset($_POST['full_name']))
header('Location: somepage.php');
else if(empty($_POST['full_name']))
//Report error to user and prompt to try again
else
$newName = $_POST['full_name'];
if(!isset($_POST['new_password_a']))
header('Location: somepage.php');
else if(empty($_POST['new_password_a']))
//Report error to user and prompt to try again
else
$newPasswordA = $_POST['new_password_a'];
if(!isset($_POST['new_password_b']))
header('Location: somepage.php');
else if(empty($_POST['new_password_b']))
//Report error to user and prompt to try again
else
$newPasswordB = $_POST['new_password_b'];
//Do some things with the variables
}
else
{
header('Location: somepage.php');
}
//View
//Display relevant view here
?>
How would you check GET and POST variables in your PHP script? I wonder if there is a better way?
Maybe creating a function to avoid the repeated code?
function check($varname,$destination,$message) {
if (!isset($_POST[$varname])) {
header("Location: $destination");
} else if (empty($_POST[$varname])) {
//Do something with $message
} else {
return $_POST[$varname];
}
return NULL;
}
And then,
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$newEmail = check('new_email','somepage.php','Error message');
$newName = check('new_name','somepage.php','Error message');
$newPasswordA = check('new_password_a','somepage.php','Error message');
$newPasswordB = check('new_password_b','somepage.php','Error message');
//Do some things with the variables
//Checking for NULL values (although if some var was null,
//it should have either redirected or reported an error)
}
else
{
header('Location: somepage.php');
}
//View
//Display relevant view here
?>
What The Pixel Developer says is true though, you should sanitize the inputs at least against SQL injection (if you will use the data in a database) and CSRF attacks.
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
foreach ($_POST as $key => $value) {
if (empty($value)) {
echo 'whoops, remember to set ', $key;
} else {
switch($key) {
case 'new_password_a':
$newPasswordA = $value;
break;
//etc
}
}
}
if (isset($newPasswordA) && isset($newPasswordB)) { //check all vars have been set or whatever
header('Location: somepage.php');
} else {
header('Location: somepage.php');
}
Sorry I couldn't be more specific with the code, your sample code was kinda vague. I hope that helps.
Your code is a wild mess for a start. Please use brackets, better code comments and classes / functions.
You're not checking for anything correct other than if the key has a value. You might want to add a CSRF token to make sure the request has come from the form you are expecting.
Look at CSRF on Wikipedia.