Php readfile (folder / subfolder). $ _ GET ['userInput']) security issue?

I have page.php?id=example

and page.php

:

readfile('folder/subfolder/'.$_GET['id']);

      

A variable id

is a string and can take on infinite different values, so would it be difficult to list them in php?

At best I could verify that all characters are letters.

If I id

did readfile($_GET['id'])

, I realized that it is possible to read any php file and have code and database passwords.

But using readfile('folder/subfolder/'.$_GET['id'])

:

  • I know ../

    , but I tried it and it doesn't seem to work? This tells me:readfile(folder/subfolder/../../index.php): failed to open stream: No such file or directory

  • If I checked for .

    and every time /

    , would that be enough or are there other similar tricks?
  • Should I use int id

    instead of string?
  • Should I do otherwise?
+3


source to share


2 answers


You should never pass user input to file operations. Even if you avoid all ".", You will never know if there is any new security problem.

So you can



  • whitelist user input, for example using in_array

    to check if user input is defined in your list.
  • use numeric IDs as you mentioned above (so you can avoid user input (int)

    ).
  • if you need to use string input, just allow certain characters, for example check the input with preg_match('/^[A-Za-z0-9_-]+$/', $_GET['id']);

    .
0


source


Here you will find answers to the following questions: Security Issues with PHP Readfile Method

Now, about "Should I have done differently?" I would say that you could have done differently.

Apart from checking the type of files you want to grant access to, which should be easy enough, I would add the "authorized_files" file (or use a database, by the way, depends on the number of files you've got) to any sub_folder in question, and use it as a list of authorized files that can be accessed through the read file.



if (in_array($_GET['id'], file('authorized_files'))) {
    readfile(...);
}

      

Edit: Ah, if it is about reading only .txt files, type checking should be easier and best done

0


source







All Articles