php upload pdf, doc, docx - php

I am try to upload files to my server the allowed extension should be pdf, doc, docx
this is my code.
$uploadCv = $_FILES['uploadCv']['name'];
$target = "includes/employeeCv/";
$target = $target . basename($_FILES['uploadCv']['name']);
if ($_FILES['uploadCv']['size'] == 0) {
$error['uploadCvErr'] = "<span class='notAllowed'>Please upload your c.v</span>";
} elseif
(
$_FILES['uploadCv']['type'] != 'application/pdf'
&& $_FILES['uploadCv']['type'] != 'application/msword'
&& $_FILES['uploadCv']['type'] != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) {
$error['uploadCvErr'] = 'Unsupported file type uploaded.';
} elseif ($_FILES['uploadCv']['size'] > 5000000) {
$error['uploadCvErr'] = 'File uploaded exceeds maximum upload size.';
}
everything is going OK with PDF and doc but on docx it says Unsupported file type uploaded.
what I am doing wrong here.
Edit
I added this to my check files
&& $_FILES['uploadCv']['type'] != 'application/zip'
still not working.

OfficeOpenXML .docx files often have the application/zip mime type because they are a zipped collection of XML files, and browsers are too lazy to check beyond the zip signature when setting mime type

Related

php file upload always uploading files even if errors

I am trying to upload either pdf or jpg, jpeg files to a folder and the code is as follows:
//Get the uploaded file information
if(!$_FILES['medreport']['error'])
{
$medreport = basename($_FILES['medreport']['name']);
$medreport_extn = substr($medreport, strrpos($medreport, '.') + 1);//get the file extension of the file
$medreport_size = $_FILES["medreport"]["size"]/1024;//size in KBs
$tmp_path = $_FILES["medreport"]["tmp_name"];
$report_folder = "../reports/";
//Settings
$max_allowed_file_size = 200; // size in KB
$allowed_extensions = array("jpg", "jpeg", "pdf");
//Validations
}
if($medreport_size > $max_allowed_file_size )
{
$error[] = "Size of the report file should be less than $max_allowed_file_size KB";
}
//Validate the file extension
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$medreport_extn) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$error[] = "The uploaded report file is not a supported file type. "."Only pdf, jpg and jpeg report file types are supported. ";
}
//replace filename with unixtime
$unixtime =time();
$medreport = $unixtime.mt_rand(0,9).'.'.$medreport_extn;
$report_path = $report_folder . $medreport;
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$report_path))
{
$error[] = 'Error while copying the uploaded report file';
}
}
while trying to upload files with correct extension and size i am able to upload it.
But if i try to upload an over sized or incorrect format file, it displays my error message, but the file always get uploaded to the folder.
Why is it so ?? Please, What is wrong with my code??
Is the way, i am doing it is secure enough ?? the folder is owned by www-data and permission is 755. I have a .htaccess file too in the file upload folder to prevent executables as follows:
SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off
The file always uploading is confusing me.
You are not using the errors you just found to check if you need to continue.
This:
if(is_uploaded_file($tmp_path))
Should be something like:
if(count($error) === 0 && is_uploaded_file($tmp_path))
And you should initialize your $error array at the start as an empty array if you are not doing that already.

Simplest way to convert uploaded videos to mp4 before storing them on a server?

I'm using a goDaddy server and cPanel to make a website, and I want to make a feature that lets users upload videos, save them on the server, then display them elsewhere on the site.
displaying uploaded videos:
echo "<video controls><source src='{$video_row[$i]}'></video>";
But I found out that most browsers can only play a few video formats like mp4. So I want to convert them all to mp4 before saving them to the server. So sometime before running the move_uploaded_file() function.
Is there something I can download and put on the server that will let me do that? From other questions I found about FFmpeg, but i couldn't figure out how to use it and if I can even install it on a godaddy server.
Php code:
if (isset($_FILES["submit_file"])) { //this comes from an html form
$name = $_FILES['submit_file']['name'];
$original_name = $name;
$size = $_FILES['submit_file']['size'];
$tmp_name = $_FILES['submit_file']['tmp_name'];
$target_dir = null;
$finfo = finfo_open(FILEINFO_MIME_TYPE); //get mime type
$mime = finfo_file($finfo, $tmp_name);
if ($mime == "video/mp4" || $mime == "video/wmv" || $mime == "video/avi" || $mime == "video/mov") {
if ($mime != "video/mp4") {
//CONVERT TO MP4
}
$target_dir = "uploads/videos/";
$path = $target_dir.basename($name);
if (move_uploaded_file($tmp_name, $path) == true) {
//moved
}
} else {
//error: Unsupported File Type
}
}
How do others deal with videos? I was able to upload and play mp4 videos fine with my method, but html5 can't seem to play other types, and I don't want to limit users to only upload mp4

