Jump to content

How to handle file from multiple upload?


nanie

Recommended Posts

I have form where user have to fill in and upload several file. I plan to keep the files in upload folder under the ID of user (eg: ../upload/userID/filename) and save each dir of files in database so that it is easier (?) to retrieve later. But, since I am not familiar with the process, I kind of stuck with the codes.

 

student_newSubmission.php (since it is long forms/codes, I put several only)

<form action="student_newSubmission.php" method="post" enctype="multipart/form-data">
<table width="1023" cellpadding="2" cellspacing="2">
  <tr>
  	<td width="160"><strong>Full Name :  </strong></td><td colspan="3"><?php echo $row['STDNAME']; ?><style="text-transform: uppercase" required value="" /></td>
  </tr>
  
  <tr>
  	<td><strong>Sponsor :  </strong></td><td width="374"><input name="sponsor" type="text" size="50" style="text-transform: uppercase"></td>
    <td><strong>Admission Date : </strong></td><td width="309"><?php echo $date; ?> <input type="hidden" name="admissionDate" id="admissionDate" value="<?php $date;?>" style="text-transform: uppercase" required value="" /></td>
  </tr> 
  
  <tr>
  	<td><strong>Matric No : </strong></td><td width="374"><?php echo $row['MATRICNO']; ?> <input type="hidden" name="matricNo" id="matricNo" value="<?php echo $row["MATRICNO"]; ?>" style="text-transform: uppercase" required value="" /></td>
    <td><strong>Email Address :</strong></td><td width="309"><?php echo $row['EMAIL']; ?> </td>
  </tr>
.
.
.
.
.
</table>

.
.
.
.

<fieldset style="width:500px; background-color: #FFC"><legend align="center" style="font-size:24px">Upload file</legend>
<p style="color:#F00"> ( Please take note to name your files accordingly and save as .pdf or .doc ) </p>
<table width="809" cellpadding="2" cellspacing="2">
  <tr>
  <td width="252"><label for="file">Acceptance Letter from Publisher:</label></td>
  <td width="541"><input type="file" name="file" id="acceptletter" onchange=checkFile(this)  required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Turnitin Similarity Report :</label></td>
  <td width="541"><input type="file" name="file" id="turnitin" onchange=checkFile(this) required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Paper Indexing :</label></td>
  <td width="541"><input type="file" name="file" id="paperindex" onchange=checkFile(this) > <br />/ Link : <input type="text" name="paperindexurl" size="30" /></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Publisher's Reviewers Report :</label></td>
  <td width="541"><input type="file" name="file" id="reviewerReport" onchange=checkFile(this) required value=""></td>
  </tr>
</table></fieldset>

this is what I already try... edit from what I found in the forum.

if(isset($_POST['submit']) && !empty($_POST['submit']))
{
	$sponsor = $_POST['sponsor'];
	$admissionDate = $_POST['admissionDate'];
	$matricNo= $_POST['matricNo'];
        .
        .
        .
        $paperindexurl= $_POST['paperindexurl'];
	$submittedVersionurl= $_POST['submittedVersionurl'];
	$confPaperurl=$_POST['confPaperurl'];


        if (isset($_FILES['file']) && !empty($_FILES['file']))
		{
    		$num_files = count($_FILES['file']);
    		for($x =0; $x < $num_files; $x++)
			{	
			$filename = $_FILES['file']['name'][$x];
			$tempName = $_FILES['file']['tmp_name'][$i];
			$allowed_ext = array ('doc', 'docx','pdf');
			$file_ext = strtolower(end(explode('.', $filename)));
			
			if ((filesize($filename) > 1048576) && (in_array($file_ext, $allowed_ext) == false))
				{
				header('location: student_newSubmission.php?error=6');
                	        exit();
				}
					
        	         elseif ($_FILES['file']['error'][$x] == UPLOAD_ERR_OK) 
				{
            	                $saveDirectory = '../upload/'.$matricNo.'/';
            	                if (@move_uploaded_file($tempName, $saveDirectory . $fileName)) 
					{
                	                 echo 'File Successfully Uploaded!';
            		                 } 
				else 
					{
                	                echo 'There was an error whilst uploading the file.';
            		                }
        		        }			
    		          }    
		     } 


	$query= "INSERT INTO submission VALUES(seq_subID.nextval, '$matricNo', '$sponsor', '$admissionDate', '$programme', '$sem', '$field', '$supervisor', '$cosupervisor', '$papertitle', '$author', '$conftitle', '$organizer', '$address', '$tel', '$venue', '$confDate', '$fee' , .................."; 
	$parse= oci_parse($conn, $query)or die(oci_error());
	$exe= oci_execute($parse);
	
	if ($exe == 1)
	{
  		header('location:homeStudent.php');
		echo '<script type="text/javascript">';
		echo 'alert ("Successfully upload your form!")';
		echo '</script>';
	}
	else
	{
		echo '<script type="text/javascript">';
		echo 'alert("There was an error while uploading your form. Please try again.")';
		echo '</script>';
	}
	
}


