Upload problem - beginner

Addos

Verified User
Joined
Jun 15, 2005
Messages
7
Hi,
I'm really stuck with a problem and I've been at this for days trying to get
this sorted but I just have to call for help.
Basically I have a form where I can upload .doc's only to the server. I have a good few conditional statements on the page
and they all work fine when checking for any incorrect uploads such as
images or anything that is not a .doc. The problem arises when in fact the
correct file passes all the validation and goes on to upload and here is
here I get the following errors.

Warning: fopen(log.txt): failed to open stream: Permission denied in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 93
Warning: fwrite(): supplied argument is not a valid stream resource in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 96
Warning: fclose(): supplied argument is not a valid stream resource in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 97
Warning: in_array(): Wrong datatype for second argument in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 107
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link
resource in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 168
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource
in
/home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
on line 169

If I remove the validation including the insert function from this:

if (isset($_POST['wordDetails']) && !empty($_POST['wordDetails'])) {
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_name = str_replace("\\","",$file_name);
$file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;
//$wordDetails here added by Brian

//proceed with insert into db once all tests are passed.
$insertSQL = sprintf("INSERT INTO word (wordName, wordDetails) VALUES
(%s, %s)",
GetSQLValueString($_FILES['userfile']['name'],
"text"),
GetSQLValueString($_POST['wordDetails'], "text"));

mysql_select_db($database_johnston, $johnston);
$Result1 = mysql_query($insertSQL, $johnston) or die(mysql_error());
}
To this:
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_name = str_replace("\\","",$file_name);
$file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;
It will upload ok but obviously the validation has gone out the window!

Now what's really frustrating me to death is that if I test this locally on my PC and
that's including all the validation it works perfectly with no errors at all
but it's only when I upload this to the server it throws a wobbly.

I have tried moving this particular conditional statement and tried re
scripting the validation to other places and I'll refrain from posting any
more code at this time to show my many attempts but if anybody can tell me
why the errors are happening on the live server and not locally I'd be most
thankful.
I have the entire code of the page here with the relevant section
highlighted (scroll down) in the hope that this issue can be fixed.
I appreciate that there is lots of code but I feel that it's best to show it
all rather than too many snippets.
Thanks
Brian
www.ahamay.com/validation.php
 
I don't mean to be rude, but why not pay attention to the error messages and warnings??

First problem (which causes 2 further warnings) is the log.txt. It seems the file has unsuitable write permissions.

Second problem appears to be that $FILE_MIMES has been commented out causing the array problem.

Third problem is your MySQL link. Doesn't appear to be correct.
Something in Connections/me.php??

