I am creating simple file upload (for pictures). I tried in Opera and in FireFox and uploading is working fine. But when I upload via Google Chrome, picture is not uploaded. Can you please tell me where is problem:
here is php script that is used for storing picture in database
<?php
$id=$_SESSION['user_id'];
$user_id=$_SESSION['user_id'];
$album_id=$_POST['album'];
$max_size = 500; // Sets maxim size allowed for the uploaded files, in kilobytes
// sets an array with the file types allowed
$allowtype = array('bmp', 'gif', 'htm', 'html', 'jpg', 'jpeg', 'mp3', 'pdf', 'png', 'rar', 'zip');
// if the folder for upload (defined in $updir) doesn't exist, tries to create it (with CHMOD 0777)
/*if (!is_dir($updir)) mkdir($updir, 0777);*/
/** Loading the files on server **/
$result = array(); // Array to store the results and errors
// if receive a valid file from server
if (isset ($_FILES['files'])) {
// checks the files received for upload
$file_name=$_FILES['files']['name'];
$file_type=$_FILES['files']['type'];
$file_size=$_FILES['files']['size'];
$file_tmp=$_FILES['files']['tmp_name'];
for($f=0; $f<count($_FILES['files']['name']); $f++) {
$file_name = $_FILES['files']['name'][$f];
$random_name=rand();
// checks to not be an empty field (the name of the file to have more then 1 character)
if(strlen($file_name)>1) {
// checks if the file has the extension type allowed
$type=explode('.', $file_name);
$type=end($type);
if (in_array($type, $allowtype)) {
// checks if the file has the size allowed
if ($_FILES['files']['size'][$f]<=$max_size*1000) {
// If there are no errors in the copying process
if ($_FILES['files']['error'][$f]==0) {
$query = mysql_query("SELECT username from users WHERE id = '$id' ");
while($run=mysql_fetch_array($query)){
$username=$run['username'];
}
$query = mysql_query("SELECT album.name an from album WHERE album.id = '$album_id' ");
while($run=mysql_fetch_array($query)){
$album_name=$run['an'];
}
mysql_query("INSERT INTO photos VALUE ('', '$album_id', '$random_name.jpg', '$user_id')");
// Sets the path and the name for the file to be uploaded
// If the file cannot be uploaded, it returns error message
if (move_uploaded_file ($_FILES['files']['tmp_name'][$f],"./users/".$username."/".$album_name."/".$random_name.".jpg")) {
/*$result[$f] = ' The file could not be copied, try again';*/
$result[$f] = '<b>'.$file_name.'</b> - OK';
}
else {
$result[$f] = ' The file could not be copied, try again';
}
}
}
else { $result[$f] = 'The file <b>'. $file_name. '</b> exceeds the maximum allowed size of <i>'. $max_size. 'KB</i>'; }
}
else { $result[$f] = 'File type extension <b>.'. $type. '</b> is not allowed'; }
}
}
// Return the result
$result2 = implode('<br /> ', $result);
echo '<h4>Files uploaded:</h4> '.$result2;
}
?>
and here is form that is used for picture uploading:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
<br>
Select album:
<select name="album">
<?php
$query=mysql_query("SELECT id, name, user_id FROM album WHERE user_id = '$id'");
while($run=mysql_fetch_array($query)){
$album_id=$run['id'];
$album_name=$run['name'];
$album_user = $run['user_id'];
echo "<option value='$album_id'>$album_name</option>";
}
?>
</select>
<br /><br />
<h1>Chose your photo/s</h1>
<br>
<input type="file" name="files[]" />
<input type="submit" value="UPLOAD" id="sub" />
</form>
EDIT:
THis is error according to PHP(it's in first script that store uploaded file):
Notice: Undefined index: album in..
After conversing with the OP, the problem lay in this line:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
Where onSubmit="uploading(this); return false" was at fault.
Related
I am getting the undefined index error as I come for the first time in my upload form page or if I move to next page and click on back button then I have the same error message.
If I upload a file then it works fine and the error message gets away.
I have also tried this:
global $file;
if (!isset($file)) {
$file = '';
}
Here is my code:
<form id="uploadForm" name="upload" enctype="multipart/form-data"/>
<fieldset>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="file" />
<?php
echo '<pre>';
var_dump($_REQUEST['file']);
echo '</pre>';
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
?>
<div class="filesize">JPG minimaal 800x60 pixels max. 2Mb</div>
<span> Upload your own photo </span>
upload_inc.php
<?
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = 'File size error (0):' . $this->user_file_size . 'KB <br>';
if ($this->user_file_size > $this->max_filesize)
$this->error = 'File size error (1):' . $this->user_file_size . 'KB<br>';
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name . " from your folder to destination directory.";
}
}
}
?>
"Undefined index" means you're trying to read an array element that doesn't exist.
Your specific problem seems to be that you're trying to read upload data that doesn't exist yet: When you first visit your upload form, there is no $_FILES array (or rather, there's nothing in it), because the form hasn't been submitted. But since you don't check if the form was submitted, these lines net you an error:
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
They're all trying to read the value of $_FILES['file'] to pass them to the methods of $uploaded.
What you need is a check beforehand:
if (isset($_FILES['file'])) {
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
}
The error is probably in your upload class. The error message is pretty clear, if that is the actual message you get there is probably a line somewhere in that class that looks for an array key I that is named 'fileUpload'.
Just do a search in your code for 'fileUpload', and add something to check if the key is set, ie
if(isset($arraywhatever['fileUpload'])) condition to your code.
I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
Just playing around with uploading files as it's actually something I've never done before. I copied some supposedly working code from here.
I'm using cPanel hosting from Namecheap, with absolutely nothing changed from the default config.
I think the most likely problem is something very basic that I haven't activated. My HTML looks like this
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and my PHP looks like this
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
}
When I try to upload an image, I get a 500 Internal Server Error when I hit submit.
What am I missing?
Thanks
Get rid of the stuff at the bottom:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
Not sure what that was for... Also, try checking the Namecheap php.ini in your CPanel to see what the max upload size is so your users get your error, not a PHP error or a 500.
Here is the form
form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
I am trying to only run my code when only when if(!empty($_FILES['image'])){ but for some reason the array is not empty upon submitting no files and only clicking submit.
Here is the rest of the code if that will help, thanks.
<html>
Image Upload
<form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
<?php
include 'connect.php';
if(!empty($_FILES['image'])){
echo $_FILES['image']['error'];
$allowed = array('jpg', 'gif', 'png', 'jpeg');
$count = 0;
foreach($_FILES['image']['name'] as $key => $name){
$image_name = $name;
$tmp = explode('.', $image_name);
$image_extn = strtolower(end($tmp)); //can only reference file
$image_temp = $_FILES['image']['tmp_name'][$count];
$filesize = filesize($_FILES['image']['tmp_name'][$count]);
$count = $count +1;
if(count($_FILES['image']['tmp_name']) > 5){
echo "You can upload a maximum of five files.";
break;
}
else if(in_array($image_extn, $allowed) === false){
echo $name." is not an allowed file type<p></p>";
}
else if($filesize > 1024*1024*0.3){
echo $name." is too big, can be a maximum of 3MB";
}
else{
$image_path = 'images/' . substr(md5($name), 0, 10) . '.' . $image_extn;
move_uploaded_file($image_temp, $image_path);
mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image_path')") or die(mysql_error());
$lastid = mysql_insert_id();
$image_link = mysql_query("SELECT * FROM store WHERE id = $lastid");
$image_link = mysql_fetch_assoc($image_link);
$image_link = $image_link['image'];
echo "Image uploaded.<p></p> Your image: <p></p><a href = $image_link>$image_path</a>";
}
}
}
else{
echo "Please select an image.";
}
?>
This is how $_FILES array looks like when nothing uploaded
Array ( [image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )
So it's never empty.
The error code 4 [error] => 4 indicates no file was uploaded and error code 0 indicates no error and file was uploaded so you can check
if($_FILES['image']['error']==0) {
// file uploaded, process code here
}
Here is another answer on SO.
Use the is_uploaded_file PHP function instead:
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
//code here
}
http://php.net/manual/en/function.is-uploaded-file.php
You should first of all take a look into the PHP manual because - you're not the first one with that problem - the solution has been written in there:
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
So if you actually want to find out if any file for the image element has has been submitted, check for it:
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
Yes, that simple it is.
The test you used:
empty($_FILE);
will only tell you if the whole form has been submitted or not. So an example in full:
$submitted = empty($_FILE);
if ($submitted) {
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
if ($noFile) {
...
}
}
Check value is not null:
in_array(!null,$_FILES['field_name']['name'])
if($_FILES['image']['error'] === UPLOAD_ERR_OK) {
// Success code Goes here ..
}
UPLOAD_ERR_OK returns value 0 if there is no error, the file was uploaded successfully.
http://php.net/manual/en/features.file-upload.post-method.php
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name']
as none.
You get an array entry per "file" upload field, even if the user didn't select a file to upload.
I have confronted this issue with a multiple file input.
What I found to be working for checking if any file has been selected is:
<?php
$size_sum = array_sum($_FILES['img']['size']);
if ($size_sum > 0) {
// at least one file has been uploaded
} else {
// no file has been uploaded
}
?>
if(!empty($_FILES['image']['name'][0]) || !empty($_FILES['image']['name'][1]) ||
!empty($_FILES['image']['name'][2]))
or
for($1=0;$i<count($_FILES['image']);$i++){
if(!empty($_FILES['image']['name'][$i])){
// do something
}
}
if(isset($_FILES['file'])){//do some thing here}
I am getting the undefined index error as I come for the first time in my upload form page or if I move to next page and click on back button then I have the same error message.
If I upload a file then it works fine and the error message gets away.
I have also tried this:
global $file;
if (!isset($file)) {
$file = '';
}
Here is my code:
<form id="uploadForm" name="upload" enctype="multipart/form-data"/>
<fieldset>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="file" />
<?php
echo '<pre>';
var_dump($_REQUEST['file']);
echo '</pre>';
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
?>
<div class="filesize">JPG minimaal 800x60 pixels max. 2Mb</div>
<span> Upload your own photo </span>
upload_inc.php
<?
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = 'File size error (0):' . $this->user_file_size . 'KB <br>';
if ($this->user_file_size > $this->max_filesize)
$this->error = 'File size error (1):' . $this->user_file_size . 'KB<br>';
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name . " from your folder to destination directory.";
}
}
}
?>
"Undefined index" means you're trying to read an array element that doesn't exist.
Your specific problem seems to be that you're trying to read upload data that doesn't exist yet: When you first visit your upload form, there is no $_FILES array (or rather, there's nothing in it), because the form hasn't been submitted. But since you don't check if the form was submitted, these lines net you an error:
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
They're all trying to read the value of $_FILES['file'] to pass them to the methods of $uploaded.
What you need is a check beforehand:
if (isset($_FILES['file'])) {
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
}
The error is probably in your upload class. The error message is pretty clear, if that is the actual message you get there is probably a line somewhere in that class that looks for an array key I that is named 'fileUpload'.
Just do a search in your code for 'fileUpload', and add something to check if the key is set, ie
if(isset($arraywhatever['fileUpload'])) condition to your code.