-1

I have two pages: index.php and stats.php

Both of the pages contains the same query from database, and have a delete button. When pressing the delete-button it redirect like this: https://example.com/delete.php?id=50; where 50 is the row ID.

The delete.php looks like this:

<?php

include "db.php"; // Using database connection file here

$id = $_GET['id']; // get id through query string

$del = mysqli_query($link,"DELETE FROM table WHERE id = '$id'"); // delete query

if($del)
{
    mysqli_close($link); // Close connection
    header("location:index.php"); // redirects to all records page
    exit;   
}
else
{
    echo "Error deleting record"; // display error message if not delete
}
?>

The problem now is that when the user press delete, it deletes the row, and redirects back to index.php. But how can I check what page it was deleted from, and redirect back to that page?

EDIT:

For testing purpose, I tried something like this below, but when deleting from both pages, both of them gave me the same output: "2":

if($del)
{
    if($_SERVER['HTTP_REFERER'] == "index.php")
    {
        echo "1";
    } else {
        
    echo "2";
    
    }   
}
Erik Auranaune
  • 1,384
  • 1
  • 12
  • 27
  • 1
    you can pass a param to the delete page including the current page that you're in so that you can take that param from the delete page and redirect according to the value in that param. Or else you can use `HTTP_REFERER`https://www.php.net/manual/en/reserved.variables.server.php – Hirumina Jul 29 '20 at 09:07
  • What have you tried to debug the problem? If you think that a check based on `$_SERVER['HTTP_REFERER']` is not working, have you debugged what that variable contains? – Nico Haase Jul 29 '20 at 09:58

2 Answers2

2

You can use $_SERVER["HTTP_REFERER"].
It contain the URL of the previous page.

$_SERVER['HTTP_REFERER'] contain the full URL.
Ex: http://localhost/my-site/index.php

So you could just do :

header("location:".$_SERVER['HTTP_REFERER']);
Obzi
  • 2,384
  • 1
  • 9
  • 22
1

As @Bazaim said. Use $_SERVER['HTTP_REFERER'].

For your purpose it could be something like this:

if ($del) {
   ...
   header('location: ' . $_SERVER['HTTP_REFERER'])
}

Something else: You are using $_GET['id'] in your msql query. If I would add ?id=0' OR '1=1 in your URL. (id=0%27%20OR%20%271=1) This could potentially delete your whole table. You might want to read something about mysql injection.

bro
  • 61
  • 6
  • I tried the SQL Injection add you gave, but it gave me "Error deleting record", so I guess I am safe, or? – Erik Auranaune Jul 29 '20 at 09:41
  • Holy moly, Yea the whole table was deleted. What do you suggest I do to avoid this? – Erik Auranaune Jul 29 '20 at 09:58
  • You could use something like mysql_real_escape_string. But tbh. use something like PDO. There is an article in SO that might guide you: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – bro Jul 29 '20 at 10:00