.mp3 Filetype Upload - php

I'm working on a PHP upload script which allows .mp3 file uploads amongst others. I've created an array which specifies permitted filetypes, including mp3s, and set a maximum upload limit of 500MB:
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 5120000);
// create an array of permitted MIME types
$permitted = array('application/msword', 'application/pdf', 'text/plain', 'text/rtf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/tiff', 'application/zip', 'audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'application/x-rar-compressed');
So far in testing all specified filetypes have been successfully uploaded but for some reason it comes up with an error for .mp3. As you can see above I've included audio/mpeg, audio/mpeg3, and audio/x-mpeg-3 but none of them seem to make a difference.
Can someone suggest what the problem could be and also indicate which audio type is the one needed to allow .mp3 uploads?
Thanks
Update: The code I'm using to run the check on the file is as follows:
// check that file is within the permitted size
if ($_FILES['file-upload']['size'][$number] > 0 || $_FILES['file-upload']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of an permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['file-upload']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['file-upload']['error'][$number]) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// strip the extension off the upload filename
$filetypes = array('/\.doc$/', '/\.pdf$/', '/\.txt$/', '/\.rtf$/', '/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/', '/\.tiff$/', '/\.mpeg$/', '/\.mpg$/', '/\.mp4$/', '/\.mov$/', '/\.wmv$/', '/\.zip$/', '/\.rar$/', '/\.mp3$/');
$name = preg_replace($filetypes, '', $file);
// get the position of the final period in the filename
$period = strrpos($file, '.');
// use substr() to get the filename extension
// it starts one character after the period
$filenameExtension = substr($file, $period+1);
// get the next filename
$newName = getNextFilename(UPLOAD_DIR, $name, $filenameExtension);
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$newName);
}
if ($success) {
$result[] = "$file uploaded successfully";
}
else {
$result[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$result[] = "Error uploading $file. Please try again.";
default:
$result[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['file-upload']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: doc, pdf, txt, rtf, gif, jpg, png, tiff, mpeg, mpg, mp3, mp4, mov, wmv, zip, rar.";
}
I'm getting the bottom else result telling me either the file size is wrong or the extension isn't allowed.
Update 2:
I've run a print_r of the _FILES array to hopefully provide a little more info. The results are:
Array
(
[file-upload] => Array
(
[name] => Array
(
[0] => Mozart.mp3
[1] =>
[2] =>
)
[type] => Array
(
[0] => audio/mpg
[1] =>
[2] =>
)
[tmp_name] => Array
(
[0] => /Applications/MAMP/tmp/php/phpgBtlBy
[1] =>
[2] =>
)
[error] => Array
(
[0] => 0
[1] => 4
[2] => 4
)
[size] => Array
(
[0] => 75050
[1] => 0
[2] => 0
)
)
)

MAX_FILE_SIZE is a value in Bytes
5120000 is not 500 MB. It's 5MB by my reckoning.
You'll also need to check that you're not exceeding the "post_max_size" and "upload_max_size" variables in your php.ini file
Secondly, an mp3 can be any of the following mimetypes
audio/mpeg
audio/x-mpeg
audio/mp3
audio/x-mp3
audio/mpeg3
audio/x-mpeg3
audio/mpg
audio/x-mpg
audio/x-mpegaudio
http://filext.com/file-extension/MP3

You should never assume the value in $_FILES[...]['type'] actually matches the type of the file. The client can send any arbitrary string, and it's not checked at all by PHP. See here.
You'll have to do the work yourself to actually determine what type of file was uploaded, unless you have a good reason not to care about security at all (which you probably don't). PHP provides the fileinfo package by default, which does the heavy lifting for you. See finfo_file().

why not use in_array rather than the foreach loop for type check?
when you upload a valid file, have you tried checking the values of the $sizeOK & $typeOK

I doubt if you still need this but am sure many will also be facing this same problem. This is what I did and it worked for me.
Php Code:
if(isset($_POST['submit'])) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if ($fileType != 'audio/mpeg' && $fileType != 'audio/mpeg3' && $fileType != 'audio/mp3' && $fileType != 'audio/x-mpeg' && $fileType != 'audio/x-mp3' && $fileType != 'audio/x-mpeg3' && $fileType != 'audio/x-mpg' && $fileType != 'audio/x-mpegaudio' && $fileType != 'audio/x-mpeg-3') {
echo('<script>alert("Error! You file is not an mp3 file. Thank You.")</script>');
} else if ($fileSize > '10485760') {
echo('<script>alert("File should not be more than 10mb")</script>');
} else if ($rep == 'Say something about your post...') {
$rep == '';
} else {
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $uploadDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$sql = "INSERT INTO media SET
path = '$filePath',
size = '$fileSize',
ftype = '$fileType',
fname = '$fileName'";
if (mysql_query($sql)) {
echo('');
} else {
echo('<p style="color: #ff0000;">Error adding audio: ' . mysql_error() . '</p><br />');
}
and your html code will be;
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" class="file_input" name="userfile" />
<input type="submit" value="" name="submit" id="submitStatus" class="submit" />
</form>

The 5MB limit is probably your problem.

Here is some code that will give you some symbolic meaning to your errors:
class UploadException extends Exception {
public function __construct($code) {
$message = $this->codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
If you're getting an error from your last else statement, it is difficult to tell what exactly triggered it. Try using something like the above.
http://www.php.net/manual/en/features.file-upload.errors.php

Related

php image validation with zip validation

I am creating PHP image validation and zip file validation scripts my zip file validation script is working but I have added image validation but it's not working I want to add image file type jpeg,png file type I have tried to do that's not working
Here is my code
if($_FILES['fileImage']['tmp_name'][0] != "fileImage/jpg") {
die($_FILES['fileImage']['name'][0] . " is not a valid image file.");
exit;
}
$z = zip_open($_FILES['fileImage']['tmp_name'][4]);
if (!is_resource($z)) {
die($_FILES['fileImage']['name'][4] . " is not a valid ZIP file.");
}
zip_close($z);
I would first check the temp file with mime_content_type. The result does not depend on the file extension, which would be easy to manipulate. Further processing could then complete the validation.
$tmpFile = $_FILES['fileImage']['tmp_name'];
switch ($mimeType = mime_content_type($tmpFile)) {
case 'application/zip':
//... process zip ... zip_open, etc
break;
case 'image/jpeg':
//... process image ... getimagesize etc.
break;
default:
die('Unknown filetype "' . $mimeType . '".');
}
Try the following code.
$tempFile = $_FILES['file']['name'];
// Get the file extension
$fileExt = pathinfo($tempFile, PATHINFO_EXTENSION);
// Allowed extensions
$imageExt = ['jpg', 'png', 'gif'];
$compressExt = ['rar', 'zip'];
// Validation
if ( !in_array($fileExt, $imageExt) ) {
die('Not image format');
} elseif ( !in_array($fileExt, $compressExt) ) {
die('No compression format');
} else {
// proceed
}

Checking the file size and type using php

My assignment is to make a php file for uploading files to a directory. The user should only be able to upload a file if the file size is less than 512kb and the file type is txt, zip or jpg. My code is not working properly as it ignores the output if file is not relevant and it also does not check the file type properly. Can anyone help please?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Files</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="dat">
<input type="submit" value="Upload">
<div>(max. size: 512kb, Type: jpg,txt,zip)</div>
</form>
<?php
if(isset($_FILES["dat"])){
$file=$_FILES["dat"];
$name=$file["name"];
$size=$file["size"];
$location=$file["tmp_name"];
$location_file=$location . basename($name);
if($size>512000 or $location_file!="txt" or $location_file!="zip" or $location_file!="jpg"){
echo "The file is too big or the format is not correct...";
}
else{
move_uploaded_file($location,"files/".$name);
}
}
?>
</body>
</html>
In html side
<input type="file" name="dat" accept=".txt, .zip, .jpg">
In server side :
<?php
$extension = array_pop(explode(".", $_FILES["dat"]["name"])); // return file extension
if(in_array($extension, array("zip", "txt", "jpg"))) // check if extension is valid
{
if($_FILES['dat']['size'] > 512*1024) // check file size is above limit
{
echo "File size above limit";
}
else
{
move_uploaded_file($_FILES['dat']['tmp_name'],"files/".$_FILES['dat']['name']); // moving uploaded file
}
}
else
{
echo "Invalid file type";
}
First try to debug your uploaded file. Secondly don't rely on the name of the file since it can be spoofed easily.
tmp_name gives you the files temporary location, which will be a random string.
Your best option is to call getimagesize on tmp_name, for images, and finfo_open or new finfo for other file types to compare its mime type, you could also explode the name and use end which will give you an extension as well. maybe define an array of accepted extensions and use in_array to check if extension is valid.
Will provide example code after I get to a PC.
LE: as promised a more complex check with comments and security concepts
<?php
// you can make sure you have every variable set
// then procced further
if(
isset(
$_FILES['dat'], $_FILES['dat']['tmp_name'],
$_FILES['dat']['name'], $_FILES['dat']['size'],
$_FILES['dat']['error']
)
){
$accepted = array(
'image/jpeg' => 'jpg',
'text/plain' => 'txt',
'application/zip' => 'zip',
);
$file = $_FILES['dat'];
$maxSize = 512 * 1024; // 512 KB
// check if any upload error occured
if( UPLOAD_ERR_OK !== $file['error'] ){
// http://php.net/manual/en/features.file-upload.errors.php
echo 'Upload error: ', $file['error'], '<br/>';
// check if file size is bigger than $maxSize
} elseif( $file['size'] > $maxSize ){
// if filesize is bigger than upload_max_filesize directive in php.ini
// script may timeout without any error
// post_max_size and upload_max_filesize need to be high enough
echo 'Error: File size is to big!<br/>';
// can proceed further
} else {
// you will need to have the fileinfo enabled in php ini to use these
$finfo = finfo_open( FILEINFO_MIME );
$mime = finfo_file( $finfo, $file['tmp_name'] );
// finfo may give you charset info as well
// text/plain; charset=utf-8 or image/jpeg; charset=binary
$mime = array_shift( explode( ';', $mime ) );
// change uploaded file name do to security reasons
// google "php null char upload"
// nice read http://resources.infosecinstitute.com/null-byte-injection-php/
$filename = md5( time() . $file['name'] ) . '.';
// if mime is accepted
if( ! array_key_exists( $mime, $accepted ) /* or use isset: ! isset( $accepted[ $mime ] ) */ ){
echo 'Error: Unsupported file type!<br/>';
// you could check if file is image and check min-max width & height
// for now move the uploaded file
} elseif( ! #move_uploaded_file( $file['tmp_name'], 'files/' . $filename . $accepted[ $mime ] ) ){
echo 'Unable to save uploaded image to <strong>',
htmlspecialchars( 'files/' . $filename . $accepted[ $mime ] ),
'</strong>';
} else {
echo '<a href="files/', htmlspecialchars( $filename . $accepted[ $mime ] ), '" target="_blank">',
htmlspecialchars( $filename . $accepted[ $mime ] ),
'</a>';
}
}
}
For format you will need to take out the extension from the file name like this:
$explode = explode(".", $name);
$extension = $explode[sizeof($explode)-1]; //return "txt", "zip" or whatever
if(!in_array($extension, ["zip","txt", "jpg", "jpeg"])){
//format error: not in correct format
} else {
//format OK
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['dat']['tmp_name']);
$allowed_mime_types = [
"image/jpg",
"image/jpeg",
"application/zip",
"plain/text"
];
if(!in_array($mime, $allowed_mime_types)){
//error format
} else {
//format OK
}
}

Multiple file upload -- works fine when all documents are uploaded fails when only few are entered

I have this form in which it is required to upload multiple files(upto 10 files). Here's what the html looks like:
<form action="fileupload.php" method="post" enctype="multipart/form-data">
<tr><td><input type="hidden" name="consultant_id" value="<?php echo $consult_id; ?>"></td></tr>
<tr><td>Offer letter:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Project acceptance agreement:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Employee book:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>State W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td><input type="submit" name="submit" value="Upload"> </td></tr>
</form></table>
I want to upload the files to the server and store their respective paths in database(MySql). Now the following php code works awesome when I give input to all file fields(upload all 10 files) but fails when I want to upload only some files(say 5). Here's the code :
<?php
$consultant_id = $_POST['consultant_id'];
echo $consultant_id;
$verified_start_date = $_POST['verified_start_date'];
// Assign valid types
$valid_mime = array(
'application/pdf',
'image/jpeg',
'image/jpg',
);
function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
global $valid_mime;
// $files must be given.
if(!isset($files)) return false;
// Look for $valid_mime array.
isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');
// Make directory if it does not exists. set permission to 0777.
is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);
//is_dir($consultant_id) and ($dir, 0777) or mkdir($dir/$consultant_id, 0777, true);
$count = 1;
foreach($files as $file){
$file['error'] === UPLOAD_ERR_OK or die('Error in uploading file(s).');
// Check uploaded-file type.
in_array($file['type'], $valid_mime) or die();
// Set size_limit in KB.
$file['size'] > $size_limit*1024 and die('The uploaded file exceeds the maximum file size.');
$file_extension = strrchr($file['name'], '.');
$filename = basename($file['name'], $file_extension);
$file_path = "{$dir}/{$filename}{$file_extension}";
// Move uploaded-file from php temp folder to desire one.
move_uploaded_file($file["tmp_name"], $file_path);
// Make an array of filepaths
$output[] = $file_path;
}
// Change permission of folder according to security issues.
chmod($dir, 0755);
return $output;
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Controller Section ////////////////////////////////
// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');
// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
$files[] = array(
'name' => $tmp_arr['name'][$i],
'type' => $tmp_arr['type'][$i],
'tmp_name' => $tmp_arr['tmp_name'][$i],
'error' => $tmp_arr['error'][$i],
'size' => $tmp_arr['size'][$i],
);
}
// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);
?>
I have not mentioned the part where data is entered in database, as I know the problem is somewhere in $tmp_arr['error'][$i] or $file['error'] === UPLOAD_ERR_OK or die('Error in uploading file(s).');
Please take a look.
The problem appears to be that when you have a blank file input, it returns an 'error' value of 4 which means UPLOAD_ERR_NO_FILE. So since the field doesn't match UPLOAD_ERR_OK you immediately stop all code by calling die stopping any files after the first blank from copying over. If the first field was blank, nothing would get get to the move_uploaded_file. If the third out of ten was blank, then the first two files would get copied and when the third was processed it would stop any further files. But you would still just see the error "Error in uploading file(s)."
Edit:
<?php
$consultant_id = $_POST['consultant_id'];
echo $consultant_id;
$verified_start_date = $_POST['verified_start_date'];
// Assign valid types
$valid_mime = array(
'application/pdf',
'image/jpeg',
'image/jpg',
);
function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
global $valid_mime;
// $files must be given.
if(!isset($files)) return false;
//please use proper if statements. This is confusing.
//isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');
// Look for $valid_mime array.
if(!isset($valid_mime) || !is_array($valid_mime)) {
die('Error in data resources, valid_mime array not found.');
}
//please use proper if statements. This is confusing.
// is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);
// Make directory if it does not exists. set permission to 0777.
if(!is_dir($dir)) {
mkdir($dir, 0777, true);
} else {
//try to chmod if the directory does exist
chmod($dir, 0777);
}
if(!is_writable($dir)){
die('Error unable to write to specified directory.');
}
foreach($files as $key=>$file){
//switch case on the error code
//you can find a list of these error codes at: http://php.net/manual/en/features.file-upload.errors.php
switch($file['error']){
default:
//triggered if an unknown error happened. Newer php versions might bring new constants.
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'An unknown error occurred');
break;
case UPLOAD_ERR_INI_SIZE:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'File size exceeds ini setting');
break;
case UPLOAD_ERR_FORM_SIZE:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'File size exceeds MAX_FILE_SIZE setting');
break;
case UPLOAD_ERR_PARTIAL:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'File was only partially uploaded');
break;
case UPLOAD_ERR_NO_FILE:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'File input was blank');
break;
case UPLOAD_ERR_NO_TMP_DIR:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'Missing temporary folder');
break;
case UPLOAD_ERR_CANT_WRITE:
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
break;
case UPLOAD_ERR_OK:
//upload worked fine
// Check uploaded-file type.
if(in_array($file['type'], $valid_mime)){
// Set size_limit in KB.
if($file['size'] <= $size_limit*1024){
//get the file extension.
$file_extension = strrchr($file['name'], '.');
//get the filename
$filename = basename($file['name'], $file_extension);
//full filename and path
$file_path = "{$dir}/{$filename}{$file_extension}";
// Move uploaded-file from php temp folder to desire one.
// function returns true if the move was successful
if(move_uploaded_file($file["tmp_name"], $file_path)){
$output[$key] = array('error'=>false, 'message'=>'File was uploaded successfully', 'file'=>$file_path);
} else {
$output[$key] = array('error'=>true, 'message'=>'Unspecified error when moving the uploaded file');
}
} else {
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'The uploaded file exceeds the maximum file size');
}
} else {
//log error for this file
$output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
}
}
}
// Change permission of folder according to security issues.
chmod($dir, 0755);
return $output;
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Controller Section ////////////////////////////////
// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');
// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
$files[] = array(
'name' => $tmp_arr['name'][$i],
'type' => $tmp_arr['type'][$i],
'tmp_name' => $tmp_arr['tmp_name'][$i],
'error' => $tmp_arr['error'][$i],
'size' => $tmp_arr['size'][$i],
);
}
// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);
If I were doing this, this is the function I would use. If one uploaded file has a problem, it won't stop the remaining files from uploading and translates the 'error' key from $_FILES into a more user friendly message. You could easily loop over the return array and check the boolean 'error' key to see if a specific file has a problem. If 'error' is true, you could echo the message for the user to see. If there was no error, the message 'File was uploaded successfully' can be displayed. The keys from the return array correspond to the same keys found in the array passed in. So $file[0] is the same file as $returnResult[0] for easy reference.

