2

Possible Duplicate:
Sanitize file path in PHP

I have a php script that looks like this:

$search = $_REQUEST['search'];
$xml = simplexml_load_file("SOMEURL/search?q=".$search);

I'm wondering what is the correct way to stop people trying to load files or webpages by changing the search parameter.

I am fully aware of SQL Injection issues and know how to handle them, but I'm unsure as to the best method for securing the location of a file with user input.

I look forward to your replies.

EDIT

I am adding more detail to this question as it is marked as a duplicate to a post which does not answer what I'm after.

I have a php script on a Linux box that is using simplexml_load_file to query a SEARCH ENGINE Java (not javascript) script running on a Windows box. The user can change the search term to be anything that the user wishes as it's a search engine. The script on the Windows box returns back XML which the PHP code then uses for display purposes.

I would like to make sure that users cannot change the Search parameter to load another url or file.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Beanie
  • 425
  • 1
  • 5
  • 11
  • Its the headache of `SOMEURL`s owner. NOT you. – Shiplu Mokaddim Dec 02 '12 at 21:24
  • 1
    SOMEURL is on another server we run :) – Beanie Dec 02 '12 at 21:26
  • Thanks Lix, I did look at that link but that seems to be about validating file locations rather than urls, if I read it correct. – Beanie Dec 02 '12 at 21:29
  • 1
    If changing `$search` is a problem, why is it dynamic? And what exactly are the potential problems if anyone does change it? Btw, you should really `urlencode()` the variable before you use it in a URL. – Ja͢ck Dec 03 '12 at 01:33
  • Thanks for the info Jack, I have now used urlencode() in my code and updated my question with more info. – Beanie Dec 03 '12 at 05:31

1 Answers1

1

You won't be able to prevent the 'search' parameter from being altered by users/would-be-attackers. What you can and should do is validate the input to a list of valid values. If your list is small and static, this could be a simple array:

$validSearchValues = array(
    'foo',
    'bar',
);

$search = $_REQUEST['search'];
if (! in_array($search, $validSearchValues)) {
    //anything other than foo or bar will reach this point
    echo 'invalid input';
} else {
    //only foo or bar values will reach this point
    $xml = simplexml_load_file("SOMEURL/search?q=".$search);
}

For larger lists of values, you can store them in a database and issue a query to check for validity.

This example is basic. There are several frameworks and components that have good approaches to input validation which you should research (check Zend Framework or Symfony).

Rob Apodaca
  • 834
  • 4
  • 8
  • Thanks for the reply Rob, The search parameter can be any value at all so I can not validate the results against a predefined list. I will look at input validation :) – Beanie Dec 03 '12 at 05:34