Question

very simple file upload script for multiple files

Asked by: livegirllove

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>

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-09-17 at 21:55:57ID21135885
Tags

upload

,

php

,

multiple

,

script

,

file

Topic

PHP Scripting Language

Participating Experts
4
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. dont know PHP uploading script
    Hi, Because i dont know php i got a uploading script from hotscripts.com but now i dont know where to put my server path. well, i am hosting my site through a free hosting service provider and my server path is "/users/coolfreepage.com/skserver" thats what the serv...
  2. Is there a way to redirect on "die"?
    Currently, I have a page set up for a "die" : $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploadingo./ doesn't have the correct extension."); } etc. Instead of die ...
  3. PHP UPLOAD SCRIPT
    I NEED A SIMPLE PHP SCRIPT TO UPLOAD ANY FILES TO MY SERVER MAIN DIRECTORY
  4. Uploading Slide Show to Web Site
    I am using dreamweaver to build a web site. I want to use Flash Player to create and insert a slide show. When I insert the slide show using Dreamweaver and then hit F12 to view the web page all works well but when I upload it to my web site the slide show does not appear. He...
  5. Why is PHP die() command killing my CSS layout.
    Hello, I'm building a PHP contact form for my site. I'm able to pass info from an HTML form to a php page that then mails me the user's contact info. But my problem is coming in trying to validate some of the fields using PHP if() and die() statements. All the validation is ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: hernst42Posted on 2004-09-17 at 23:19:56ID: 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.

 

by: peyoxPosted on 2004-09-17 at 23:46:46ID: 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);
      }    
?>

 

by: hernst42Posted on 2004-09-18 at 01:08:38ID: 12090851

Can you just explain why the other solution fits better for you than mine?

 

by: livegirllovePosted on 2004-09-18 at 01:16:36ID: 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.

 

by: SabreCEOPosted on 2005-02-11 at 22:11:14ID: 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];

 

by: livegirllovePosted on 2005-02-11 at 22:17:02ID: 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....

 

by: mbigradPosted on 2005-02-20 at 22:33:24ID: 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

 

by: livegirllovePosted on 2005-02-20 at 23:36:04ID: 13360711

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...