Link to home
Start Free TrialLog in
Avatar of galneweinhaw
galneweinhaw

asked on

Trying to upload files via a webpage

Using the code detailed here: http://de3.php.net/manual/en/features.file-upload.php


I am getting this error page when I try to upload a file:

******************
Warning:  move_uploaded_file(/var/www/uploads/lurchvsGE.log): failed to open stream: No such file or directory in /home/happyhik/public_html/OtherStuff/EternalLogFiles/successorfail.php on line 19

Warning:  move_uploaded_file(): Unable to move '/var/tmp/phpiSq0OM' to '/var/www/uploads/lurchvsGE.log' in /home/happyhik/public_html/OtherStuff/EternalLogFiles/successorfail.php on line 19
Possible file upload attack!
Here is some more debugging info:Array
(
    [userfile] => Array
        (
            [name] => lurchvsGE.log
            [type] => application/x-zip-compressed
            [tmp_name] => /var/tmp/phpiSq0OM
            [error] => 0
            [size] => 20368
        )

)
***********************

Here is my successorfail.php code:

<html>

<head>
<title>New Page 2</title>
</head>

<body>
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>
</body>

</html>

Avatar of ldbkutty
ldbkutty
Flag of India image

>> $uploaddir = '/var/www/uploads/';

Are you sure the "/var/www/uploads" directory exists ? Check it and make sure the directory is writable.
Avatar of AlanJDM
AlanJDM

From the manual page you quoted...

"Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini."

You have simply cut nad pasted the example from the manual. Chance are your tmp directory is something different than the one used in the example. Check the php.ini file and be sure you set  $uploaddir to be the same value as the upload_tmp_dir parameter in the php.ini file.


Alan
Avatar of galneweinhaw

ASKER

I can't find a php.ini file, nor can I find the  /var directory...


should /var be here? : mydomain.com/var

or mydomain.com/public_html/vat?  what's the diff?

either way, it's not in either
php.ini is going to be on the server end, don't worry about that for now.

'var/www/uploads/' is the path for wherever you want your uploads to go.

You can type in whatever path you want there. If you want to use this path, create a directory inside public_html called var, then create www inside of that, and then uploads in side of that.

Otherwise, just put the path of the directory which you want your uploads to go in place of 'var/www/uploads/'

And like ldbkutty said, make sure its writable.
i'm not sure if justinsane made this clear enough so i'll try to help.

/var means the directory is in the server root's var directory, not yours.

if you wanted a publically viewable var directory, create one in public_html and the new directory would be '/home/happyhik/public_html/var/'

also, as the other users stressed, insure that this directory is writable

i hope this helps

K guys, sorry but I'm confused.

I'm really in over my head here so if anyone can baby me through that would be appreciated.

1.  How do I make a directory writable... something to do with the 755?

2. Say I just want everything to go to and "uplaods" folder....  mydomain.com/uploads.  what code do I need to change?

thanks again guys and sorry for trouble =)
Unfortunately you are going to need to have some understanding of your server to be able to give us the information we need to help you.

You say you want your files to go to mydomain.com/uploads. First we need to know where on the server mydomain lives. So, do me a favor and run this script from mydomain.com...

<?php

system('pwd');

?>

This will give you the path we need to use.


Alan
This is what I get:

/home/happyhik/public_html
ASKER CERTIFIED SOLUTION
Avatar of AlanJDM
AlanJDM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm thinking you better find your php.ini file because there are several things in there you need to set or keep track of. One is the location of the temp directory that the file gets uploaded to first and the other is the max file size that you will put up with.

There is this temp directory that the file is saved in until your submit/upload process runs it's course. Here is where you validate the file to make sure it's not an exe or other malicious type/content. Once validated, you do the "Move" to get the file into a permanent location. If you don't do the move or the file doesn't validate, then the file gets deleted at the end of the submit/upload process.

I don't want to horn in on someone else's hard efforts but I do have the file upload and validate code working on a production website if you want it or pieces of it.

John
John,

If you can help, please do. Don't worry about "horning in", we are all here to help. I can't speak for the others, but I certainly have no problem with you jumping in. I for one would like to see what you have, I will probably learn a thing or two myself. I always like seeing how others do things.


Alan
Ok, here goes:
Here is everything but the connection stuff:
<?
/*we must re-register the session variables on every
page that will use them*/
session_register("loggedon");
session_register("labid");
session_register("labname");

/*if the user cannot be validated (does not have open session)
redirect them to the login page*/
if ($loggedon!="true")
{
//this needs to be at the top before anything is written to the page
header("Location: lablogin.php3");

}

