Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

PHP Upload: PHP on one drive, upload to another.

Posted on 2004-11-01
12
Medium Priority
?
570 Views
Last Modified: 2013-12-12
Is it possible to use PHP (installed on C:) to upload a file to a different drive on the same machine? (upload to E:)

For some reason, no matter where I define the path to store the image (even the temp image), I never see an image get stored there (temp image or moved image)
I've checked my php.ini and have everything set.
file_uploads = On
upload_tmp_dir = C:\blahblahblah
upload_max_filesize = 2M

I've tried all sorts of tests from simple to complex and I just can't seem to get this image to upload.
what's odd is I can tell it is generating a temporary name for the uploaded file because I store that in a database.
but as I said, I can see no temporary image in the temp folder nor a moved image in the uploads folder.

Any help would be appreciated.
0
Comment
Question by:ballbstr
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 9

Expert Comment

by:AlanJDM
ID: 12465669
To answer your question... Yes, you can save an uploaded file to a drive other than the drive that PHP resides on.

As for your problem, we won't be able to help you if you don't post your code. The problem could be any of a number of things and guessing at each without seeing the code would be a waste of everyones time. Please post you code so we may take a look and see whats going on in your script.

Alan
0
 
LVL 9

Expert Comment

by:stefanaichholzer
ID: 12466069
ballbstr,

I have to agree with Alan, post your code...

;)
0
 

Author Comment

by:ballbstr
ID: 12466730
yea I figured. I didn't post the code before because I wanted to make sure I could even switch drive letters.
thought so, but wasn't sure - thanks.

well, here it goes...
(I don't see anything on posting code so hopefully I'm not breaking a rule here. Sorry ahead of time for the length.)

///////////////////////////
// members_edit.php //
///////////////////////////
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>blah</title>
</head>

<body>
<?php
require("fileupload-class.php");

$path = "E:\\my_directory_path\\";

// The name of the file field in form.
$upload_file_name = "picture";

$acceptable_file_types = "image/gif|image/jpeg|image/pjpeg";
      
default_extension = "";

$mode = 2;
      
      
#--------------------------------#
# PHP
#--------------------------------#
if (isset($_REQUEST['submitted'])) {
                  
      // Create a new instance of the class
      $my_uploader = new uploader($_POST['language']);
      $my_uploader->max_filesize(204800); // 200 kb
      $my_uploader->max_image_size(800, 800); // max_image_size($width, $height)
            
      // UPLOAD the file
      if ($my_uploader->upload($upload_file_name, $acceptable_file_types, $default_extension)) {
            $my_uploader->save_file($path, $mode);
      }
            
      if ($my_uploader->error) {
            echo $my_uploader->error . "<br /><br />\n";
            
      } else {
            // Successful upload!
            print"<p class=\"text\">" .($my_uploader->file['name'] . " was successfully uploaded!</p>");
                  
            // Print all the array details...
            //print_r($my_uploader->file);
                  
            // ...or print the file
            if(stristr($my_uploader->file['type'], "image")) {
            echo "<img src=\"" . $path . $my_uploader->file['name'] . "\" border=\"0\" alt=\"\"><br /><br />";
            } else {
                  $fp = fopen($path . $my_uploader->file['name'], "r");
                  while(!feof($fp)) {
                        $line = fgets($fp, 255);
                        echo $line;
                  }
                  if ($fp) { fclose($fp); }
            }
       }
 }
#--------------------------------#
# HTML FORM
#--------------------------------#
?>

<form name="editMembers" enctype="multipart/form-data" method="POST" action="membersController.php">
<input type="hidden" name="id" value="<? echo $pr->getId() ?>">
<input type="hidden" name="submitted" value="true">
<input type="hidden" name="language" value="en" />

<font color="red"><? echo $msg ?></font>
<strong>Date Entered</strong>: <input type="hidden" name="dateEntered" value="<? echo $pr->getDateEntered() ?>"><? echo date("F d, Y", $pr->getDateEntered()) ?>

