To protect the websites we're programming from attacks such as SQL-Injection or XSS we need to filter users' inputs before storing or displaying it.
In PHP, we use htmlspecialchars
and addslashes
functions to the inputs to prevent XSS and SQL-Injection attacks. So, what about the files ?
I used to protect web-apps by checking the files type and it's extension to know if those were in the whitelist or not. But I don't use htmlspecialchars
and addslashes
functions because I didn't see someone using this approach.
For example, if I want to get the file name I use $_FILES['file']['tmp_name']
then I store it directly to the database.
Is this wrong or it cannot be injected with codes, commands ... etc.
If you're using PDO or MySQLi you should be able to place the file in a prepared statement which should protect you from SQL injection attacks. I pasted a method from https://www.mysqltutorial.org/php-mysql-blob/ which has some good information on storing files in a MySQL database.
/**
* insert blob into the files table
* @param string $filePath
* @param string $mime mimetype
* @return bool
*/
public function insertBlob($filePath, $mime) {
$blob = fopen($filePath, 'rb');
$sql = "INSERT INTO files(mime,data) VALUES(:mime,:data)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':mime', $mime);
$stmt->bindParam(':data', $blob, PDO::PARAM_LOB);
return $stmt->execute();
}
Or you could store the file on the filesystem and just include a reference to the file for when you need to serve it up. This method is quicker, but doesn't have the convenience of keeping all your data in one place.
The details about the elements of the $_FILES
array are kind of buried in the manual, but they can be found at the end of example 1 here:
https://www.php.net/manual/en/features.file-upload.post-method.php
The values on all elements of the $_FILES
array should be regarded as user input. I would recommend ignoring those values. However, if you wish to write them in to a database and/or display them later in your UI, you definitely need to protect yourself from SQL injection and XSS attacks. So using prepared statements and htmlspecialchars
wouldn't hurt, in that case.