?>
<HTML><HEAD><TITLE>ASCII FILE UPLOAD</TITLE>
<script language="JavaScript">
  <!--
  //when Submit button clicked, check to make sure that
  //file has been chosen and if yes, that it has a .txt extension
     function checkForm(thisform,thisalert){
        if(thisform.userfile.value == "" || thisform.userfile.value == null) {
                  if (thisalert==1)
                  {
           alert("Please select a file to upload");
               }
               else
               {
           alert("Please select a file to view");              
               }
           thisform.userfile.focus();
           thisform.userfile.select();
           return false;
       } else {
           validformFile = /(.txt|.TXT)$/;
   
           if(!validformFile.test(thisform.userfile.value)){
               alert("Only text files are supported. Please select a different file.");
                 thisform.userfile.focus();
               thisform.userfile.select();
               return false;
           }
       }
        
      return true;
     }

// Thank you Larry McClurg for the cross-browser fix
function whatFile() {
//if (checkForm(document.newform,2))
//{
//look at the file in client text application--doesn't work for some--needs fixing
window.open('file:///' + document.newform.userfile.value,'popWin','resizable=yes,scrollbars=yes')
//window.location= 'file:///' + document.newform.userfile.value;
//}
}
  //-->
</script>
<LINK REL=STYLESHEET HREF='labstyles.css' TYPE='text/css' >

</HEAD>
<BODY class="fileupload">
<BR><BR>
<Div align ="center">

<?
function display_upload_inputs() {
//session variable to keep track of Lab's Orelap number
global $labid;
global $labname;
//for the file upload history table/display
include "yourconnectionstuff here.php3";
print "<div align=center>";
print 'Welcome<BR>'.$labid;
print '<BR>'.$labname;
?>
<form name="newform" enctype="multipart/form-data" action="file_upload.php3" method="POST" onSubmit="return checkForm(this,1)" >
<input type="hidden" name="action" value="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">

<STRONG> Oregon Department of Human Services </STRONG>
<BR>
<IMG alt="Drinking Water Data Access" border=0 height=45 src="dwphead.jpg" width=324>
<br>
<STRONG>ASCII File Upload Page</STRONG>
<br>
<br>

<!--todo: make sure to run the final string to display rows thru HTMLSpecialChars($string)-->
      <table>
            <tr>
                  <td class="fileupload" colspan= 2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Send this file
                  </td>
            </tr>
            <tr>
                  <td colspan= 2><input name="userfile" type="file" >
                  </td>
            </tr>
      
            <tr>
                  <td align=right><br>(be patient, click submit only once)<input type="submit" name="submit" value="submit">
                  &nbsp;&nbsp;&nbsp;</td>

            </tr>
            <!-- value of checkbox only shows if checked -->
      <!-- <tr><td><label>File has Free Chlorine</label><input type="checkbox" name="freechlorine"></td></tr> -->            

      </table>

</form>


<?
//upload history display

$data = odbc_do($connectionSDWIS, "SELECT ID, LabOrelap, FileName, BatchID, NumAccepted AS Accepted, NumRejects AS Rejects, Convert(varchar(12),DateRecv,107) AS DateReceived, Convert(varchar(12),LowestDate, 101) AS LowestDate, Convert(varchar(12),HighestDate, 101) AS HighestDate FROM jdavis.ASCIIHistory WHERE LabOrelap='$labid' ORDER BY DateRecv DESC");

echo "<br><br><br>";

//============================================
/*display queries fields for column headers*/
// then display data in columns
//============================================
echo "<table width=80%>";
echo "<th align=center colspan=9>ASCII File Process History For $labname</th>";
echo "<tr>";
$fields=odbc_num_fields($data);
{
  for($i=1 ; $i<=$fields ; $i++)
  echo "<td align=center><b>".odbc_field_name($data,$i)."</b></td>";
  echo "</tr>\n";
  }

do
  {
  echo "<tr>";
  $fields=odbc_num_fields($data);
  for($i=1 ; $i<=$fields ; $i++)
  echo "<td align=center>".odbc_result($data,$i)."</td>";
  echo "</tr>\n";
  } while(odbc_fetch_row($data));
 
echo "</table>";
echo "<br><br><br>If you've just uploaded an ASCII file you will not see it here. Only files that have become live data are visible. <br>";
echo "There will be a lag time where the ASCII Custodian sees the uploaded file and processes it, printing<br> out Alerts and Proofsheets for filing. An email denoting accepted or rejected rows gets sent at the same time<br> a processed file is added to this table.";

echo "<table><tr><td>";
echo "<br><br>1. The lab uploads their ASCII file here.";
echo "<br>2. The ASCII Custodian sees the file and processes it, completing the validation.";
echo "<br>3. The lab receives an email notification and the file info is added above.";
echo "<br>3. The rows in the file are now live data in the DWP database, available online.";
echo "</td></tr></table>";

} //end of function "display_upload_inputs"