<strong>Full Name</strong>: <input type="text" name="fullName" value="<? echo $pr->getFullName() ?>" class="textfield">

<strong>Board</strong>: <input type="radio" name="board" value="Advisors" <? if ($pr->getBoard()=="Advisors"){?>checked<?}?>> Advisors<br>
      <input type="radio" name="board" value="Executive" <? if ($pr->getBoard()=="Executive"){?>checked<?}?>> Executive

<strong>Picture</strong>: <input type="file" name="<?= $upload_file_name; ?>" class="textfield">
<?if($pr->getPicture()!=""){?><br><img src="../images/board/<? echo $pr->getPicture() ?>" alt="<? echo $pr->getFullName() ?>" name="shim" width="75" height="100"><?}else{?><br><img src="../images/board/blank.gif" alt="<? echo $pr->getFullName() ?>" name="shim" width="75" height="100"><?}?>

<strong>Publish</strong>: <input type="checkbox" name="active" value="Yes" <? if($pr->getActive()=="Yes"){?>Checked<?}?>> (check to publish - leave blank to unpublish) </td>

<input type="submit" name="action" value="Update" class="button">&nbsp;&nbsp;
<input type="submit" name="action" value="Delete" class="button"></td>

</form>

</body>
</html>

////////////////////////////
// fileupload-class.php //
////////////////////////////
<?php
class uploader {

      var $file;
      var $language;
      var $acceptable_file_types;
      var $error;
      var $errors; // Depreciated (only for backward compatability)
      var $accepted;
      var $max_filesize;
      var $max_image_width;
      var $max_image_height;

      function uploader ( $language = 'en' ) {
            $this->language = strtolower($language);
            $this->error   = '';
      }
      
      
      function max_filesize($size){
            $this->max_filesize = (int) $size;
      }


      function max_image_size($width, $height){
            $this->max_image_width  = (int) $width;
            $this->max_image_height = (int) $height;
      }
      

      function upload($filename='', $accept_type='', $extention='') {
            
            $this->acceptable_file_types = trim($accept_type); // used by error messages
            
            if (!isset($_FILES) || !is_array($_FILES[$filename]) || !$_FILES[$filename]['name']) {
                  $this->error = $this->get_error(0);
                  $this->accepted  = FALSE;
                  return FALSE;
            }
                        
            // Copy PHP's global $_FILES array to a local array
            $this->file = $_FILES[$filename];
            $this->file['file'] = $filename;
            
            // Initialize empty array elements
            if (!isset($this->file['extention'])) $this->file['extention'] = "";
            if (!isset($this->file['type']))      $this->file['type']      = "";
            if (!isset($this->file['size']))      $this->file['size']      = "";
            if (!isset($this->file['width']))     $this->file['width']     = "";
            if (!isset($this->file['height']))    $this->file['height']    = "";
            if (!isset($this->file['tmp_name']))  $this->file['tmp_name']  = "";
            if (!isset($this->file['raw_name']))  $this->file['raw_name']  = "";
                        
            // test max size
            if($this->max_filesize && ($this->file["size"] > $this->max_filesize)) {
                  $this->error = $this->get_error(1);
                  $this->accepted  = FALSE;
                  return FALSE;
            }
            
            if(stristr($this->file["type"], "image")) {
                  
                  /* IMAGES */
                  $image = getimagesize($this->file["tmp_name"]);
                  $this->file["width"]  = $image[0];
                  $this->file["height"] = $image[1];
                  
                  // test max image size
                  if(($this->max_image_width || $this->max_image_height) && (($this->file["width"] > $this->max_image_width) || ($this->file["height"] > $this->max_image_height))) {
                        $this->error = $this->get_error(2);
                        $this->accepted  = FALSE;
                        return FALSE;
                  }
                  // Image Type is returned from getimagesize() function
                  switch($image[2]) {
                        case 1:
                              $this->file["extention"] = ".gif"; break;
                        case 2:
                              $this->file["extention"] = ".jpg"; break;
                        case 3:
                              $this->file["extention"] = ".png"; break;
                        case 4:
                              $this->file["extention"] = ".swf"; break;
                        case 5:
                              $this->file["extention"] = ".psd"; break;
                        case 6:
                              $this->file["extention"] = ".bmp"; break;
                        case 7:
                              $this->file["extention"] = ".tif"; break;
                        case 8:
                              $this->file["extention"] = ".tif"; break;
                        default:
                              $this->file["extention"] = $extention; break;
                  }
            } elseif(!ereg("(\.)([a-z0-9]{3,5})$", $this->file["name"]) && !$extention) {
                  // Try and autmatically figure out the file type
                  // For more on mime-types: http://httpd.apache.org/docs/mod/mod_mime_magic.html
                  switch($this->file["type"]) {
                        case "text/plain":
                              $this->file["extention"] = ".txt"; break;
                        case "text/richtext":
                              $this->file["extention"] = ".txt"; break;
                        default:
                              break;
                  }
            } else {
                  $this->file["extention"] = $extention;
            }
            
            // check to see if the file is of type specified
            if($this->acceptable_file_types) {
                  if(trim($this->file["type"]) && stristr($this->acceptable_file_types, $this->file["type"])) {
                        $this->accepted = TRUE;
                  } else {
                        $this->accepted = FALSE;
                        $this->error = $this->get_error(3);
                  }
            } else {
                  $this->accepted = TRUE;
            }
            
            return (bool) $this->accepted;
      }


