Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

very simple file upload script for multiple files

Posted on 2004-09-17
9
Medium Priority
?
86,436 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
[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
9 Comments
 
LVL 48

Assisted Solution

by:hernst42
hernst42 earned 700 total points
ID: 12090629
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 1300 total points
ID: 12090672
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
ID: 12090851
Can you just explain why the other solution fits better for you than mine?
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.

 
LVL 1

Author Comment

by:livegirllove
ID: 12090869
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
 
LVL 2

Expert Comment

by:SabreCEO
ID: 13292606
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
ID: 13292619
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
ID: 13360520
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
ID: 13360711
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

730 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