?>
</Div>
</BODY>

</HTML>
<?

// In PHP earlier then 4.1.0, $HTTP_POST_FILES should be used instead of
// $_FILES.  In PHP earlier then 4.0.3, use copy() and is_uploaded_file()
// instead of move_uploaded_file

////////////////////////////////////////////////////////////////////////
//build locations where uploaded files will be held and processed
/////////////////////////////////////////////////////////////////////////

$uploaddir = 'C:/Program Files/Apache13 14/Apache/htdocs/AsciiCheck/';
$uploadfileandpath = $uploaddir. $HTTP_POST_FILES['userfile']['name'];
$AcceptedFolder= 'C:/Program Files/Apache13 14/Apache/htdocs/AsciiUploads/';
$RejectedFolder = 'C:/Program Files/Apache13 14/Apache/htdocs/AsciiRejected/';
$AcceptedFileAndPath=$AcceptedFolder.$HTTP_POST_FILES['userfile']['name'];
$RejectedFileAndPath=$RejectedFolder.$HTTP_POST_FILES['userfile']['name'];



if ($HTTP_POST_VARS['submit'])
{
            print "<div align=left><pre>";
            
            //for troubleshooting, unrem
/*             print "<br>labs orelap: ".$labid."<br>";
            print "<br>labs name: ".$labname."<br>"; */
            
            
            //////////////////////////////////////////////////////////////////////////////
            //this include file validates that the file name is comprised
            //of the loggod  on lab's orelap and TODAY'S date formatted
            //with 4 digit year. Example: "yourOrelapNumber-mmddyyyy.txt"
            //file_name_validate.php3 returns "GOOD" or "BAD"            
            ///////////////////////////////////////////////////////////////////////////////////
            include "file_name_validate.php3";
            
            //echo "<br>goodbad AFTER file_name_validate: ".$goodbad."<br>";
            
            If($goodbad=="BAD")
            {
                  echo "<div align=center>";
                  echo "<H5 class=badname>Incorrect file name:</H5>".$userfile_name."<br>";

                  echo "<H5 class=badname>File must be named:</H5>\"yourOrelapNumber-mmddyyyy.txt\" using today's date";
                  echo "<H5 class=badname>In your case, today's file must be named:</H5>".$labid."-".date("mdY").".txt";
                   echo "</div>";            
                  echo "</pre></div>";
                  display_upload_inputs();
                  die;  //go no further      
            }
            
                  if($userfile_type!="text/plain")
                        {
                        print "File was not uploaded<br>";
                        print "File type can only be text";
                        echo "<br><br>".$userfile_name."<br><br>";            
                        echo "<br><br>".$userfile_type."<br><br>";
                        
                        }
                  elseif (move_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'], $uploadfileandpath))
                        {
                        //build characteristics into a string to use after file is validated or not
                        $filename=$userfile_name;
                        $filesize=$userfile_size;
                        $filetype=$userfile_type;
                              
                        //////////////////////////////////////
                        //this include validates and prints
                        //the file to the browser including
                        //any bad data notes that might have
                        //occurred.
                        //It also returns an "A" or
                        //"R" to determine display verbage
                        /////////////////////////////////////
                        include "file_validator.php3";
                                    
                                     ////////////////////////////////////////////////
                                     //copy the files to the correct final folders///
                                     ////////////////////////////////////////////////
                                    if ($acceptOrReject=="A")
                                          {
                                          copy($uploadfileandpath,$AcceptedFileAndPath);
                                          }
                                    else
                                      {
                                      //////////////////////////////////////////////////////////////
                                      //let's add a timestamp to the rejected file
                                      //put ".txt" extension on it so we can double click and view easier
                                      ////////////////////////////////////////////////////////////////////
                                      $FinalRejectedFileAndPath= $RejectedFileAndPath."--".date("H-i-sa").".txt";
                                      copy($uploadfileandpath,$FinalRejectedFileAndPath);      
                                      }      
                        
                              /////////////////////////////////////////////////
                              //Delete the file from AsciiCheck folder once
                              //it is accepted or rejected
                              /////////////////////////////////////////////////
                              unlink($uploadfileandpath);
            
                        } //closing bracket of if move successful
                  else  //if move function not succesful
                        {
                        echo "<br>File was not uploaded<<br>";
                        }

      print "</pre></div>";
      
}  //closing bracket of if submit button pushed
else
{
//back to beginning if submit not clicked

display_upload_inputs();
}


?>
One other thing. We chose to keep the uploaded files on the webserver and then go "pull" them across the network when we wanted them. This was for security reasons. You might be having trouble "pushing" your file to a different server or network location using a mapped drive.