      function save_file($path, $overwrite_mode="3"){
            if ($this->error) {
                  return false;
            }
            
            if ($path[strlen($path)-1] != "/") {
                  $path = $path . "/";
            }
            $this->path = $path;      
            $copy       = "";      
            $n          = 1;      
            $aok        = false;      
                        
            if($this->accepted) {
                  // Clean up file name (only lowercase letters, numbers and underscores)
                  $this->file["name"] = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($this->file["name"]))));
                  
                  // Clean up text file breaks
                  if(stristr($this->file["type"], "text")) {
                        $this->cleanup_text_file($this->file["tmp_name"]);
                  }
                  
                  // get the raw name of the file (without its extenstion)
                  if(ereg("(\.)([a-z0-9]{2,5})$", $this->file["name"])) {
                        $pos = strrpos($this->file["name"], ".");
                        if(!$this->file["extention"]) {
                              $this->file["extention"] = substr($this->file["name"], $pos, strlen($this->file["name"]));
                        }
                        $this->file['raw_name'] = substr($this->file["name"], 0, $pos);
                  } else {
                        $this->file['raw_name'] = $this->file["name"];
                        if ($this->file["extention"]) {
                              $this->file["name"] = $this->file["name"] . $this->file["extention"];
                        }
                  }
                  
                  switch((int) $overwrite_mode) {
                        case 1: // overwrite mode
                              $aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);
                              break;
                        case 2: // create new with incremental extention
                              while(file_exists($this->path . $this->file['raw_name'] . $copy . $this->file["extention"])) {
                                    $copy = "_copy" . $n;
                                    $n++;
                              }
                              $this->file["name"]  = $this->file['raw_name'] . $copy . $this->file["extention"];
                              $aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);
                              break;
                        default: // do nothing if exists, highest protection
                              if(file_exists($this->path . $this->file["name"])){
                                    $this->error = $this->get_error(4);
                                    $aok = null;
                              } else {
                                    $aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);
                              }
                              break;
                  }
                  
                  if(!$aok) { unset($this->file['tmp_name']); }
                  return (bool) $aok;
            } else {
                  $this->error = $this->get_error(3);
                  return FALSE;
            }
      }
      
      
      function get_error($error_code='') {
            $error_message = array();
            $error_code    = (int) $error_code;
            
            switch ( $this->language ) {
                  // French (fr)
                  case 'fr':
                        $error_message[0] = "<span style=\"color: #EF4427\"><strong>Aucun fichier n'a été envoyé</strong></span>";
                        $error_message[1] = "<span style=\"color: #EF4427\"><strong>Taille maximale autorisée dépassée. Le fichier ne doit pas être plus gros que " . $this->max_filesize/1000 . " Ko (" . $this->max_filesize . " octets).</strong></span>";
                        $error_message[2] = "<span style=\"color: #EF4427\"><strong>Taille de l'image incorrecte. L'image ne doit pas dépasser " . $this->max_image_width . " pixels de large sur " . $this->max_image_height . " de haut.</strong></span>";
                        $error_message[3] = "<span style=\"color: #EF4427\"><strong>Type de fichier incorrect. Seulement les fichiers de type " . str_replace("|", " or ", $this->acceptable_file_types) . " sont autorisés.</strong></span>";
                        $error_message[4] = "<span style=\"color: #EF4427\"><strong>Fichier '" . $this->path . $this->file["name"] . "' déjà existant, écrasement interdit.</strong></span>";
                  break;
                  
                  // German (de)
                  case 'de':
                        $error_message[0] = "<span style=\"color: #EF4427\"><strong>Es wurde keine Datei hochgeladen</strong></span>";
                        $error_message[1] = "<span style=\"color: #EF4427\"><strong>Maximale Dateigrösse überschritten. Datei darf nicht grösser als " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . " bytes) sein.</strong></span>";
                        $error_message[2] = "<span style=\"color: #EF4427\"><strong>Maximale Bildgrösse überschritten. Bild darf nicht grösser als " . $this->max_image_width . " x " . $this->max_image_height . " pixel sein.</strong></span>";
                        $error_message[3] = "<span style=\"color: #EF4427\"><strong>Nur " . str_replace("|", " oder ", $this->acceptable_file_types) . " Dateien dürfen hochgeladen werden.</strong></span>";
                        $error_message[4] = "<span style=\"color: #EF4427\"><strong>Datei '" . $this->path . $this->file["name"] . "' existiert bereits.</strong></span>";
                  break;

                  // English
                  default:
                        $error_message[0] = "<span style=\"color: #EF4427\"><strong>No file was uploaded</strong></span>";
                        $error_message[1] = "<span style=\"color: #EF4427\"><strong>Maximum file size exceeded. File may be no larger than " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . " bytes).</strong></span>";
                        $error_message[2] = "<span style=\"color: #EF4427\"><strong>Maximum image size exceeded. Image may be no more than " . $this->max_image_width . " x " . $this->max_image_height . " pixels.</strong></span>";
                        $error_message[3] = "<span style=\"color: #EF4427\"><strong>Only " . str_replace("|", " or ", $this->acceptable_file_types) . " files may be uploaded.</strong></span>";
                        $error_message[4] = "<span style=\"color: #EF4427\"><strong>File '" . $this->path . $this->file["name"] . "' already exists.</strong></span>";
                  break;
            }
            
            // for backward compatability:
            $this->errors[$error_code] = $error_message[$error_code];
            
            return $error_message[$error_code];
      }


      function cleanup_text_file($file){
            // chr(13)  = CR (carridge return) = Macintosh
            // chr(10)  = LF (line feed)       = Unix
            // Win line break = CRLF
            $new_file  = '';
            $old_file  = '';
            $fcontents = file($file);
            while (list ($line_num, $line) = each($fcontents)) {
                  $old_file .= $line;
                  $new_file .= str_replace(chr(13), chr(10), $line);
            }
            if ($old_file != $new_file) {
                  // Open the uploaded file, and re-write it with the new changes
                  $fp = fopen($file, "w");
                  fwrite($fp, $new_file);
                  fclose($fp);
            }
      }

}