PHP validate image file extension error

Can anybody find the problem in this code ? It keeps returning "Invalid file extension_"
PHP version 5.3.13
<?php
Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762);
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('POST exceeded maximum allowed size.');
// Settings
$save_path = getcwd() . '/uploads/';
// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'file';
// change this accordingly
$max_file_size_in_bytes = 2147483647;
// 2GB in bytes
$whitelist = array('.jpg', '.png', '.gif', '.jpeg');
// Allowed file extensions
$backlist = array('.php', '.php3', '.php4', '.phtml','.exe');
// Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s ';
// Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = '';
$file_extension = '';
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
HandleError('No upload found in \$_FILES for ' . $upload_name);
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) ||!#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed is_uploaded_file test.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
// Validate the file size (Warning: the largest files supported by this code is 2GB)
$file_size = #filesize($_FILES[$upload_name]['tmp_name']);
if (!$file_size || $file_size $max_file_size_in_bytes)
HandleError('File exceeds the maximum allowed size');
if ($file_size <= 0)
HandleError('File size outside allowed lower bound');
// Validate its a MIME Images (Take note that not all MIME is the same across different browser, especially when its zip file)
if(!eregi('image/', $_FILES[$upload_name]['type']))
HandleError('Please upload a valid file!');
// Validate that it is an image
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && isset($imageinfo))
HandleError('Sorry, we only accept GIF and JPEG images');
// Validate file name (for our purposes we'll just remove invalid characters)
$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', '', strtolower(basename($_FILES[$upload_name]['name'])));
if (strlen($file_name) == 0 || strlen($file_name) $MAX_FILENAME_LENGTH)
HandleError('Invalid file name');
// Validate that we won't over-write an existing file
if (file_exists($save_path . $file_name))
HandleError('File with this name already exists');
// Validate file extension
if(!in_array(end(explode('.', $_FILES['file']['name'])), $whitelist))
{HandleError('Invalid file extension_');}
if(in_array(end(explode('.', $_FILES['file']['name'])), $backlist))
{HandleError('Invalid file extension');}
// Rename the file to be saved
$file_name = md5($file_name. time());
// Verify! Upload the file
if (!#move_uploaded_file($_FILES[$upload_name]['tmp_name'], $save_path.$file_name)) {
HandleError('File could not be saved.');
}
exit(0);
/* Handles the error output. */
function HandleError($message) {
echo $message;
exit(0);
}
// Validate file extension
if(!in_array(end(explode('.', $_FILES['file']['name'])), $whitelist))
{HandleError('Invalid file extension_');}
if(in_array(end(explode('.', $_FILES['file']['name'])), $backlist))
{HandleError('Invalid file extension');}
?>

How to upload .mp3 file in php only after validation,my .wav file gets uploaded easily

if ((($_FILES["myfile"]["type"] == "audio/mp3") ||
($_FILES["myfile"]["type"] == "audio/wav")) &&
($_FILES["myfile"]["size"] < 20000000))
{
if (move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path) )
{
$result1=1;
}
}
just print $_FILES["myfile"]["type"]; for real mp3 file then copy the value and use it instead of audio/mp3 because MIME type of mp3 will not be 'audio/mp3', i think its audio/mpeg
Please check this Link also, because its not recommended to depend on $_FILES["myfile"]["type"] that send by browser.
Two things.
Check the size of your .mp3 file.
Check the file type of your .mp3 if it is actually audio/mp3. Try print_r($_FILES);.
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
if( ( ($type == "audio/mp3") || ($type == "audio/wav") ) && ($size < 20000000)) {
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path) ) {
$result1=1;
}
}
Hope it helps.
You can check by evaluating the extension of the uploaded file or if you want to check file level then you can one of the pear packages https://pear.php.net/package/MP3_ID

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories