How can I detect how a user accesses a page in php? (from a form or directly)

Viewed 24

I would like to detect how a user accesses a page with php. For example, if I have this form on an html page:

<form action="php/file.php" method="post">
<input type="text" name="text">
<input type="submit">
</form>

and I send it to file.php:

<?php
echo $_POST["text"];
?>

It should work as normal, but if I went to file.php directly, (something like example.com/php/file.php) I would like it to display something like the 404 error page.

Is there any way to do this? Thanks!

1 Answers

In your case, you can check if $_POST["text"] is set, if not means the page is being accessed directed (by GET) or the text field is not being sent (by POST).

if (!isset($_POST['text']) { 
  header('Location: 404.php'); //redirect to 404 page
  return false;
}

Note: this code should be added before write/print any other character so that redirect can work

Related