Help with File Upload & MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Help with File Upload & MySQL

Post by tsm4781 »

I've written a little piece of code to upload a file to a folder on my remote server and write a title, desc, id, filename to my database. I'm running into an issue and I am wondering if you could help me.

All of the data is writing to the database just file, but the file never uploads. My directory is CHMOD 777, so I'm thinking my code must be busted in some area. If you could take a look and tell me what you think, I'd be appreciative.

Here is my control file.

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
  $table = "filemanager";
  $title = $_POST['title'];
  $leadin = $_POST['leadin'];
  $file = $_FILES['file']['name'];

if (($_FILES['file']['type'] == 'application/pdf') && ($_FILES['file']['size'] < 100000))
{
    echo '<strong>' . 'Uploading ' . $_FILES['file']['name'] . ' (' . $_FILES['file']['type'] . ', ' . ceil($_FILES['file']['size'] / 1024) . ' Kb)' . '</strong>' . '<br />';

    if (file_exists('/files/' . $_FILES['file']['name']))
    {
        echo "<p class="error">". $_FILES['file']['name']." already exists.<br />";
        echo "Please rename the file and try again.</p>";
    }
    else
    {
        move_uploaded_file($_FILES['file']['tmp_name'], '/files/' . $_FILES['file']['name']);
        echo "<p class="error">The file has been uploaded successfully</p>";
    }
} 
else
{
    echo "<p class="error">This site only accepts .pdf files only.</p>";
}

  $query = "INSERT into $table values (NULL,'$title','$leadin','$file')"; 
  $result = mysql_query($query);
  // $p is the result page
  $p = 9; //fileadd.inc.php
};

?>
This is the HTML file that I include into my control file.

Code: Select all

&lt;div id="maincontent"&gt;

&lt;form action="&lt;?PHP echo $PHP_SELF ?&gt;" method="post" enctype="multipart/form-data" name="form"&gt;

&lt;h2&gt;Add A File:&lt;/h2&gt;

&lt;h3&gt;Title:&lt;/h3&gt;
&lt;p&gt;(The main caption of the file.)&lt;/p&gt;
&lt;p&gt;&lt;textarea name="title" cols="60" id="title" rows="1"&gt;&lt;?php echo $title ?&gt;&lt;/textarea&gt;&lt;/p&gt;

&lt;h3&gt;Lead In Text:&lt;/h3&gt;
&lt;p&gt;(Description of the file.)&lt;/p&gt;
&lt;p&gt;&lt;textarea name="leadin" cols="60" id="leadin" rows="3"&gt;&lt;?php echo $leadin ?&gt;&lt;/textarea&gt;&lt;/p&gt;

&lt;h3&gt;File Upload:&lt;/h3&gt;
&lt;p&gt;&lt;input type="file" name="file" value="&lt;?php echo $file ?&gt;" /&gt;&lt;/p&gt;

&lt;p align="center"&gt;&lt;input name="action" type="hidden" value="addfilemanager" /&gt;
&lt;input name="Submit" type="submit" id="Submit" value="Add A File" /&gt;
&lt;input name="Reset" type="reset" id="Reset" value="Reset"&gt;&lt;/p&gt;
 
&lt;/form&gt;
&lt;/div&gt;
Again, any help will be GREATLY appreciated!

Thanks!
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

is it possible that maybe where my if statement is for the actual file upload is in the wrong place?
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

I'm a noob in this area too. I've been working on file upload scripts all weekend myself. I don't see anything wrong with your code. I think maybe there is a file size limitation. Are you trying to upload a file bigger than 2MB? The default limit on uploads is 2MB. Try inserting this switch and seeing what the results are... These are php constants that determine the message. Checking for $_FILES['files']['error'] should probably be added some where in your script.

Code: Select all

