简体   繁体   中英

How to escape input in PHP?

I have a PHP page that accepts input from a form post, but instead of directing that input to a database it is being used to retrieve a file from the file system. What is a good method for escaping a string destined for the file system rather then a database? Is mysql_real_escape_string() appropriate?

If you're using user-provided input to specify a filename directory, you'll have to make sure that the provided filename/path isn't trying to break "out" of your site's playground.

eg having something like

readfile($_GET['filepath']);

will send out ANYTHING on your server that the attack knows the path for. Even something like

readfile('/path/to/your/site/download/' . $_GET['filepath']);

accomplishes the same, if the user specifies enough '../../../' to get to whatever file they want.

mysql_real_escape_string() is NOT appropriate for this, as you're not doing a database operation. Use appropriate tools for appropriate jobs. In a goofy way, m_r_e_s() is a banana, and you need a giraffe. Something like

readfile('/path/to/your/site/download/' . basename($_GET['filepath']));

would be relatively save as basename() will extract only the filename portion of the user-provided file, so even if they pass in ../../../../../etc/passwd , basename will return only passwd .

You always only need to escape characters that are otherwise interpreted by your target system. For databases you usually make sure to escape quotes so you use mysql_real_escape_string or others. If your target is html, you usually use htmlspecialchars to make sure you get rid of html special characters (namely < , > and & ). If your target is CSV, you basically only need to make sure line breaks and the CSV separator are escaped.

So depending on your target you can either reuse an existing escape function, define your own, or even go without one. If all you do is dump the input in a single file, then there is not much you need to take care of, as long as you specify the filename and that file is never used (or interpreted) by anything else than your application.

So think of what kind of special characters your target format requires for it to work, and simply escape those. You can usually ignore the rest.

edit:

If you want to use the input as the file path or file name, you can simply decide yourself how gracious you are, and what characters you want to support. A simple method would be to replace everything except latin characters and numbers (and maybe some special characters like _ and - ) by something else. For example:

preg_replace( '/[^A-Za-z0-9_-]/', '_', $text );

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