?>


/////////////////////////////////
// membersController.php //
////////////////////////////////
<?php
include("../config/phpConfig.php");
include("../phpinclude/common_db.php");
include("../phpinclude/logonCheck.php");
include("../phpinclude/classes/Member.php");

      if($active=="")
      {
            $active="No";
      }
      // do the search...
      $dbConn = connectUfDb($odbcName, $dbUsername, $dbPassword);

      $pr = new Member($id, $fullName, $board, $body, $dateEntered, $active);

      if(isSet($id) && $id!="-1")
      {
            $pr = $pr->getMember($dbConn, $id);

            if($action=="Update")
            {
                  $pr->setBoard($board);
                  $pr->setFullName($fullName);
                  $pr->setPicture($picture);
                  $pr->setactive($active);
            }
      }

      if(isSet($board) && $board=="")
      {
            $msg = "Board is required";
            include("members_edit.php");
      }
      elseif(isSet($fullName) && $fullName=="")
      {
            $msg = "Full Name is required";
            include("members_edit.php");
      }
      else
      {
            if($action=="Update")
            {
                  $temppic = str_replace("'", "&#39;", $pr->getPicture());
                  $pr->setPicture($temppic);
                  $tempboard = str_replace("'", "&#39;", $pr->getboard());
                  $pr->setBoard($tempboard);
                  $tempname = str_replace("'", "&#39;", $pr->getFullName());
                  $pr->setFullName($tempname);
                  $pr->save($dbConn);
                  $done="true";
            }
            if($action=="Delete")
            {
                  $pr->deleteMember($dbConn, $id);
                  $done="true";
            }
            if($action=="")
            {
                  include("members_edit.php");
            }
      }

      odbc_close($dbConn);

      if($done=="true")
      {
            include("members.php");
      }