<?php
	switch ($_FILES['files']['error'])
			{
				case 1 :
				echo "File size exceeds php.ini limit " .ini_get("upload_max_filesize");	
				break; 
				case 2 : 
					echo  "File size exceeds limit set in hidden element named MAX_FILE SIZE";	
				break;
				case 3 :
			echo "File only partially uploaded";
				break;
				case 4:
				echo " File not uploaded";
				break; 
				
			} 
//if the case is 0 file upload was successfull.
?>
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

The file I attempted to upload only was about 10k, so I don't think that was it. It just seems that the actual upload script never initializes. It will most certainly take all of the info and insert it into the database, but it won't actually take the file and copy it to the remote server in the "files" directory. At once point I had this thing working, but since I didn't use CVS, I have no clue where it was in fact working which is why I wonder if I have some bad syntax.
npeelman
Forum Commoner
Posts: 32
Joined: Tue Jul 27, 2004 5:13 am
Location: Oviedo,FL.

Post by npeelman »

neophyte wrote:I'm a noob in this area too. I've been working on file upload scripts all weekend myself. I don't see anything wrong with your code. I think maybe there is a file size limitation. Are you trying to upload a file bigger than 2MB? The default limit on uploads is 2MB. Try inserting this switch and seeing what the results are... These are php constants that determine the message. Checking for $_FILES['files']['error'] should probably be added some where in your script.

Code: Select all

<?php
	switch ($_FILES['files']['error'])
			{
				case 1 :
				echo "File size exceeds php.ini limit " .ini_get("upload_max_filesize");	
				break; 
				case 2 : 
					echo  "File size exceeds limit set in hidden element named MAX_FILE SIZE";	
				break;
				case 3 :
			echo "File only partially uploaded";
				break;
				case 4:
				echo " File not uploaded";
				break; 
				
			} 
//if the case is 0 file upload was successfull.
?>
Do not rely on this code. While it works in theory, i've had it fail before.

Norm
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

so no ideas why it might be failing?
npeelman
Forum Commoner
Posts: 32
Joined: Tue Jul 27, 2004 5:13 am
Location: Oviedo,FL.

Re: Help with File Upload & MySQL

Post by npeelman »

tsm4781 wrote:I've written a little piece of code to upload a file to a folder on my remote server and write a title, desc, id, filename to my database. I'm running into an issue and I am wondering if you could help me.

All of the data is writing to the database just file, but the file never uploads. My directory is CHMOD 777, so I'm thinking my code must be busted in some area. If you could take a look and tell me what you think, I'd be appreciative.

Here is my control file.

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
  $table = "filemanager";
  $title = $_POST['title'];
  $leadin = $_POST['leadin'];
  $file = $_FILES['file']['name'];

if (($_FILES['file']['type'] == 'application/pdf') && ($_FILES['file']['size'] < 100000))
{
    echo '<strong>' . 'Uploading ' . $_FILES['file']['name'] . ' (' . $_FILES['file']['type'] . ', ' . ceil($_FILES['file']['size'] / 1024) . ' Kb)' . '</strong>' . '<br />';

    if (file_exists('/files/' . $_FILES['file']['name']))
    {
        echo "<p class="error">". $_FILES['file']['name']." already exists.<br />";
        echo "Please rename the file and try again.</p>";
    }
    else
    {
        move_uploaded_file($_FILES['file']['tmp_name'], '/files/' . $_FILES['file']['name']);
        echo "<p class="error">The file has been uploaded successfully</p>";
    }
} 
else
{
    echo "<p class="error">This site only accepts .pdf files only.</p>";
}

  $query = "INSERT into $table values (NULL,'$title','$leadin','$file')"; 
  $result = mysql_query($query);
  // $p is the result page
  $p = 9; //fileadd.inc.php
};

?>
Again, any help will be GREATLY appreciated!

