Home > Article > Backend Development > Detailed explanation of the dangerous file_put_contents function in PHP
The file_put_contents() function writes a string to a file. Recently, I discovered that the file_put_contents function has problems that I have never noticed, so the following article mainly introduces you to the relevant information about the dangerous file_put_contents function in PHP. Friends who need it can refer to it. Let’s take a look together.
Let’s take a look at the official website definition of the second parameter data of the file_put_contents function:
data 要写入的数据。类型可以是 string,array 或者是 stream 资源(如上面所说的那样)。 如果 data 指定为 stream 资源,这里 stream 中所保存的缓存数据将被写入到指定文件中,这种用法就相似于使用 stream_copy_to_stream() 函数。 参数 data 可以是数组(但不能为多维数组),这就相当于 file_put_contents($filename, join('', $array))。
As you can see, the data parameter can be an array, which will be automatically join('',$array)
converted into a string
When this function accesses files, it follows the following rules:
If FILE_USE_INCLUDE_PATH is set, then the built-in path for a copy of *filename* will be checked
If the file does not exist, a file will be created
open a file
If LOCK_EX is set, the file will be locked
If FILE_APPEND is set, moves to the end of the file. Otherwise, the contents of the file will be cleared
Write data to the file
Close files and unlock all files
If successful, the function returns the number of characters written to the file. On failure, False is returned.
But our string filtering function generally uses the preg_match function to filter, such as:
if(preg_match('/\</',$data)){ die('hack'); }
We know that many functions that process strings will return NULL if an array is passed in, such as strcmp, strlen, md5, etc. But the preg_match function returns false if an error occurs. Here we can pass var_dump(preg_match('/fb28f8b4e44df6c7f682ade00cf5e97e&ext=php
to bypass
Repair method
The fix is to use the fwrite function instead of the dangerous file_put_contents function. The fwrite function can only pass in strings. If it is an array, it will error and return false
<?php if(isset($_POST['content']) && isset($_POST['ext'])){ $data = $_POST['content']; $ext = $_POST['ext']; //var_dump(preg_match('/\</',$data)); if(preg_match('/\</',$data)){ die('hack'); } $filename = time(); // file_put_contents($filename.$ext, $data); $f = fopen($filename.$ext); var_dump(fwrite($f,$data)); } ?>
Related recommendations:
Recommended 10 articles about php file_put_contents() function
The difference between fwrite and file_put_contents in PHP
php file_put_contents function_PHP tutorial
The above is the detailed content of Detailed explanation of the dangerous file_put_contents function in PHP. For more information, please follow other related articles on the PHP Chinese website!