?>
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:ballbstr
ID: 12468223
I'm really starting to believe the issue isn't with the code as much as it is PHP.
I'm using version PHP 4.3.0.

I've tried doing less complex tests, just a simple file upload (no DB involved) and still no image shows up in my temp folder or live folder, but I am saving the temporary file name to the database (though by accident, I want to store the original file name, not the temp. I can fix that part).

as I mentioned in my first post, I believe my php.ini is set correctly. (see original post in this thread)
or is there something else that I might need to alter in my php.ini?
I thought I remembered reading something about "upload_max_filesize = 2M" needing a change because of the "M"?
does that sound familiar to anyone?

thanks again.
0
 
LVL 10

Expert Comment

by:frugle
ID: 12471007
Has the web_user got permission to write to the E: drive?

It could be as *simple* as incorrect NTFS security settings.

Mike
0
 

Author Comment

by:ballbstr
ID: 12473690
Yes, the web_user has permission to write to a folder found on the E: drive.

I would think that I even if the proper permissions weren't set, I'd still see the temporary file in PHP's temp directory - wouldn't I?
0
 
LVL 10

Expert Comment

by:frugle
ID: 12473815
I believe the file is deleted from /tmp after upload - if copy to final destination fails, the file is lost.

I can't see anything immediately wrong with the code

Mike
0
 
LVL 9

Expert Comment

by:AlanJDM
ID: 12473843
Something in the upluad function doesn't look quite right to me. I can't put my finger on it yet, but it seems to me the problem is in there somewhere. I am setting up a test using your class. I will let you know if I can find the problem.


Alan
0
 

Author Comment

by:ballbstr
ID: 12526746
This question can be closed.
No solution found as of yet.
I believe the version of PHP (4.0.4pl1 yikes!) I have to use has some bugs regarding file uploads.
0
 
LVL 10

Expert Comment

by:frugle
ID: 12534081
I would recommend PAQ/refund as the questioner has "solved" the problem themselves and given valuable advice about the suitability of PHP4.0.4pl1 and file uploads. It would be useful to keep this information on file.

Mike
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 12574229
Closed, 500 points refunded.

modulo
Community Support Moderator
Experts Exchange
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses

596 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question