TAGS :Viewed: 3 - Published at: a few seconds ago

[ Check redirect source ]

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
}*/
?>

Answer 1


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
}

Answer 2


you can simply try this :

if(isset($_GET['id']) && !empty($_GET['id']))
{
       // your success message
}

Answer 3


  • 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.

Answer 4


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.