Securing when using $_GET

I created a delete page so the user can delete their posts they no longer want and wanted to see if this looks solid or if there improvements needed.

this is what they click to delete on their dashboard
<td><a href="user_post_delete.php?id=<?php echo $row['id'] ?>" class="btn btn-danger">Delete</a></td>

and this is the delete setup on its own file

if (isset($_GET)) {   

    $id = $_GET['id'];

$stmt = $pdo->prepare ("DELETE FROM posts WHERE id = :id");
$stmt->bindParam(':id', $id);



// var_dump($_GET['id']);

header('Location: http://localhost/database_system/user_articles.php'); 

You should use a post method form, with a hidden field for the id, since you are performing an action on the server. By using a get method link, should a search engine index the page, all the data will get deleted, because it will follow all the links it finds.

Both the form processing code and the code producing the post method form must enforce delete permission and owner-ship or administrator-ship for the id(s) being operated on.

In general, the code for any page should be laid out like this -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce the data needed to display the page
  4. html document

For the posted code -

  1. Use ‘require’ for things your code must have for it to work and require/require_once is not a function. The () around the filename are unnecessary clutter.
  2. $_GET is always set, even it if is empty. You should trim, then validate all inputs before using them. If a ‘required’ input is empty or in this case isn’t owned by the currently logged in user or the currently logged in user isn’t an administrator, who can operate on all data, this is an error. You would setup user/validation error messages, in an array, using the form field name as the main array index, letting the user know what was wrong with the data that they submitted. After the end of the validation logic, if there are no errors, use the submitted form data. To display the errors, test for and display the content of the array holding the errors in the html document.
  3. don’t copy variables to other variables for nothing.
  4. if you use simple ? place-holders and supply an array of values to the ->execute([…]) call, you can reduce the amount of typing.
  5. upon successful completion of the post method form processing code, you should execute a redirect to the exact same URL of the current page to cause a get request for that page. This will prevent the browser from resubmitting the form data should that page get reloaded or browsed back to.
  6. every redirect needs an exit/die statement to stop php code execution.
Sponsor our Newsletter | Privacy Policy | Terms of Service