I have a form to edit an entry, after the user presses the submit button it executes the includes/edit.php?id=XXX script and then redirects using the header('Location: ../index.php'); to the index page where all the entries are being displayed.
On the index page, I want to create a condition:
if the index page is accessed via a redirect from the edit.php?id=XXX page, then show a success message to notify the user that the edit was succesfull.
How should this condition look like?
<?php
require_once('includes/session.php');
require_once('includes/config.php');
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
}
$query = ("SELECT * FROM archive ORDER by id DESC");
$result = mysqli_query($link, $query) or die (mysqli_error());
/*if (condition){
//show success message
}*/
?>
You should take a look at this var :
$_SERVER['HTTP_REFERER'];
As it will return the page from where you come before this one:
So you could just do :
if($_SERVER['HTTP_REFERER'] == "edit.php?id=XXX"){
// your code here
}
you can simply try this :
if(isset($_GET['id']) && !empty($_GET['id']))
{
// your success message
}
If you set a $_SESSION variable with messages you can then display all messages and clear the list afterwards.
Adding a message:
if ( ! isset($_SESSION['messages']) ) {
# initialize messages
$_SESSION['messages'] = [];
}
# Add a new message:
$_SESSION['messages'][] = 'Something was a success!';
Reading messages:
# If there are messages not displayed
if ( isset($_SESSION['messages']) && is_array($_SESSION['messages']) ) {
foreach ( $_SESSION['messages'] as $message ) {
echo $message . '<br>';
}
# Clear messages
unset( $_SESSION['messages'] );
}
The suggested 'HTTP_REFERER' can be manipulated and browsers are not required to send it.
I would suggest to redirect immediately and not execute more code after the location header is set:
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
exit();
}
If $_SESSION['login'] is not set: redirect and exit.
You might consider the rest of the code as one big "else" (= if $_SESSION['login'] is set).
To answer the question from comments: without the exit, the code below will be executed .. and doing that query is not really necessary. Thats why its better to end the program flow by adding an exit. Referencing: Why I have to call 'exit' after redirection through header('Location..') in PHP?
And for the condition you could use $_SERVER['HTTP_REFERER'] or $_GET['id'] to check the page you are coming from. Just compare the strings or parts of them.
Related
I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help
how to jump a page if condition true and also i want to sent a variable value to secont page
if(isset($_POST['compair']))
{
$_SESSION['usermail'];
$answer=$_POST['answer'];
if ($answer == $_SESSION['answer'])
{
$mail=$_SESSION['usermail'];(i want to sent "$mail" variable)
header("Location:resetpass.php?value = $mail ");
}
else
{
echo "<script>alert('Please Try again')</script>";
}
}
please also tell me how to receive this variable on second page.
Your solution is correct. Just pay attention to spaces:
header("Location: resetpass.php?value=$mail");
exit; // as suggested by "nogad"
Also make sure that resetpass.php file is in the same directory of current page.
In resetpass.php you can get the variable by $_GET['value'] like:
<?php
if( isset($_GET['value']) ){
$mail = $_GET['value'];
}
After header("Location : resetpass.php?value=$mail");
exit(); // i.e quit the current page and go to resetpass.php
Then at resetpass.php collect $mail using the GET method.
if(isset[$_GET['value'])){
$the_mail = $_GET['value'];
}
I am writing from my handy. So apologies for any layout discripancies
This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form
So I am creating an application (new -ish to sessions) and have been trying to create a simple error handling statement using sessions.
To simplify things, let me describe the basics.
User enters query on page 1
User presses submit
Page 2 is loaded to check the value of the query
If the query is set, it is run and the result is displayed on page 3
If it is empty however, an error is caught, set and the user is redirected back to page 1
What I care about is the last step as I cannot get it to work for some reason.
Here is the code pertaining to the error:
Page 1s relevant code:
<?php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
And on page 2:
<?
session_start();
---------------- And as we go down the file a bit ----------------
if(trim($getQuery == "")){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "localhost:8000/mysite"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
$getQuery is the value captured in the query box on page 1 and sent via the post method to page 2 as you may assume naturally.
But when I enter nothing in the query box and then send the query, the page refreshes (as it should when page 2 realises that the query is empty and header location reloads the page) but no error is shown, which it should considering I check on page 2 that it is set.
Any ideas?
Cheers,
-- SD
You have a typo in if(trim($getQuery == "")) { ... } it should be if(trim($getQuery) == "") { ... }, since you only want to trim the $getQuery variable, and not the whole condition. If you change this, then it will work.
Here's a minimum working example
<?php // 1.php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
<?php // 2.php
$getQuery = ""; // This is empty so it will redirect to 1 and show error message
session_start();
if(trim($getQuery) == ""){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "1.php"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
Sometimes the browser redirect (your header("Location")) can be quicker than the server.
Just before the redirect you should put
session_write_close()
Just to make sure the session is written for next time.
I am try to develop flash message using sessions in php
suppose on successfully delete query I am setting
$_SESSION["msg"]="record deleted successfully";
header("location:index.php");
and I have the following script on all pages which checks if msg variable is available it echo its value as below
if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
{
$msg=$_SESSION["msg"];
echo "<div class='msgbox'>".$msg."</div>";
unset($_SESSION['msg']); //I have issue with this line.
}
if I comment
unset($_SESSION['msg']);
message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.
You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.
Try adding exit; after header("location:index.php");.
Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1
In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
But this code probably will work as you want. Note that I have added exit after header line.
You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.
Another problem might be that you are doing more than one redirect.
You can simply set your session empty or null instead of unset it. Just do:
$_SESSION['msg']=NULL;
Or
$_SESSION['msg']="";