News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord

Main Menu

[solved] PHP Upload

Started by TXSherry, February 06, 2005, 08:01:55 PM

Previous topic - Next topic

TXSherry

Greetings,

I'm having trouble setting up a php upload page on my site.  Site's running "PHP Version 4.3.10", shared hosting.  I'm using methods I've used successfully on other hosts but it won't work here.    SMF on the same site has no problem with uploading.   I'm guessing it's a problem in moving the file from the tmp directory.  I'm guessing SMF uses a fully qualified directory to write to and doensn't use the hosts tmp directory.   Please note the "guessing"! 

I'm wanting to upload large files but this isn't the issue (yet) as I cannot even upload small ones.  [In anticipation though I've set up .htaccess to modify settings for php.ini on my own site.  The script wouldn't work prior to or after modification of ini_set though.  This is just an aside.]

Now I could, and will eventually, contact the host for resolving this, but I was hoping to work on it over the weekend. :) Thing is, SMF on the same site works!  and my upload script, which is not doing anything fancy, does not!

If anyone can help me out I'd be ever so grateful! 

Thanks, Sherry.

(PS.  We just upgraded from RC1 to 1.01 and it was a SNAP with no probs whatsoever!)

[Unknown]

Can you post the script, or a part of it?  Are you using $_FILES?

-[Unknown]

TXSherry

I'll give it a shot...   

upload.php

<?php

include('_gen.php');
$subdir='closet/';

if (isset(
$_REQUEST['btnlogon_x']))
{
   if (
$_REQUEST['txtpw']=='MYPASSWORD')
       
page_choosefile();
   else
       
page_login('Password incorrect.');
   }
else
{
   if (
$_REQUEST['btnupload_y'])
   {    
//  MODE OPTIONS (for destination file already exists):
         //   1 = overwrite mode  2 = create new with incremental extention  3 = do nothing if exists, highest protection
       
require("_classupload.php");
       
$mode = 1;
       
$my_uploader = new uploader('en');
       
$my_uploader->max_filesize(10000000);
       
$my_uploader->upload('userfile', '', '');
       
$my_uploader->save_file($subdir, $mode);   //$my_uploader->save_file('uploads/', 2);
       
if ($my_uploader->error)
         
$msg=$my_uploader->error . "<br><br>\n";
       else
           
$msg="Thanks for uploading " . $my_uploader->file['name'] . "<br><br>\n";
       
page_senddone($msg);
   }
   else
       
page_login('');
}

function
page_login($errmsg='')
{
echo <<<EOT
  <html><head><link REL="stylesheet" TYPE="text/css" href="pband.css">
  <title>First United Methodist Church of Pflugerville: Praise Band Uploads (Login)</title></head>
  <body>
  <a class=h href="../">Pflame Home</a> <a class=h href="index.php">Praise Band Home</a><p>
  <center>
  <table border=1 cellpadding=3 cellspacing=0 width="97%"><tr>
  <td valign=top bgcolor="#ffffff" align=center>
  <div class=title>Praise Band Uploads</div>
  <div style='margin-top: 70px;'></div>
  <form action="upload.php" method="post">
  <table border=3 cellspacing=1 cellpadding=17 width=300 ><tr><td align=center>
  Enter upload password<br>
  <input type="password" name="txtpw" size="24">
  <p><div class="err1">
$errmsg</div>
  <input type="image" name="btnlogon" src='img/continue1.jpg'
     onmouseover="this.src='img/continue.jpg'"  onmouseout ="this.src='img/continue1.jpg'">
  </td></tr></table>
  </form>
  <p style="margin-bottom:300px;">&nbsp;</p>
  </td></tr></table>
  </center>  </body></html>
EOT;
}
function
page_choosefile()
{
echo <<<EOT
  <html><head><link REL="stylesheet" TYPE="text/css" href="pband.css">
  <title>First United Methodist Church of Pflugerville: Praise Band Uploads (Choose File)</title></head>
  <body>
  <a class=h href="../">Pflame Home</a> <a class=h href="index.php">Praise Band Home</a><p>
  <center>
  <table border=1 cellpadding=3 cellspacing=0 width="97%"><tr>
  <td valign=top bgcolor="#ffffff" align=center>
  <div class=title>Praise Band Uploads</div>
  <div style='margin-top: 70px; margin-bottom:200px;'>

  <form enctype="multipart/form-data" action="upload.php" method="POST">
  Upload this file:<br>
  <input name="userfile" type="file">

  <br><br>
  <input type="image" name="btnupload" src='img/upload1.jpg'
      onmouseover="this.src='img/upload.jpg'" onmouseout="this.src='img/upload1.jpg'">
  </form>
   </div></td></tr></table></center></body></html>
EOT;
}
function
page_senddone($msg)
{
echo <<<EOT
  <html><head><link REL="stylesheet" TYPE="text/css" href="pband.css">
  <title>First United Methodist Church of Pflugerville: Praise Band Uploads (Choose File)</title></head>
  <body>
  <a class=h href="../">Pflame Home</a> <a class=h href="index.php">Praise Band Home</a><p>
  <center>
  <table border=1 cellpadding=3 cellspacing=0 width="97%"><tr>
  <td valign=top bgcolor="#ffffff" align=center>
  <div class=title>Praise Band Uploads</div>
  <div style='margin-top: 40px; margin-bottom:100px;'>
  Result of last upload: <p>
   
{$msg}<p><br>
  <form enctype="multipart/form-data" action="upload.php" method="POST">
  Upload this file:<br>
  <input name="userfile" type="file">

  <br><br>
  <input type="image" name="btnupload" src='img/upload1.jpg'
      onmouseover="this.src='img/upload.jpg'" onmouseout="this.src='img/upload1.jpg'">
  </form>
   </div></td></tr></table></center></body></html>
EOT;
}
?>



