Skip to content
Advertisement

Sanitize user-supplied URL for file_get_contents

I want to use file_get_contents to implement a proxy so I can do cross domain AJAX requests.

Query string will be used to supply the URL to file_get_contents. Now the problem is people can muck around with the query string in order to read local files on the server. I don’t want this. Can someone get me a function to sanitize the query string in order to accept only URLs and not local files, i.e.:

  • ?url=http://google.com.au – OK

  • ?url=./passwords.txt – Not OK

Advertisement

Answer

$url = filter_var($_GET['url'], FILTER_SANITIZE_URL);

or

if($_GET['url'] === filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
    ... your stuff here ...
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement