简体   繁体   中英

PHP accept GET method only from specific page

I have two PHP files:

1.php

<?php

...  header("location: 2.php?id=1");
?>

2.php

<?php

... echo $_GET['id'];

?>

URL from 1.php to 2.php is: http://localhost/2.php?id=1

My question. Is it possible to validate where get method coming from and accept only if from coming 1.php. But if someone in address bar changing id values then ignore? Something with $_SERVER['HTTP_REFERER'] but i'm not sure

Is it possible to validate where get method coming from and accept only if from coming 1.php.

Not reliably.

But if someone in address bar changing id values then ignore?

Find something else to test against. (eg is this a user who is logged in and authorised to view the page with that id?).

Simple answer is no. $_SERVER['HTTP_REFERER'] is often disabled by browsers and is easily spoofed.

You can do someting close to your requirement:

<?php
 //1.php
 $id = 1;
 $key = generateKeyBasedOnId($id);
 header("location: 2.php?id=$id&key=$key");
?>

You can write generateKeyBasedOnId() function as you wanted to, but you are the only one who should known the algorithm. (For example return md5('my very secret'.$id.' string');

<?php
//2.php
if($_GET['key'] !== generatekeyBasedOnId($_GET['id'])) {
   //error
}
?>

Of course, if someone copy paste the url 2.php?id=..&key=..., it will still work. You can hide key into cookies, but it is still easilly spoofable.

You can also generate random key, save it into database, read it in 2.php and if it exists, immediately delete it. So the key can be used only once. But if someone catch your header redirect, he still could (theoreticaly) take it and use it in different browser in different country ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM