Solved

very simple file upload script for multiple files

Posted on 2004-09-17
9
86,304 Views
Last Modified: 2011-08-18
I need an upload script that will upload multiple files at once.  I need to set the file names to be the same everytime.  So it renames the files after uploading.  I need to upload 5-10 files and have them automatically named 1.gif through 10.gif.   I have a couple of scripts that do this fine for one file at a time but I need to do multiple for a slide show.

Thanks-

Heres what I use now.  If I could some how use a meta refresh after submitting.  

Thanks-

<?php

$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 = "../images/";
$upload_url = "http://####";
$message ="";

//create upload_files directory if not exist
//If it does not work, create on your own and change permission.
if (!is_dir("images")) {
      die ("upload_files directory doesn't exist");
}

if ($_FILES['userfile']) {
      $message = do_upload($upload_dir, $upload_url);
}
else {
      $message = "Invalid File Specified. Ignore if you havent clicked upload yet";
}

print $message;

function do_upload($upload_dir, $upload_url) {

      $temp_name = $_FILES['userfile']['tmp_name'];
      $file_name = '1.gif';
      $file_type = $_FILES['userfile']['type'];
      $file_size = $_FILES['userfile']['size'];
      $result    = $_FILES['userfile']['error'];
      $file_url  = $upload_url.$file_name;
      $file_path = $upload_dir.$file_name;

      //File Name Check
    if ( $file_name =="") {
          $message = "Invalid File Name Specified";
          return $message;
    }
    //File Size Check
    else if ( $file_size > 500000) {
        $message = "The file size is over 500K.";
        return $message;
    }
    //File Type Check
    else if ( $file_type == "text/plain" ) {
        $message = "Sorry, You cannot upload any script file" ;
        return $message;
    }

    $result  =  move_uploaded_file($temp_name, $file_path);
    $message = ($result)?"File url <a href=$file_url>$file_url</a><br><img src=$file_url height=\"210\" width=\"210\">" :
                "Somthing is wrong with uploading a file.";

    return $message;
}
?>
<style type="text/css">
<!--
.style1 {
      font-family: Verdana, Arial, Helvetica, sans-serif;
      font-weight: bold;
}
.style2 {font-family: Verdana, Arial, Helvetica, sans-serif}
-->
</style>

<title>Slideshow Upload Page</title><form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
  <span class="style1">Upload Slideshow Image<br>
  </span>  
  <input type="file" id="userfile" name="userfile"><br>
  <input type="submit" name="upload" value="Upload">
</form>
<p class="style2">Click Browse to choose the slideshow file (1.gif) on your computer or office network.</p>
<p class="style2">Click Upload</p>
<p class="style2">The image displayed will be in the slideshow on the front page of lulushoponline </p>
<p class="style2"><a href="collage_upload.php">Change Collage Picture</a></p>
<p class="style2"><a href="slideshow_upload.php">Change Slideshow Image</a></p>
<p><span class="style2"><a href="featured_upload.php">Change Featured Items</a></span> </p>
0
Comment
Question by:livegirllove
9 Comments
 
LVL 48

Assisted Solution

by:hernst42
hernst42 earned 175 total points
Comment Utility
You can try this modified version of the script:

<?php
if ($_FILES['userfile']) {
    //to see the structure that generates PHP for uploaded files with an name ending with[] uncomment the following line:
    echo '<pre>'; var_dump($_FILES); echo '</pre>';
    $num = 0;
    foreach($_FILES['userfile']['size'] as $id => $size) {
        if ($size == 0) {
            //no or empty file, skip it
            continue;
        }
        $message .= do_upload($id, $upload_dir, $upload_url);
    }
    ++$num;
}

function do_upload($id, $upload_dir, $upload_url) {
    static $counter = 1;

    $temp_name = $_FILES['userfile'][$id]['tmp_name'];
    $file_type = $_FILES['userfile'][$id]['type'];
    $file_size = $_FILES['userfile'][$id]['size'];
    $result    = $_FILES['userfile'][$id]['error'];
    $file_name = $counter . '.gif';
    $file_url  = $upload_url.$file_name;
    $file_path = $upload_dir.$file_name;

    //File Name Check
    if ( $file_name =="") {
        $message = "Invalid File Name Specified for filei $id.";
        return $message;
    }
    //File Size Check
    else if ( $file_size > 500000) {
        $message = "The file size is over 500K for file $id.";
        return $message;
    }
    //File Type Check
    else if ( $file_type == "text/plain" ) {
        $message = "Sorry, You cannot upload any script file" ;
        return $message;
    }

    if (file_exists($file_path)) unlink($file_path);
    $result  =  move_uploaded_file($temp_name, $file_path);
    $message = ($result)?"File url <a href=$file_url>$file_url</a><br><img src=$file_url height=\"210\" widt
h=\"210\">" :
        "Somthing is wrong with uploading a file.";
    ++$counter;
    return $message;
}

?>
.....
<form name="uplVoad" id="upload" ENCTYPE="multipart/form-data" method="post">
<span class="style1">Upload Slideshow Image<br>
</span>
<?php for ($i = 0; $i< 10; ++$i) { ?>File <?=$i?>:
<input type="file" class="userfile" name="userfile[]"><br>
<?php } ?>
<input type="submit" name="upload" value="Upload">
</form>

So the mostimportant thing to know is how the structure of uploaded files will look like if in the form the name is eneded with []
The files will be name from 1 to 10. If a user skips one field for files inbetween the sequence will not ge broken. This is done by the static variable $counter in do_upload as do up_load is only. If one of those files have failed it will be overwritten by the next file.
0
 
LVL 6

