Jump to content

Uploading multiple files on with data issue


frc

Recommended Posts

Hi there, I have a form submitting to a mysql database. It was requested that I put a multiple file upload option on it. So I added the fields to the form and the database and added the upload script to the form processing file (and of course created the folder on the server with proper permissions to upload to). It should upload the file(s) to the folder on the server and insert the filename into the database. I keep getting:

 

HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

 

This leads me to believe the upload script isn't working properly. If someone could take a look at it I would be a very happy guy.

 

This is the upload script: (insert.php)

<?php

$con = mysql_connect("server","user","pass");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }



mysql_select_db("db", $con);



$dateSubmitted = date("Y-m-d"); 

$target = "attachments/"; 
$target = $target . basename( $_FILES['doc1']['name']); 
$target = $target . basename( $_FILES['doc2']['name']); 
$target = $target . basename( $_FILES['doc3']['name']); 
$target = $target . basename( $_FILES['doc4']['name']); 
$target = $target . basename( $_FILES['doc5']['name']); 




$sql="INSERT INTO investments (active, project, inv_amount, account_type, prefix, first_name, last_name, address1, address2, city, province, postal_code, country, phone, email, referral_fee, ref_agent, ship_name, ship_address, ship_city, ship_province, ship_postal, ship_country, notes, dateSubmitted, doc1, doc2, doc3, doc4, doc5)

VALUES

('$_POST[active]','$_POST[account_type]','$_POST[project]','$_POST[inv_amount]','$_POST[prefix]','$_POST[prefix]','$_POST[first_name]','$_POST[last_name]','$_POST[address1]', '$_POST[address2]','$_POST[city]','$_POST[province]','$_POST[postal_code]','$_POST[country]','$_POST[phone]','$_POST[email]','$_POST[referral_fee]','$_POST[ref_agent]','$_POST[ship_name]','$_POST[ship_address]','$_POST[ship_city]','$_POST[ship_province]','$_POST[ship_postal]','$_POST[ship_country]','$_POST[notes]','$_POST[dateSubmitted]',$_FILES['doc1']['name'],$_FILES['doc2']['name'],$_FILES['doc3']['name'],$_FILES['doc4']['name'],$_FILES['doc5']['name'])";



