Reputation: 107
i have a php file that is called from a javascript with the purpose of uploading files to my server.
Clarification that what im doing is calling this php file with ajax, so as i understand it it's not run in the traditional sence, which is why i am not using $_FILE and $_POST as the whole point of this project is to handle fileupload / collection of user data is done without a page reload.
obviously we want some sort of serverside file validation, which i have set up in an if statement.
however the code succeeds and proceeds with the upload no matter what file type i select.
can someone tell me what is wrong / or guide me in the right direction ?
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(!in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
return false;
}
?>
much apreciated - Mr B
Upvotes: 0
Views: 84
Reputation: 1579
The problem with the code is (Like @Cashbee mentioned in the comments), is with if(!in_array($ext,$allow))
portion of the code. This part allows the file to be uploaded if the file extension is not in $allow
array. The correct code should be as below.
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
exit;
}
?>
Important Note : Please keep in mind that, trusting an extension based on a header set by a javascript command from browser has a high risk and shouldn't be trusted. If this is required, you must store those files in a folder either inaccessible/restricted from the web and serve them raw with the correct mime header upon request or check more than file extension on upload.
Upvotes: 2