How to Rename Image File on Upload Using this Script

Please could someone show me where i need to change the code so that the image uploaded is renamed to "freddy" for e.g.
But still carries the correct existing extension i.e jpg, png, gif.
Thanks In Advance
<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/home/richard/public_html/testing/editable-images/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg',
'image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
// Uncomment to stop overwritten files >>>> if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success =
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR .
$file);
// Uncomment to stop overwritten files >>>> } else {
// Uncomment to stop overwritten files >>>> $result = 'A file of the same name already exists.';
// Uncomment to stop overwritten files >>>>> }
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
// get file extension
$ext = end(explode($_FILES['image']['name']));
// name your file and preserve file extension
$file = "freddy.".$ext;
// create an array of permitted MIME types
....
Check description of method move_uploaded_file here

Method keeps returning false when it should return true?

I have a method that checks if a thumbnail is validate for uploading. For some reason it is returning false in the calling program.
The image file definitely meets the requirements that I set for it in terms of correct size, dimensions, file type and there are no errors in the file.
This is the print_r() of the Image file:
imageArray ( [file] => Array ( [name] => juliensbook2slide.jpg [type] => image/jpeg [tmp_name] => C:\Users\chris\AppData\Local\Temp\php5A99.tmp [error] => 0 [size] => 20590 ) )
Here is the method code:
public function checkThumb(){
$this->temp_dir = $_FILES['file']['tmp_name'];
$this->image_type = $_FILES['file']['type'];
$this->image_size = $_FILES['file']['size'];
$this->image_name = $_FILES['file']['name'];
$this->image_error = $_FILES['file']['error'];
#$this->image_dimensions = getimagesize($this->temp_dir);
$this->image_width = $this->image_dimensions[0]; // Image width
$this->image_height = $this->image_dimensions[1]; // Image height
$this->path = '';
$this->error = '';
if(!empty($this->image_name) && $this->image_error == 0){
$this->path = 'img/thumb_/'.$this->random_name. $_FILES['file']['name'];
if(in_array($this->image_type, $this->allowed_type)){
if($this->image_size <= $this->max_size){
if(($this->image_width < $this->max_width) && $this->image_height < $this->max_height){
return true;
}else{
return $error = 'ERROR: Image dimension must be no larger than 4050x4050';
}
}else{
return $error = 'ERROR: Image size must be no larger than 5MB';
}
}else{
return $error = 'ERROR: image must be .jpg, .gif, .png only.';
}
}else {
return false;
}
}
and here is the code where it is not moving the uploaded image because it is returning false:
if($register->checkThumb){
//send image to permanent image directory
$register->moveUploadedImage();
//if the thumbnail failed validation put the error message in variable
}else if(is_string($register->checkThumb())){
$message = $register->checkThumb();
}
print_r($_FILES);
//put record of user into database
$register->convertSex();
$register->insertIntoDB($thumb);
}
So why is it returning false?
You weren't calling the method. There were no round brackets after the method name. So basically you were checking if a property named checkThumb is set.
As in $register->checkThumb vs. $register->checkThumb().
This should work:
if($register->checkThumb()){ //send image to permanent image directory
$register->moveUploadedImage();
} //if the thumbnail failed validation put the error message in variable
else if(is_string($register->checkThumb())) {
$message = $register->checkThumb();
}
But i would recommend not calling the same method 3 times so I'd use the following:
$checked_thumb = $register->checkThumb();
if($checked_thumb){ //send image to permanent image directory
$register->moveUploadedImage();
} //if the thumbnail failed validation put the error message in variable
else if(is_string($checked_thumb)) {
$message = $checked_thumb;
}

Categories