TXSherry

_classupload.php


<?php
/**
* Copyright 1999, 2002, 2003 David Fox, Dave Tufts
*  SNIP REST Copyright to fit in post --SHERRY
*/
class uploader {

var $file;
var $path;
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"]) || stristr($this->file["type"], $this->acceptable_file_types)) ) {
$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 (strlen($path)>0) {
if ($path[strlen($path)-1] != "/") {
$path = $path . "/";
}
}
$this->path = $path;
$copy       = "";
$n          = 1;
$success    = 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
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
$success = true;
} else {
$success     = false;
$this->error = $this->get_error(5);
}
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"];
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
$success = true;
} else {
$success     = false;
$this->error = $this->get_error(5);
}
break;
default: // do nothing if exists, highest protection
if(file_exists($this->path . $this->file["name"])){
$this->error = $this->get_error(4);
$success     = false;
} else {
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
$success = true;
} else {
$success     = false;
$this->error = $this->get_error(5);
}
}
break;
}

if(!$success) { unset($this->file['tmp_name']); }
return (bool) $success;
} 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 ) {
// English
default:
$error_message[0] = "No file was uploaded";
$error_message[1] = "Maximum file size exceeded. File may be no larger than " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . " bytes).";
$error_message[2] = "Maximum image size exceeded. Image may be no more than " . $this->max_image_width . " x " . $this->max_image_height . " pixels.";
$error_message[3] = "Only " . str_replace("|", " or ", $this->acceptable_file_types) . " files may be uploaded.";
$error_message[4] = "File '" . $this->path . $this->file["name"] . "' already exists.";
$error_message[5] = "Permission denied. Unable to copy file to '" . $this->path . "'";
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);
}
}

}


?>

TXSherry

Quote from: [Unknown] on February 06, 2005, 08:06:04 PM
Can you post the script, or a part of it?  Are you using $_FILES?

-[Unknown]

I posted the two files into two posts for space considerations.   Yes, it uses $_FILES.

also>>  pflame.org/info.php

Thanks!
Sherry

Saleh

I suggest using a full path instead of a relative one..
I see you are using $subdir='closet/'; which is a relative path of course..
I once tried relative path on my upload script on Windows and the files were saved in the parent directory instead and their names were  like: parentDirFilename.ext

also a security note, use move_uplaoded_file() instead of copy()

We don't need a reason to help people

TXSherry

Quote from: NeverMind on February 07, 2005, 06:17:17 AM
I suggest using a full path instead of a relative one..
I see you are using $subdir='closet/'; which is a relative path of course..
I once tried relative path on my upload script on Windows and the files were saved in the parent directory instead and their names were  like: parentDirFilename.ext

also a security note, use move_uplaoded_file() instead of copy()

Yes, exactly!  That's what I was asking, or guessing rather.   I too believe it's probably a path problem.   As far a smove_uploaded_file() vs copy()  the upload class is not mine.  However, several other scripts I tried -- which also failed-- used move_uploaded_file() and not copy, and they too did not work.

Any smf gurus out there willing to show me how smf does it?  I can wrap it up myself (security, SQLizing file details, etc) but cannot get the file uploading portion to work.  Frustrated is an understatement :)

I just spend all day in SQL server, oracle and ASP so it's hard to switch gears in the evening.   I'm off to put the kiddo to bed, and will check in later.  Did I happen to say "Please?"  :)    Please!!


TXSherry

Bueno okay ;/

Got it.  Found the equivalent to server.mappath, yay.   I was really hoping someone here might know how to find the absolute path in a shared environment using php!


'tis hokiedokie though.  Now to write all the user jigamaroll stuff. 

Have a good'un!

[Unknown]

Actually, the server's path varies depending on the webserver you're using.  I don't think DOCUMENT_ROOT, for example, works everywhere.  The best is, generally, dirname(__FILE__) - but that's hardly like ASP.NET's MapPath (which is only there because it's integrated so much into IIS.)

-[Unknown]

TXSherry

Good to know.  Document_root did work on my server, though that wasn't my issue. 


:-[  My ftp program said it was chgmod-ing but it wasn't; as soon as I pointed to SMF's attachment directory i was able to upload, hence determining my prob was permissions and not code, and so went to work tackling that.   Still and all, I did need to know how to arrive at abs. paths.   

Haven't done a lot of .net stuff ;)   I don't care for it, though my boss wants me to switch over. 

Thanks lots!

Sherry

Advertisement: