Current location: Hot Scripts Forums » Programming Languages » PHP » Need help with upload script


Need help with upload script

Reply
  #11 (permalink)  
Old 09-09-09, 05:23 AM
triplebig triplebig is offline
Newbie Coder
 
Join Date: Nov 2007
Posts: 83
Thanks: 6
Thanked 0 Times in 0 Posts
thanks job01017
Reply With Quote
  #12 (permalink)  
Old 09-09-09, 10:39 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
Your welcome.
__________________
Jerry Broughton
Reply With Quote
  #13 (permalink)  
Old 09-12-09, 10:10 AM
triplebig triplebig is offline
Newbie Coder
 
Join Date: Nov 2007
Posts: 83
Thanks: 6
Thanked 0 Times in 0 Posts
OK i made some modification to the script

file-update.php
PHP Code:



<?php

####################################################################
# http://www.zubrag.com/
####################################################################

####################################################################
#  SETTINGS START
####################################################################

// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','uploads/2008/');

// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE'0);

// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','update-success.php');

// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array('doc','docx');

// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE'false);

// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING''');

// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG'false);

// MySql data (in case you want to save uploads log)
define('DB_HOST','localhost'); // host, usually localhost
define('DB_DATABASE','test'); // database name
define('DB_USERNAME','root'); // username
define('DB_PASSWORD',''); // password

/* NOTE: when using log, you have to create mysql table first for this script.
Copy paste following into your mysql admin tool (like PhpMyAdmin) to create table
If you are on cPanel, then prefix _uploads_log on line 205 with your username, so it would be like myusername_uploads_log

CREATE TABLE _uploads_log (
  log_id int(11) unsigned NOT NULL auto_increment,
  log_filename varchar(128) default '',
  log_size int(10) default 0,
  log_ip varchar(24) default '',
  log_date timestamp,
  PRIMARY KEY  (log_id),
  KEY (log_filename)
);

*/

####################################################################
###  END OF SETTINGS.   DO NOT CHANGE BELOW
####################################################################

// Allow script to work long enough to upload big files (in seconds, 2 days by default)
@set_time_limit(172800);

// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");

function showUploadForm($message='') {
  
$max_file_size_tag '';
  if (
MAX_FILE_SIZE 0) {
    
// convert to bytes
    
$max_file_size_tag "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
  }

  
// Load form template
  
include ('file-update.html');
}

// errors list
$errors = array();

$message '';

// we should not exceed php.ini max file size
$ini_maxsize ini_get('upload_max_filesize');
if (!
is_numeric($ini_maxsize)) {
  if (
strpos($ini_maxsize'M') !== false)
    
$ini_maxsize intval($ini_maxsize)*1024*1024;
  elseif (
strpos($ini_maxsize'K') !== false)
    
$ini_maxsize intval($ini_maxsize)*1024;
  elseif (
strpos($ini_maxsize'G') !== false)
    
$ini_maxsize intval($ini_maxsize)*1024*1024*1024;
}
if (
$ini_maxsize MAX_FILE_SIZE*1024) {
  
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}

// show upload form
if (!isset($_POST['submit'])) {
  
showUploadForm(join('',$errors));
}