Thanks!
Check new code (same as yours but easier to read:

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
   $table = "filemanager";
   $title = $_POST['title'];
   $leadin = $_POST['leadin'];
   $file = $_FILES['file']['name'];

   if (($_FILES['file']['type'] == 'application/pdf') && ($_FILES['file']['size'] < 100000))
   {
      echo "<strong>Uploading $_FILES[file][name] ($_FILES[file][type], ".ceil($_FILES['file']['size'] / 1024).'Kb)</strong><br />';

      if (file_exists('/files/'.$_FILES['file']['name']))
      {
         echo "<p class='error'> $_FILES[file][name] already exists.<br />";
         echo "Please rename the file and try again.</p>";
      }
      else
      {
         if(move_uploaded_file($_FILES['file']['tmp_name'], "//files//$_FILES[file][name]") == false)
         {
            echo "<p class='error'>The file has not been uploaded successfully. Please try again.</p>";
            //header('Location: http://your.domain.com/your/page.html');
         }
         else
         {
            echo "<p class='error'>The file has been uploaded successfully</p>";
            $query = "INSERT into $table values (NULL,'$title','$leadin','$file')"; 
            $result = mysql_query($query);
            // $p is the result page
            $p = 9; //fileadd.inc.php
         }
      }
   } 
   else
   {
      echo "<p class='error'>This site accepts .pdf files only.</p>";
   }
}
?>
Check your slashes in your move_uploaded_file line may need to double them up. And you perform your database INSERT whether the upload works or not.
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

npeelman wrote: Do not rely on this code. While it works in theory, i've had it fail before.

Norm
Really? Now I'm curious. What was the circumstance so I don't repeat it?
npeelman
Forum Commoner
Posts: 32
Joined: Tue Jul 27, 2004 5:13 am
Location: Oviedo,FL.

Post by npeelman »

neophyte wrote:
npeelman wrote: Do not rely on this code. While it works in theory, i've had it fail before.

Norm
Really? Now I'm curious. What was the circumstance so I don't repeat it?
Not sure of what caused/causes it but I set the FORM/php.ini/Apache Virtual Server variables and I have still had it pass a larger file than I want.

Norm
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

Ok so I tried the suggestion in code above, but all I get for a return is "This site accepts .pdf files only." when I click submit. It is also not doing an insert, but that is obvious since it isn't actually executing. Thoughts?
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

dont know if this is your problem, but its wrong

if (file_exists('/files/' . $_FILES['file']['name']))


your using a leading /
if your want to use a relative file path, thats definately not the way


currently, your looking here

C:\files\



most likely you want
C:\path\to\your\doc_root\files\

so get rid of that leading slash



and as for debugging scripts
first, always put this at the top of the script
error_reporting(E_ALL);
in fact, imo you should always have that when developing.
being able to see all errors is helpfull


second, place echo statements strategically in your script like so

Code: Select all

if ($foo == 'bar') {
    echo 'foo is equal to bar, so the script makes it at least this far.';
} else {
     echo 'hmm... foo didnt equal bar. this is the value:' . $bar;
}
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
   $table = "filemanager";
   $title = $_POST['title'];
   $leadin = $_POST['leadin'];
   $file = $_FILES['file']['name'];

   if (($_FILES['file']['type'] == 'application/pdf') && ($_FILES['file']['size'] < 100000))
   {
      if (file_exists('files/'.$_FILES['file']['name']))
      {
         echo "<h2>$_FILES[file][name] already exists.</h2>";
         echo "Please rename the file and try again.</p>";
      }
      else
      {
         if(move_uploaded_file($_FILES['file']['tmp_name'], "files/$_FILES[file][name]") == false)
         {
            echo "<h2>The file has not been uploaded successfully. Please try again.</h2>";
            //header('Location: http://your.domain.com/your/page.html');
         }
         else
         {
            echo "<h2>The file has been uploaded successfully</h2>";
            $query = "INSERT into $table values (NULL,'$title','$leadin','$file')"; 
            $result = mysql_query($query);
            // $p is the result page
            $p = 9; //fileadd.inc.php
         }
      }
   } 
   else
   {
      echo "<h2>File Did NOT Upload</h2>";
   }
};