and here is submission table..

         subID NUMBER(4) NOT NULL,
	 matricNo VARCHAR2 (10)NOT NULL,
	 sponsor VARCHAR2(10),
	 admissionDate DATE NOT NULL,
	 programme VARCHAR2(10), 
 	 sem VARCHAR2(4) NOT NULL,
	 field VARCHAR2(10) NOT NULL, 
	 supervisor VARCHAR2(50) NOT NULL,
	 cosupervisor VARCHAR2(50) NOT NULL,
 	 papertitle VARCHAR2(50) NOT NULL,
	 author VARCHAR2(150) NOT NULL,
	 conftitle VARCHAR2(50) NOT NULL,
	 organizer VARCHAR2(20),
	 orgaddress VARCHAR2(50),
	 orgtel VARCHAR2(20),
	 venue VARCHAR2(30),
	 confDate DATE,
	 fee NUMBER(10),
	 file1 VARCHAR2(30) NOT NULL,
	 file2 VARCHAR2(30) NOT NULL,
	 file3 VARCHAR2(30),
	 indexurl VARCHAR2(30),
 	 file4 VARCHAR2(30) NOT NULL,
 	 submitversionurl VARCHAR2(30) NOT NULL,
	 confpaperurl VARCHAR2(30),
	 file5 VARCHAR2(30) NOT NULL,
	 file6 VARCHAR2(30) NOT NULL);

So far, is it correct what I am doing.? From the code above, nothing happen when I try to submit. Not even check the file. Please anyone show me the way.. I really don't know how to proceed.

Link to comment
Share on other sites

When giving fields in a form the same name you need to add [] (square brakets) after the name, eg name="file[]".  When the form is submitted the the $_FILES superglobal will be an array of uploaded files. If you dont add the [] in the name then only the last file will be uploaded. 

 

This is how your file fields should be named

<input type="file" name="file[]" id="acceptletter" onchange=checkFile(this)  required value=""></td>

<input type="file" name="file[]" id="turnitin" onchange=checkFile(this) required value=""></td>

<input type="file" name="file[]" id="paperindex" onchange=checkFile(this) > <br />/ Link : <input type="text" name="paperindexurl" size="30" /></td>

<input type="file" name="file[]" id="reviewerReport" onchange=checkFile(this) required value=""></td>

 

Now the code for looping over the uploaded files should work.

Edited by Ch0cu3r
Link to comment
Share on other sites

Even better, give the files a proper index, like the id that you use in the HTML. That way you don't have to guess  which file is which:

 

<input type="file" name="file[acceptletter]" id="acceptletter" onchange=checkFile(this)  required value=""></td>
<input type="file" name="file[turnitin]" id="turnitin" onchange=checkFile(this) required value=""></td>

 

Loopingh will still work, but now you also know which file is which.

Link to comment
Share on other sites

Dear @Ch0cu3r and vinny42 , I've try the solution you guys give me. But once I submit, it will return to the page form and empty the field that I insert before.

 

* I already commented the query part since I want to see if the files successfully uploaded.

 
Link to comment
Share on other sites

if you're naming the file input fields as file[] then you have a few problems with the for loop that processes the uploaded files.

$tempName = $_FILES['file']['tmp_name'][$i];

$i above should be $x. Your for loop increments $x not $i.

 

Next

$file_ext = strtolower(end(explode('.', $filename))); 

use pathinfo to reliably get the file extension

$file_ext = pathinfo($filename, PATHINFO_EXTENSION);