Accepted Solution

by:
peyox earned 325 total points
Comment Utility
Below is a script with basic error handling:
- renames files: 1.gif ... n.gif   n - number of the last file
- checks if file exists
- checks mime format
- checks file size
- it handles up to 10 uploads
- displays upload summary (status of each upload + total number of uploaded files)

Enjoy :-)


<?
      // (C) 2004 Piotr Szwajkowski
      
      // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
      // of $_FILES.

   $form = TRUE;
      $upload_path = "c:\\apache\\htdocs\\test\\";

      $fname = 1;

      for ($i=0;$i<10;$i++)
      {
            list($problem, $error) = upload_file ($upload_path, $fname.".gif", $i);
            if (!$problem)
            {
                  $fname++;
            }
            else
                  echo $i.": ".$error."<br>";
      }
      
      echo "<br>";
      echo --$fname." file(s) uploaded";

      
         
      if ($form)
      {
      ?>
          <form enctype="multipart/form-data" action="<?php echo $SELF_PHP; ?>" method="POST">
          <input type="hidden" name="MAX_FILE_SIZE" value="300000">
          0: <input class="file" type="file" name="file[0]"><br>
          1: <input class="file" type="file" name="file[1]"><br>
          2: <input class="file" type="file" name="file[2]"><br>
          3: <input class="file" type="file" name="file[3]"><br>
          4: <input class="file" type="file" name="file[4]"><br>
          5: <input class="file" type="file" name="file[5]"><br>
          6: <input class="file" type="file" name="file[6]"><br>
          7: <input class="file" type="file" name="file[7]"><br>
          8: <input class="file" type="file" name="file[8]"><br>
          9: <input class="file" type="file" name="file[9]"><br>
          <input type="submit" value="Submit Images">
          </form>
      <?
      }
     
     
      function upload_file ($upload_path, $fname, $fileid)
      {    
            $problem = TRUE;
            
            switch ($_FILES['file']['error'][$fileid])
            {
                case UPLOAD_ERR_FORM_SIZE:
                     $error = "The uploaded file exceeds the 85kb";
                     break;
                case UPLOAD_ERR_NO_FILE:
                     $error = "No file was uploaded";
                     break;
                default:
                     $error = "";
            }
            
            
            //$fname = $_FILES['file']['name'][$fileid];
            $dest = $upload_path.$fname;
            $tmpfile = $_FILES['file']['tmp_name'][$fileid];
            
            if ($tmpfile)
            {
                $info = getimagesize($tmpfile);
              $ftype = $info['mime'];
            
                if ($ftype != "image/gif" && $ftype != "image/jpeg")
                {
                     $error = "File type not supported";
                     $problem = TRUE;
                }
                else
                {
                     if (file_exists($dest))
                     {
                          $error = "File already exists. (".$dest.")";
                          $problem = TRUE;
                     }                    
                     else
                     {
                          copy ($tmpfile,$dest);                    
                          $problem = FALSE;
                     }
                }
            }
      
            return array($problem, $error);
      }    
?>
0
 
LVL 48

Expert Comment

by:hernst42
Comment Utility
Can you just explain why the other solution fits better for you than mine?
0
 
LVL 1

Author Comment

by:livegirllove
Comment Utility
Cut and pasted and it worked.  Doesnt fit any better than that.

Although I thought I split the points 325/175 because your answer was informative and worked with the script I was already familiar with.  

Must be tired.  Ill post a comment in community to have it reopened.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Expert Comment

by:SabreCEO
Comment Utility
I saw this was one of the top 10 viewed answers, but it took me over an hour to figure somethin out here. So i know this is closed, but so no one else gets confused, The above was wrong:
 $_FILES['userfile'][$id]['type'];
$_FILES['userfile'][$id]['size'];
$_FILES['userfile'][$id]['error'];

is all wrong, so i am correcting it all of those and the others should be

$_FILES['userfile']['type'][$id];
$_FILES['userfile']['size'][$id];
$_FILES['userfile']['error'][$id];
0
 
LVL 1

Author Comment

by:livegirllove
Comment Utility
hnmm.
ok, i seem to remember it working, but ill have to check through my files.  I cant remember what I used this on....
0
 

Expert Comment

by:mbigrad
Comment Utility
Hello,

The below script has been causing me problems for quite some time. All it does is upload the filename in to the database. I need it to upload an image into the images directory on our website. Please help.

$sqlQuery = "SELECT * FROM motorcycles WHERE id = '$this->_id'";
$sqlServer->execQuery($sqlQuery);
$data = $sqlServer->getDataSetArray();

$this->_product_image_1 = $data["image_name_1"];
$this->_product_image_2 = $data["image_name_2"];
$this->_product_image_3 = $data["image_name_3"];
$this->_product_image_4 = $data["image_name_4"];
$this->_product_thumbnail = $data["thumbnail"];
             
             

$this->_product_image_dir = "http://www.ourwebsite.com/images" . "/";

$filedir = $GLOBALS["base_imagedir"];
$file_name = "thumb_" . $_FILES['new_thumb']['name'];
 if($_FILES['new_thumb']['name'] != '')
 {
     @unlink($filedir . $file_name);
     $copy = copy($_FILES['new_thumb']['tmp_name'],$filedir . $file_name);
     if($copy){
          echo "$file_name | uploaded successfuly!<br>";
          $real_path = realpath($uploads);
          echo $real_path;
              }else{
         echo "$file_name | could not be uploaded!<br>";
         }      
        $this->_product_thumbnail = $file_name;
 }
Thanks,
mbigrad
0
 
LVL 1

Author Comment

by:livegirllove
Comment Utility
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now