As a general debugging aid, put lots of comments in to test values throughout (eg print "<!-- filename after validity step 1 = $filename -->";

Hope this helps!
 
Hi Mike,
Just as a follow up to this I'm happy to report that I have managed to
overcome this problem. Basically I added this to my conditional statement
to:

PHP:
if ($_FILES['userfile']['type'] == 'application/msword')

and placed it in a different part of the page and this stopped any further
upload errors.

I notice that in IE that the following error pops up extremely briefly (I
had to hit print screen really fast to capture the details!)

> Warning: fopen(log.txt): failed to open stream: Permission denied in
> /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
> on line 93
> Warning: fwrite(): supplied argument is not a valid stream resource in
> /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
> on line 96
> Warning: fclose(): supplied argument is not a valid stream resource in
> /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php
> on line 97

But as I say it does go on to upload successfully. In FF there is no such
problem is just uploads without any flashing errors so I wonder if this is
something to ignore or is there an underling issue.

Thanks
Brian
 
I bet the upload is not being logged in the log file (log.txt). Fix permissions on that and those three errors will disappear.

The reason the errors only flash up briefly is that your code redirects the page after a successful upload. Comment out the page redirection (or disable javascript) so that you can see the error messages.

Since the error messages are generated Server-side this is not a FF vs IE issue. Perhaps in Firefox the redirection occurs before the page gets written, hence no flash of error messages.
 
And....

I guess you've taken out the line

PHP:
if (!in_array($file_type, $FILE_MIMES)

because that was causing your failure. as a result of the commented out $FILE_MIMES array at the top of the unit.

Pay attention to the error messages! All the information you needed to fix the problem was in the messages:
PHP:
Warning: in_array(): Wrong datatype for second argument in ...
I looked at the line,saw the second argument was $FILE_MIMES.
I checked for $FILE_MIMES in the rest of the page and saw that it was commented out. So the file type check was always going to fail.
 
Hi Mike,
Thanks for your quick reply it is most appreciated. I’m so new to all of this and I’m struggling to keep up with this complicated script so I really don’t know how to fix the log.txt permissions that you suggest. I did also realise (thanks to your help) that I had commented out the FILE_MIMES which also gave me the idea to use this as a validation rather than using ‘Type’ . Also am not sure how or why there is a need for the upload to be logged or maybe this is something to do with the temp folder that’s used. What also confuses me is why there are two (!chmod($file_path,0777)) in my script (see below) and along with this I have also set permissions on folder on server to 777 too.
This page by the way has a secure log in so I understand giving this kind of permission is not recommended.
Anyway if you have the time to give ms a few pointers as to what all this means I’d be very grateful. I have studied this script and am using it as a kind of project and I want to understand fully what’s going on as I’m very eager to learn PHP as much as I can.
I think I did point out before that this script is something that I implemented from another source as I simply don’t have the know how to do it by myself.
Thanks again for all your great advice.
Brian
;)
Full code that works [better!] at the moment
PHP:
//Maximum file size. You may increase or decrease. 
$MAX_SIZE = 10000000; 
                            
//Allowable file Mime Types. Add more mime types if you want 
$FILE_MIMES = array('application/msword',); 
// 'image/jpeg','image/jpg','image/gif','image/png','application/zip','application/sit','application/rar','application/txt','application/rtf',
//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.doc'); 
//,'.txt','.zip','.sit','.jpg','.jpeg','.png','.gif','.rtf','.rar' 
  
//Allow file delete? no, if only allow upload only 
$DELETABLE  = true;                                

/************************************************************ 
 *     Setup variables 
 ************************************************************/ 
$site_name = $_SERVER['HTTP_HOST']; 
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); 
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; 
  
$upload_dir = "files/"; 
$upload_url = $url_dir."/files/"; 
$message =""; 
  $name = "";
/************************************************************ 
 *     Create Upload Directory 
 ************************************************************/ 
if (!is_dir("files")) { 
  if (!mkdir($upload_dir)) 
      die ("upload_files directory doesn't exist and creation failed"); 
  if (!chmod($upload_dir,0777)) 
      die ("change permission to 755 failed."); 
}   
/************************************************************ 
 *     Process User's Request 
 ************************************************************/ 
if ($_REQUEST[del] && $DELETABLE)  { 
  $resource = fopen("log.txt","a"); 
  fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n"); 
  fclose($resource); 
    
  
  if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking 
  else if (strpos($_REQUEST[del],"files/") === false); //possible hacking 
  else if (substr($_REQUEST[del],0,6)=="files/") { 
    unlink($_REQUEST[del]); 
    print "<script>window.location.href='$url_this?message=File deletion successful.'</script>"; 
  } 
} 
  
else if ($_FILES['userfile']) { 
  $resource = fopen("log.txt","a"); 
  fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]" 
            .$_FILES['userfile']['name']." " 
            .$_FILES['userfile']['type']."\n"); 
  fclose($resource); 
  
  $file_type = $_FILES['userfile']['type']; 
  $file_name = $_FILES['userfile']['name']; 
  $file_ext = strtolower(substr($file_name,strrpos($file_name,"."))); 
  
//File Size Check 
  	if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
     $message = "The file size is over 2MB."; 
//File Type/Extension Check 
	else if (!in_array($file_type, $FILE_MIMES) && !in_array($file_ext, $FILE_EXTS) )  {
    $message = "Sorry, \"".$file_name."(".$file_type.")\" is not allowed to be uploaded.";
}	  
  	else 
     $message = do_upload($upload_dir, $upload_url); 
      
    print "<script>window.location.href='$url_this?message=$message'</script>"; 
} 
	else if (!$_FILES['userfile']); 
	else 
    $message = "Invalid File Specified."; 
  