To check the uploaded files size you need to check the $_FILES['file']['size][$x] variable, not filesize($filename).

if ((filesize($filename) > 1048576) && (in_array($file_ext, $allowed_ext) == false))

If you're naming the fields as vinny42 suggests then you'll need to use a foreach loop instead of a for loop. replacing the for loop construct with this foreach construct may work.

foreach($_FILES['file']['name'] as $x => $value)
Edited by Ch0cu3r
Link to comment
Share on other sites

I still face the same problem..What else should I do to make it successful?

 

Below is what I've change.

if (isset($_FILES['file']) && !empty($_FILES['file']))
        {
            $num_files = count($_FILES['file']);
            for($x =0; $x < $num_files; $x++)
            {    
            $filename = $_FILES['file']['name'][$x];
            $tempName = $_FILES['file']['tmp_name'][$x];
            $allowed_ext = array ('doc', 'docx','pdf');
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
            
            if (($_FILES['file']['size'][$x] > 1048576) && (in_array($file_ext, $allowed_ext) == false))
                {
                header('location: student_newSubmission.php?error=6');
                    exit();
                }
                    
            elseif ($_FILES['file']['error'][$x] == UPLOAD_ERR_OK)
                {
                $saveDirectory = "../upload/'.$matricNo.'/";
                if (move_uploaded_file($tempName, $saveDirectory.$fileName))
                    {
                    echo 'File Successfully Uploaded!';
                    }
                else
                    {
                    echo 'There was an error whilst uploading the file.';
                    }
                }            
            }    
        }
Link to comment
Share on other sites

what is your current form code? depending on which of the suggestions you used, the method you use to loop over the uploaded files changes.

 

edit: or you could just use a foreach(){} loop that would work regardless of the naming of the form fields.

Edited by mac_gyver
Link to comment
Share on other sites

@mac_gyver, here is my current code.

<fieldset style="width:500px; background-color: #FFC"><legend align="center" style="font-size:24px">Upload file</legend>
<p style="color:#F00"> ( Please take note to name your files accordingly and save as .pdf or .doc ) </p>
<table width="809" cellpadding="2" cellspacing="2">
  <tr>
  <td width="252"><label for="file">Acceptance Letter from Publisher:</label></td>
  <td width="541"><input type="file" name="file[]" id="acceptletter" onchange="checkFile(this)"  required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Turnitin Similarity Report :</label></td>
  <td width="541"><input type="file" name="file[]" id="turnitin" onchange="checkFile(this)" required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Paper Indexing :</label></td>
  <td width="541"><input type="file" name="file[]" id="paperindex" onchange="checkFile(this)" > <br />/ Link : <input type="text" name="paperindexurl" size="30" /></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Publisher's Reviewers Report :</label></td>
  <td width="541"><input type="file" name="file[]" id="reviewerReport" onchange="checkFile(this)" required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Paper Submitted Version :</label></td>
  <td width="541">Link : <input type="text" name="submittedVersionurl" size="30" required value="" /></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Published Conference Paper :</label></td>
  <td width="541">Link : <input type="text" name="confPaperurl" size="30" required value=""/></td>
  </tr>  
  <tr>
  <td width="252"><label for="file">Camera Ready Paper (full) :</label></td>
  <td width="541"><input type="file" name="file[]" id="cameraReady" onchange="checkFile(this)" required value=""></td>
  </tr>
  <tr>
  <td width="252"><label for="file">Blind Paper (withour author info) :</label></td>
  <td width="541"><input type="file" name="file[]" id="blindPaper" onchange="checkFile(this)" required value=""></td>
  </tr>

and the php still the same as the post above you.

Link to comment
Share on other sites

What does the PHP code currently output? any errors/messages etc. What is it doing now? What should it be doing?

 

Your form code should work with the changes I suggested earlier.

 

I have tested the form code and php code and it is uploading files. However this line

if (($_FILES['file']['size'][$x] > 1048576) && (in_array($file_ext, $allowed_ext) == false))

had to be changed to

if ($_FILES['file']['size'][$x] > 1048576 || !in_array($file_ext, $allowed_ext) 

To stop non .doc, docx and .pdf files from uploading.

Edited by Ch0cu3r
Link to comment
Share on other sites

your form processing code is not testing if the upload worked at all before trying to use the uploaded file information and your current symptom is either due to your form processing code being entirely skipped over due to the conditional tests being false or your form is not using the ?error=n information it does receive.
 
if you use this forum's advanced search (the white star like thing to the right of the search box) and search for find words uploaded and find author mac_gyver, you will get a number of replies concerning testing for upload errors.
 
briefly - both the $_FILES and $_POST array will be empty if the total of the content being submitted exceeds the post_max_size setting. next the file ['name'] element will be set, but the other fields won't be for most of the possible ['error'] element values (see this link for the errors - http://us1.php.net/manual/en/features.file-upload.errors.php), the most common one being that an individual file exceeds the upload_max_filesize setting or in this case No file was uploaded (selected) for a file field (if you don't require an uploaded file from each file field, you will need to test for this error number and ignore it, rather than report it back to the user. however if one or more of the file fields is required, you would need to report back to the user that they must select a file to upload.)

so, you must test if a form has been submitted, then test if the $_FILES array is not empty, then for each of the possible file fields test if the ['error'] element is set and is a zero.
 
it also wouldn't hurt to output a distinct and verbose message for each of the possible conditions that have failed telling the user what is wrong with his uploaded file(s) that caused them to not be processed.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.