Check referrer?

600 Views Asked by At

I am having a problem. I have this code:

$theUrl = $_GET["url"];
include("$theUrl.php");

This gets the url, for example: http://mywebsite.com/index.php?url=test

But what if someone puts in:

http://mywebsite.com/index.php?url=http://theirwebsite.com/someEvilscript

How to avoid this? I want only scripts that i have on my server to be executed and not from other websites. Thanks for help.

3

There are 3 best solutions below

1
On

One of the good way to handle this is to define a white list of file that can be included. If anything isn't in that list, it should be considered evil and never included.

For example :

<?php
$allowed = array('file1', 'file2', 'file3');

if (in_array($_GET["url"], $allowed)) {
    // You can include
} else {
   // Error message and dont include
}
?>

Note : As suggested in the comment, the allowed list can be populated dynamically by scanning allowed directory.

0
On

You really shouldn't have any code that looks like that. And I mean really. What are you trying to achieve with this? I'm sure there's another way to the same without the risks (and let's say general uglyness).

Like HoLyVieR suggests, whitelisting what can be included is the key to making your current code safe.

0
On

Why don't you just create test.php on your site, and use http://mywebsite.com/test.php in the link? This way you can include your initialization script in test.php (and in the other scripts) if needed.