/************************************************************ 
 *     List Files 
************************************************************/ 
	 $handle=opendir($upload_dir); 
	 $filelist = ""; 
	 while ($file = readdir($handle)) { 
	 if(!is_dir($file) && !is_link($file)) { 
     $filelist .= "<a href='$upload_dir$file'>".$file."</a>"; 
     if ($DELETABLE) 
     $filelist .= " - <a href='?del=$upload_dir$file' title='delete'> Delete this file?</a>"; 
     $filelist .= "<sub><small><small><font color=black>  ".date("d-m H:i", filemtime($upload_dir.$file)) 
                   ."</font></small></small></sub>"; 
     $filelist .="<br>"; 
} } 
/********************************************************************************************
Delete on this page returns a url parm of files/signal.doc for example 
substr() will extract from the position (counting from 0) and strip files from files/signal.doc 
WHERE wordName= %s is replaced with $filename after it has been striped of files/ 
****************************************************************************/
	$relURL = $_GET['del']; 
	$filename = substr($relURL, 6); 
    if ((isset($_GET['del'])) && ($_GET['del'] != "")) { 
    $deleteSQL = sprintf("DELETE FROM word WHERE wordName='$filename'", 
                       GetSQLValueString($_GET['del'], "text")); 
  
   mysql_select_db($database_johnston, $johnston); 
   $Result1 = mysql_query($deleteSQL, $johnston) or die(mysql_error()); 
  } 
    function do_upload($upload_dir, $upload_url) { 
    $temp_name = $_FILES['userfile']['tmp_name']; 
    $file_name = $_FILES['userfile']['name']; 
    $file_name = str_replace("\\","",$file_name); 
    $file_name = str_replace("'","",$file_name); 
    $file_path = $upload_dir.$file_name; 
    
    $wordDetails= $_POST['wordDetails']; 
//If wordDetails empty check 
    if ( $wordDetails =="") { 
    $message = "Programme Note title missing"; 
    return $message; 
     } 
//File Name Check 
    if ( $file_name =="") { 
    $message = "Invalid File Name Specified"; 
    return $message; 
     } 
    $result  =  move_uploaded_file($temp_name, $file_path); 
  	if (!chmod($file_path,0777)) 
    $message = "change permission to 755 failed."; 
  	else 
  	$message = ($result)?"$file_name uploaded successfully." : "Something is wrong with uploading a file."; 
  	return $message; }
/*****************************************************************
Proceed with insert into db once all tests are passed.
This final test makes sure that if an attempt to upload an image and text is
placed in the second form field ' wordDetails' this text will not be entered into the db.
************************************************************************/
       if (isset($_POST['wordDetails']) && !empty($_POST['wordDetails'])) { 
// test for $FILE_MIMES type. Tried testing for ext .doc for ages but this didn't work.
	   if ($_FILES['userfile']['type'] == 'application/msword') {
       $insertSQL = sprintf("INSERT INTO word (wordName, wordDetails) VALUES (%s, %s)", 
                       GetSQLValueString($_FILES['userfile']['name'], "text"), 
                       GetSQLValueString($_POST['wordDetails'], "text")); 
  
   mysql_select_db($database_johnston, $johnston); 
   $Result1 = mysql_query($insertSQL, $johnston) or die(mysql_error()); 
} }
?>
 
1/ Take out the trailing commas in the $FILE_MIMES declaration.

2/ Change the file permissions in the script form 0777 to 0755.
Safer and should work. Do you understand what the numbers mean?

3/
why there are two (!chmod($file_path,0777))
There aren't! There is a chmod($file_path,0777) and there is a chmod($upload_dir,0777).
One of them changes permissions for the upload directory, the other changes permissions for the file.

4/ The upload log is there to provide you with useful information. If you don't care for that information you can comment out the code that handles the logging.

5/ I would also give a more definite location for the log file. Perhaps have it in the same directory as the uploaded files. Currently I think it is writing (or at least attempting to...) to the same directory as the script, but I haven't looked too closely.
 
Back
Top