?>
This is the latest code base that I have setup. It still is not working. I am on a linux machine not a windows machine, but I know that will make no different. It is not even attempting to upload a file at all, it is just executing the FILE DID NOT LOAD statement, even though I have a PDF that I am uploading to the server. So I am completely lost. What else should I be doing here?
tsm4781
Forum Commoner
Posts: 38
Joined: Wed Jul 09, 2003 7:17 pm

Post by tsm4781 »

ok so I finally have it all working, but I have one question....

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
  $table = "filemanager";
  $title = $_POST['title'];
  $leadin = $_POST['leadin'];
  $userfile = $_FILES['userfile']['name'];
  $uploaddir = 'files/';
  $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

   if (($_FILES['userfile']['type'] == "application/octet-stream") && ($_FILES['userfile']['size'] < 100000) || ($_FILES['userfile']['type'] == "application/pdf") && ($_FILES['userfile']['size'] < 100000))
   {
      if (file_exists($uploadfile))
      {
         echo "<h2>$_FILES[userfile][name] already exists.</h2>";
         echo "Please rename the file and try again.";
      }
      else
      {
         if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) == false)
         {
            echo "<h2>The file has not been uploaded successfully. Please try again.</h2>";
         }
         else
         {
        $file_type = $_FILES['userfile']['type'];
        print $file_type;
	$query = "INSERT into $table values (NULL,'$title','$leadin','$userfile')"; 
	$result = mysql_query($query);
        // $p is the result page
        $p = 7; //filelist.inc.php
         }
      }
   } 
   else
   {
      echo "<h2>File Did NOT Upload</h2>";
   }

?>
Why is it that when I upload a PDF, it comes up as "application/octet-stream" for the file type. Isn't that going to product a huge security hole?
npeelman
Forum Commoner
Posts: 32
Joined: Tue Jul 27, 2004 5:13 am
Location: Oviedo,FL.

Post by npeelman »

tsm4781 wrote:ok so I finally have it all working, but I have one question....

Code: Select all

<?php
if ($_POST['action'] == 'addfilemanager')
{
  $table = "filemanager";
  $title = $_POST['title'];
  $leadin = $_POST['leadin'];
  $userfile = $_FILES['userfile']['name'];
  $uploaddir = 'files/';
  $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

   if (($_FILES['userfile']['type'] == "application/octet-stream") && ($_FILES['userfile']['size'] < 100000) || ($_FILES['userfile']['type'] == "application/pdf") && ($_FILES['userfile']['size'] < 100000))
   {
      if (file_exists($uploadfile))
      {
         echo "<h2>$_FILES[userfile][name] already exists.</h2>";
         echo "Please rename the file and try again.";
      }
      else
      {
         if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) == false)
         {
            echo "<h2>The file has not been uploaded successfully. Please try again.</h2>";
         }
         else
         {
        $file_type = $_FILES['userfile']['type'];
        print $file_type;
	$query = "INSERT into $table values (NULL,'$title','$leadin','$userfile')"; 
	$result = mysql_query($query);
        // $p is the result page
        $p = 7; //filelist.inc.php
         }
      }
   } 
   else
   {
      echo "<h2>File Did NOT Upload</h2>";
   }

?>
Why is it that when I upload a PDF, it comes up as "application/octet-stream" for the file type. Isn't that going to product a huge security hole?
It means that you at least need to add another line to check your file type, something like:
...
if (($_FILES['userfile']['type'] == "application/octet-stream") || ($_FILES['userfile']['type'] == "application/pdf") || (eregi('/.pdf',$_FILES['userfile']['name'])) && ($_FILES['userfile']['size'] < 100000))
...
should work, check on the use of ereg/eregi on http://www.php.net. But it won't stop someone from changing the file type before uploading...

Norm
Post Reply