//Writes the photo to the server 
if(move_uploaded_file($_FILES['doc1']['tmp_name'], $target)) 
if(move_uploaded_file($_FILES['doc2']['tmp_name'], $target)) 
if(move_uploaded_file($_FILES['doc3']['tmp_name'], $target)) 
if(move_uploaded_file($_FILES['doc4']['tmp_name'], $target)) 
if(move_uploaded_file($_FILES['doc5']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 



if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }	

//echo "1 record added";

header("Location: ../forms.php");



mysql_close($con)

?>

 

Thanks in advance.

 

JE

Link to comment
Share on other sites

Well, this may not be the cause of your error (based on the error message  you are getting), but one problem is you trying to use header() after sending output to the page. You cannot send any output to the browser before header() statements.

 

Currently, you are trying to display a confirmation or error message before redirecting the user to a different page. How would the user see the message anyway?

 

Remove the redirect message for testing purposes. Once it all works then remove the messages and implement the redirect. You will have to display any messaging on the redirected page.

 

Also, you have several if() statements lumped together - that doesn't make sense. Plus, it assumes that the user is ALWAYS uploading all five images. You need to do some validation before attempting to upload the file.

 

EDIT: You also have problems with your query:

1. No validation to prevent SQL injection

2. You have $_POST['prefix'] duplicated in the values, etc.

3. The fields are not in the right order. For example, $_POST['account_type'] is matched up with the project field.

 

Go back and take your time to ensure everything is kosher and add some error handling.

Link to comment
Share on other sites

Well, this may not be the cause of your error (based on the error message  you are getting), but one problem is you trying to use header() after sending output to the page. You cannot send any output to the browser before header() statements.

 

Currently, you are trying to display a confirmation or error message before redirecting the user to a different page. How would the user see the message anyway?

 

Remove the redirect message for testing purposes. Once it all works then remove the messages and implement the redirect. You will have to display any messaging on the redirected page.

 

Also, you have several if() statements lumped together - that doesn't make sense. Plus, it assumes that the user is ALWAYS uploading all five images. You need to do some validation before attempting to upload the file.

 

EDIT: You also have problems with your query:

1. No validation to prevent SQL injection

2. You have $_POST['prefix'] duplicated in the values, etc.

3. The fields are not in the right order. For example, $_POST['account_type'] is matched up with the project field.

 

Go back and take your time to ensure everything is kosher and add some error handling.

 

Thanks, I still don't have any validation or error handling inserted (still have to figure out how) but did clean up the query and removed the header and other messages. It got me to the point where when i hit submit I can see the files uploading in the status bar then at 99% it takes me to the same error page and doesn't submit... I wish i was in the matrix and could just download php guru to my brain!.. sure wish I didn't have to demo this tomorrow...

Link to comment
Share on other sites

To upload multiple files, you can use an array for input naming and to move upload files, you can loop through the array of files.

Thanks for your response. Can you give me an example I can look at and expand on? I'm not all that familiar with arrays yet but have been working on one for user management this week.

 

Great idea!

 

JE

Link to comment
Share on other sites

I am able to comment as much as I can; it could be too much blah blah...

Take the one you want

 


<?

function filename($extension)
{
	$ran_name = "";
	//This line assigns a random number to a variable.  
	for($i=0; $i<5; $i++){ $ran_name .= mt_rand(38,50); }

	//This takes the random number you generated and adds a . on the end, so it is ready of the file extension to be appended.
	$ran_name = $ran_name.".";

	//This combines the directory, the random file name, and the extension
	$newfile_name =  $ran_name.$extension;
	return $newfile_name;
}

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
	function getExtension($str) 
{ 
		$i = strrpos($str,"."); 
        if (!$i) { return ""; }        
		$l = strlen($str) - $i;         
		$ext = substr($str,$i+1,$l);         
		return $ext; 
}        
    /*** the upload directory ***/
// the path with the file name where the file will be stored, upload is the directory name.
$upload_dir ="/uploads"; 
   
    /*** numver of files to upload ***/
    $num_uploads = 6;

    /*** maximum filesize allowed in bytes ***/
    $max_file_size  = 51200;

    /*** the maximum filesize from php.ini ***/
    $ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
    $upload_max = $ini_max * 1024;

    /*** a message for users ***/
    $msg = 'Select pictures for upload';

    /*** an array to hold messages ***/
    $messages = array();

$c=0; 

    /*** check if a file has been submitted ***/
    if(isset($_FILES['userfile']['tmp_name']))
    {	 
    $count =  count($_FILES['userfile']['tmp_name']);

    /** loop through the array of files ***/
        for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
        {
           
	   $filename = stripslashes($_FILES['userfile']['name'][$i]);
	   //get the extension of the file in a lower case format 
	   $extension = getExtension($filename);
	   $extension = strtolower($extension); 
	   //if it is not a known extension, we will suppose it is an error and will not  upload the file, 
	   $New_filename =  filename($extension);
	   
	   // check if there is a file in the array
           if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
           {
                $messages[] = 'No file uploaded';
			$c++;
           }
          /*** check if the file is less then the max php.ini size ***/
/*           elseif($_FILES['userfile']['size'][$i] > $upload_max)
           {
                $messages[] = "File size exceeds $upload_max php.ini limit";
           }
*/		   // check the file is less than the maximum file size
           elseif($_FILES['userfile']['size'][$i] > $max_file_size)
           {
                $messages[] = "File size exceeds $max_file_size limit";
           }
	   elseif (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
	   {		
		    $messages[] ="Unknown extension! ";
	   }
           else
           {
			// the path with the file name where the file will be stored, upload is the directory name.
     		$add="uploads/$New_filename";
			if(move_uploaded_file ($_FILES['userfile']['tmp_name'][$i],$add))
			{	
					$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
			}
			else
                {		/*** an error message ***/
					$messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
                }		   
            }
        }
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Image Upload.</title>
<style type="text/css">
<!--
.style1 {	font-family: Arial, Helvetica, sans-serif, Calibri;	font-size: 12px;	}
.style2 {	font-family: Arial, Helvetica, sans-serif, Calibri; font-size: 9px;		}
-->
</style>
</head>
<body>
<div align="center">


<table width="95%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
<?
	echo "<h3>". $msg ."</h3>"; 
	echo "<span class='style2'>For the best quality, use the pictures that are more than 500 pixels in hight or width.</span><br/><br/>";

?>
</td>
  </tr>
  <tr>
  	<td  align='left' valign='middle'> 

</td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<?	
if(sizeof($messages) != 0)
    {	foreach($messages as $err){	echo "<span class='style1'>".$err.'</span><br />';		}
   }
?>
</p>
</td>
<tr>
<tr><td>
<form enctype="multipart/form-data" action="103.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<input type="hidden" name="counter" value="<? echo $a; ?>" />
<?php
    $num = 0;
$newNUm = $num_uploads - $a;
    while($num < $newNUm)
    {	echo '<div><input name="userfile[]" type="file" /></div>';	$num++;	   }
?>
<br/>
<input type="submit" value="Upload" />
<input type=button value="Cancel" onClick="javascript:window.close();">
</form>
</td>
</tr>

</td>
    <td width="100"> </td>
  </tr>
</table>	

</body>
</html>

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.