// process file upload
else {

  while(
true) {

    
// make sure destination folder exists
    
if (!@file_exists(DESTINATION_FOLDER)) {
      
$errors[] = "Destination folder does not exist or no permissions to see it.";
      break;
    }

    
// check for upload errors
    
$error_code $_FILES['filename']['error'];
    if (
$error_code != UPLOAD_ERR_OK) {
      switch(
$error_code) {
        case 
UPLOAD_ERR_INI_SIZE:
          
// uploaded file exceeds the upload_max_filesize directive in php.ini
          
$errors[] = "File is too big (1).";
          break;
        case 
UPLOAD_ERR_FORM_SIZE:
          
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
          
$errors[] = "File is too big (2).";
          break;
        case 
UPLOAD_ERR_PARTIAL:
          
// uploaded file was only partially uploaded.
          
$errors[] = "Could not upload file (1).";
          break;
        case 
UPLOAD_ERR_NO_FILE:
          
// No file was uploaded
          
$errors[] = "Could not upload file (2).";
          break;
        case 
UPLOAD_ERR_NO_TMP_DIR:
          
// Missing a temporary folder
          
$errors[] = "Could not upload file (3).";
          break;
        case 
UPLOAD_ERR_CANT_WRITE:
          
// Failed to write file to disk
          
$errors[] = "Could not upload file (4).";
          break;
        case 
8:
          
// File upload stopped by extension
          
$errors[] = "Could not upload file (5).";
          break;
      } 
// switch

      // leave the while loop
      
break;
    }

    
// get file name (not including path)
    
$filename = @basename($_FILES['filename']['name']);

    
// filename of temp uploaded file
    
$tmp_filename $_FILES['filename']['tmp_name'];

    
$file_ext = @strtolower(@strrchr($filename,"."));
    if (@
strpos($file_ext,'.') === false) { // no dot? strange
      
$errors[] = "Suspicious file name or could not determine file extension.";
      break;
    }
    
$file_ext = @substr($file_ext1); // remove dot

    // check file type if needed
    
if (count($exts)) {   /// some day maybe check also $_FILES['user_file']['type']
      
if (!@in_array($file_ext$exts)) {
        
$errors[] = "Files of this type are not allowed for upload.";
        break;
      }
    }

    
// destination filename, rename if set to
    
$dest_filename $filename;
    if (
RENAME_FILE) {
      
$dest_filename md5(uniqid(rand(), true)) . '.' $file_ext;
    }
    
// append predefined string for safety
    
$dest_filename $dest_filename APPEND_STRING;

    
// get size
    
$filesize intval($_FILES["filename"]["size"]); // filesize($tmp_filename);

    // make sure file size is ok
    
if (MAX_FILE_SIZE && MAX_FILE_SIZE*1024 $filesize) {
      
$errors[] = "File is too big (3).";
      break;
    }

    if (!@
move_uploaded_file($tmp_filename DESTINATION_FOLDER $dest_filename)) {
      
$errors[] = "Could not upload file (6).";
      break;
    }

    if (
DO_LOG) {
      
// Establish DB connection
      
$link = @mysql_connect(DB_HOSTDB_USERNAMEDB_PASSWORD);
      if (!
$link) {
        
$errors[] = "Could not connect to mysql.";
        break;
      }
      
$res = @mysql_select_db(DB_DATABASE$link);
      if (!
$res) {
        
$errors[] = "Could not select database.";
        break;
      }
      
$m_ip mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
      
$m_size $filesize;
      
$m_fname mysql_real_escape_string($dest_filename);
    
  
$log_id=$_POST[log_id];

 
$sql "UPDATE _uploads_log SET courseName='".$_POST[courseName]."',log_filename='$m_fname',log_size='$m_size',log_ip='$m_ip' WHERE log_id=$log_id"";
      
$res = @mysql_query($sql);
      if (!
$res) {
        
$errors[] = "Could not run query.";
        break;
      }
      @mysql_free_result(
$res);
      @mysql_close(
$link);
    } // if (DO_LOG)


    // redirect to upload success url
    header('Location: ' . SUCCESS_URL . "
?courseName=" . $_POST["courseName"]);
    die();

    break;

  } // while(true)

  // Errors. Show upload form.
  
$message = join('',$errors);
  showUploadForm(
$message);

}

?>
file-update.html
PHP Code:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Update</title>
</head>
<body>


 <?php
 
include "connect.php"

$log_id=$_POST[log_id];

$result mysql_query("SELECT * FROM report WHERE log_id=$log_id");
while(
$row mysql_fetch_array($result))
{
$log_id=$row['log_id'];
$courseName=$row['courseName'];
$log_filename=$row['log_filename'];
}
?>
<form method="post" enctype="multipart/form-data">

 <?php echo $max_file_size_tag?>
 <table border=1>
  <tr>
   <td colspan="2" align="center"><h3>Report</h3></td>
  </tr>
  <tr>
   <td colspan="2" align="center"><?php echo $message?></td>
  </tr>
  <tr>
   <td>Course Name: </td>
   <?php 
   
echo "<td><input type='text' size='50' name='courseName' value='$courseName'/></td> ";
   
   
?>

   <tr>
   <td>Report: </td>
  <td>
 <?php echo "Uploaded File: <img src='images/msword_icon.png' height='16' width='16' title='$log_filename'> 
<a href='uploads/2009/
$log_filename' target='_blank'>$log_filename</a>";?>
  <br />
  <small> In case you want update the above file click browse to select a new file</small
  
  <input type='file' size='40' name='filename'>
   <br />
<small>   ** Your file must be in Microsoft Word (*.doc /docx) format</small>
   
   </td>
  </tr>
  <tr>
   <td colspan="2" align="center"><br />
      <?php echo " <input type='hidden' name='log_id' value='$log_id'/>";?>
       
   <input type="submit" value="Update" name="submit">
  
  
   </td>
 </table>
</form>


</body>
</html>
my problem

if i just want to update the coursename and not update the uploaded file and click the update button i received error message 'could not upload file (2)' no file uploaded

i comment out this..same problem
PHP Code:

   case UPLOAD_ERR_NO_FILE:
          
// No file was uploaded
          
$errors[] = "Could not upload file (2).";
          break; 
a. update both the uploaded file (upload a new file) and course name - successs
b. - upload a new file only..click update button..success
c. update coursename only - click update button .....error



p/s:sorry for my english

Last edited by triplebig; 09-12-09 at 10:18 AM.
Reply With Quote
  #14 (permalink)  
Old 09-12-09, 12:35 PM
triplebig triplebig is offline
Newbie Coder
 
Join Date: Nov 2007
Posts: 83
Thanks: 6
Thanked 0 Times in 0 Posts
i kinda solved it

PHP Code:

 case UPLOAD_ERR_NO_FILE:
 
//No file was uploaded
 //$errors[] = "Could not upload file (2).";
$log_id=$_POST[log_id];
mysql_query("UPDATE _uploads_log SET courseName='".$_POST[courseName]."' WHERE log_id=$log_id");   
           
header('Location: ' SUCCESS_URL);

       break; 
php rocks !!
Reply With Quote
  #15 (permalink)  
Old 09-13-09, 01:52 AM
job0107's Avatar
job0107 job0107 is offline
Community Liaison
 
Join Date: Dec 2006
Location: Tacoma, Washington USA
Posts: 3,454
Thanks: 0
Thanked 140 Times in 137 Posts
In file_update.php you want to add a condition that looks at the file size.
It will equal 0 if no file is selected for upload.
And you want to put the file upload commands in side this condition.
Like this:
PHP Code:

while(true)
 {
  if(
$_FILES['filename']['size'] != 0)
  {
   
// make sure destination folder exists
   
if (!@file_exists(DESTINATION_FOLDER))
   {
    
$errors[] = "Destination folder does not exist or no permissions to see it.";
    break;
    }
   
// check for upload errors
   
$error_code $_FILES['filename']['error'];
   if (
$error_code != UPLOAD_ERR_OK)
   {
    switch(
$error_code)
    {
     case 
UPLOAD_ERR_INI_SIZE:
      
// uploaded file exceeds the upload_max_filesize directive in php.ini
      
$errors[] = "File is too big (1).";
      break;
     case 
UPLOAD_ERR_FORM_SIZE:
      
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
      
$errors[] = "File is too big (2).";
      break;
     case 
UPLOAD_ERR_PARTIAL:
      
// uploaded file was only partially uploaded.
      
$errors[] = "Could not upload file (1).";
      break;
     case 
UPLOAD_ERR_NO_FILE:
      
// No file was uploaded
      
$errors[] = "Could not upload file (2).";
      break;
     case 
UPLOAD_ERR_NO_TMP_DIR:
      
// Missing a temporary folder
      
$errors[] = "Could not upload file (3).";
      break;
     case 
UPLOAD_ERR_CANT_WRITE:
      
// Failed to write file to disk
      
$errors[] = "Could not upload file (4).";
      break;
     case 
8:
      
// File upload stopped by extension
      
$errors[] = "Could not upload file (5).";
      break;
     } 
// switch
    // leave the while loop
    
break;
    }
   
// get file name (not including path)
   
$filename = @basename($_FILES['filename']['name']);
   
// filename of temp uploaded file
   
$tmp_filename $_FILES['filename']['tmp_name'];
   
$file_ext = @strtolower(@strrchr($filename,"."));
   if (@
strpos($file_ext,'.') === false)
   { 
// no dot? strange
    
$errors[] = "Suspicious file name or could not determine file extension.";
    break;
    }
   
$file_ext = @substr($file_ext1); // remove dot
   // check file type if needed
   
if (count($exts))
   {   
/// some day maybe check also $_FILES['user_file']['type']
    
if (!@in_array($file_ext$exts))
    {
     
$errors[] = "Files of this type are not allowed for upload.";
     break;
     }
    }
   
// destination filename, rename if set to
   
$dest_filename $filename;
   if (
RENAME_FILE)
   {
    
$dest_filename md5(uniqid(rand(), true)) . '.' $file_ext;
    }
   
// append predefined string for safety
   
$dest_filename $dest_filename APPEND_STRING;
   
// get size
   
$filesize intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
   // make sure file size is ok
   
if (MAX_FILE_SIZE && MAX_FILE_SIZE*1024 $filesize)
   {
    
$errors[] = "File is too big (3).";
    break;
    }
   if (!@
move_uploaded_file($tmp_filename DESTINATION_FOLDER $dest_filename))
   {
    
$errors[] = "Could not upload file (6).";
    break;
    }
   } 
__________________
Jerry Broughton
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Raffle/Lottery Script (Very profitable!), Coded it myself. Voltaire General Advertisements 6 03-16-09 07:15 AM
Submit button....can it send info to my email w/out the use of php???? lisa33 HTML/XHTML/XML 7 10-17-06 11:46 AM
3 Column CSS Fluid Layout (IE 6 Problem) Heidenreich12 CSS 9 10-04-06 03:22 PM
use html to open application absvinyl HTML/XHTML/XML 5 09-18-06 02:04 PM
unknown problem with upload script rush989 PHP 3 08-31-04 01:56 AM


All times are GMT -5. The time now is 07:58 AM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.