I have this code but this code is not allowing me to upload any types of video files.
This always shows 'Please Select File To Upload'.
Code for uploading file shown below:
$fileElementName = 'ufile';
if (!empty($_FILES[$fileElementName]['error'])) {
switch ($_FILES[$fileElementName]['error']) {
case '1':
$error = 'You Are Not Allowed To Upload File Of This Size';
break;
case '2':
$error = 'You Can Not Not Upload File Of This Size';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'Not Able To Upload';
break;
case '6':
$error = 'Server Error Please Try Again Later';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'Error Found But Did Not Found What Was Problem';
}
} elseif (empty($_FILES['ufile']['tmp_name']) || $_FILES['ufile']['tmp_name'] == 'none') {
$error = 'Please Select File To Upload';
$success = FALSE;
} else {
$file = $_FILES['ufile']['name'];
move_uploaded_file($_FILES["ufile"]["tmp_name"], $path);
}
echo json_encode($arr);
In the above code $path is upload/ which is correct--it works for all file except video.
This code always shows 'Please Select File To Upload'
Your error handling is broken. On uploads, a successful upload has error code 0 (UPLOAD_ERR_OK constant). You're doing
if (!empty(...))
empty() evaluates to boolean TRUE for zero values, so you're basically saying "if there was no error, act like there was one".
Your code really should be:
if ($_FILES['ufile']['error'] !== UPLOAD_ERR_OK) {
... error handling switch() here ...
die();
}
Your subsequent empty() checks on the tmp_name are also pointless. If no file was uploaded, then you'll get error code 4 (UPLOAD_ERR_NO_FILE) anyways.
Then for the move_uploaded_file() stuff, you pull out the uploaded filename into $file, but then move the file to $path, which is not set anywhere in your code. As a word of warning, never EVER use the user-supplied filename directly in file-system operations. It is trivial to embed path information in that field, and if you do not take appropriate sanitization/security precautions, you'll be allowing malicious users to scribble on any file on your server.
Did you defined the enctype of your form?
In the form tag insert the enctype as follow: enctype="multipart/form-data"
check permissions, if $path exists, etc, and change move_uploaded_file to copy, some servers have a restrict permission on folders
EDIT: Maybe same issue https://stackoverflow.com/a/3587158/1519436
Related
First of all I'd like to say that I am fairly new to PHP, and especially the go abouts on how to make a multiple upload script. And the problem I am encountering is how to validate the files with MIME types.
Based on my research - almost every source says to check the MIME type. I know this is because the $_FILE variables is user determined, and can cause bad files to be uploaded.
When I try to check the MIME type, I cannot get it to work. The script is supposed to only accept certain document files, and without the MIME check the script works fine. The problem is that it does not validate any file types, even if it is the ones I include in the array, and print the $errors variable.
This is the code:
foreach ($_FILES['ufile']['name'] as $f => $name) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['ufile']['tmp_name']);
$ok = false;
switch ($mime) {
case 'application/pdf':
$ok = true;
break;
case 'application/msword':
$ok = true;
break;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$ok = true;
break;
default:
$ok = false;
break;
}
if ($_FILES['ufile']['error'][$f] == 4) {
continue;
}
if ($_FILES['ufile']['error'][$f] == 0) {
if ($_FILES['ufile']['size'][$f] > $max_file_size) {
$errors[] = 'message';
continue;
}
elseif($ok == false){
$errors[] = 'message';
continue;
}
else{
if(move_uploaded_file($_FILES["ufile"]["tmp_name"][$f], "path".$name))
'queries and stuff.';
}
}
}
Any idea on what the problem might be? A new set of eyes might see something obvious that I should have seen or changed.
Thanks in advance!
I have a problem that I simply don't know how or as a matter of fact what to solve. I'm using Yii and an extension called YUSH. This helps with folder structuring when uploading an image.
On my localhost everything works great. But now that I migrated to a live server, the filename still gets written to the database but a folder containing the uploaded file is not created. Thus only an image placeholder is displayed.
This isn't giving any error messages, so I really don't know how to fix it. My host has increased my mem_size in php.ini and I have checked all my error logs. Still nothing.
Here is my code:
$image = CUploadedFile::getInstance($l, 'path');
if ($image)
{
// Clean up the filename
$encName = md5($image->name . microtime()) . '.' . $image->extensionName;
$l->path = $encName;
}
$l->merchant_id_fk = $this->getMerchantRelation(Yii::app()->user->id);
switch ($l->validate()) {
// User validate Successfull
case TRUE:
if($l->save())
{
//Save Image
Yush::init($l);
// Nothing has been uploaded yet but YUSH will return a full path that can be used to save the resource
$originalPath = Yush::getPath($l, Yush::SIZE_ORIGINAL, $l->path);
// Save the original resource to disk
$image->saveAs($originalPath);
$thumbPath = Yush::getPath($l, Yush::SIZE_THUMB, $l->path);
// Create a thumbnail
// Kohana Image library
$thumbImage = Yii::app()->image->load($originalPath);
$thumbImage->resize(350, 350)->rotate(0)->quality(100)->sharpen(10);
// $thumbImage = PhpThumbFactory::create($originalPath);
// $thumbImage->resize(350, 350);
switch ($thumbImage->save($thumbPath)) {
case true:
Yii::app()->user->setFlash('success', self::MESSAGE_SUCCESS);
$this->redirect(Yii::app()->params->local . 'merchant/profile');
break;
default:
# code...
Yii::app()->user->setFlash('error', self::MESSAGE_FAILURE);
$this->redirect(Yii::app()->params->local . 'merchant/profile');
break;
}
}
else
{
Yii::app()->user->setFlash('error', self::MESSAGE_FAILURE);
$this->redirect(Yii::app()->params->local . 'merchant/profile');
}
break;
}
Does anybody have any idea what the problem might be??
When the tmp directory is full, file_put_contents returns FALSE but the file is created with size of 0. file_put_contents should either complete the creation of the file or have no effect at all. For example:
$data = 'somedata';
$temp_name = '/tmp/myfile';
if (file_put_contents($temp_name, $data) === FALSE) {
// the message print that the file could not be created.
print 'The file could not be created.';
}
But when I go to the tmp directory, I can find the file "myfile" created in the directory with size 0. This makes it difficult to maintain. The file should not be created and I would like to see a message or warning the the tmp directory is full. Am I missing anything? And is this normal behaviors?
You are probably missing that if you do the error messages, you need to take care of that scenario, too:
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if ($success === FALSE)
{
$exists = is_file($temp_name);
if ($exists === FALSE) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}
This will also allow you to deal with it, like cleaning up if the transaction to write to the temporary file failed, to reset the system back into the state like before.
The problem is that file_put_contents will not necessarily return a boolean value and therefore your condition may not be appropriate you could try:
if(!file_put_contents($temp_name, $data)){
print 'The file could not be created.';
if(file_exists ($temp_name))
unlink($temp_name);
}
hi bro i found the Solution,
i know its old but its maybe help other people like me,
i was search about this code long time.
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if (!$success){
$exists = is_file($temp_name);
if (!$exists) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}
on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.
You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.
There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.
You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.
I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))
We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}
if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";
if ($_FILES['logo']['error'] === 0)
is the only right way
I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?
You can use is_uploaded_file():
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by
filename was uploaded via HTTP POST.
This is useful to help ensure that a
malicious user hasn't tried to trick
the script into working on files upon
which it should not be working--for
instance, /etc/passwd.
This sort of check is especially
important if there is any chance that
anything done with uploaded files
could reveal their contents to the
user, or even to other users on the
same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
#karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.
/**
* Tests all upload fields to determine whether any files were submitted.
*
* #return boolean
*/
function files_uploaded() {
// bail if there were no upload forms
if(empty($_FILES))
return false;
// check for uploaded files
$files = $_FILES['files']['tmp_name'];
foreach( $files as $field_title => $temp_name ){
if( !empty($temp_name) && is_uploaded_file( $temp_name )){
// found one!
return true;
}
}
// return false if no files were found
return false;
}
You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.
is_uploaded_file() is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).
However, if you want to check whether the user uploaded a file,
use $_FILES['file']['error'] == UPLOAD_ERR_OK.
See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.
I checked your code and think you should try this:
if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name']))
{
echo 'No upload';
}
else
echo 'upload';
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully.
https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}