Page 1 of 1

copying files from an array using for loop.

Posted: Mon May 25, 2009 4:15 pm
by TheFineArtist
Hey guys im a beginning level php dev.
my task is very simple, I have 20 files being uploaded using a form. ( file1 - file20 )

I want to use a for loop to copy the posted files into my server dir.

Code: Select all

$file = array( "file1", "file2", "file3", "file4", "file5", "file6", "file7", "file8", "file9", "file10", "file11", "file12", "file13", "file14", "file15", "file16", "file17", "file18", "file18", "file19", "file20"); 
 
I would like to use this array ^
to capture my filenames.

but when I use the expression $file[ $i ] in my for loop. my script crashes. Im running php and apache off of my local machine. Ive tried setting it to another variable, and echoing it. but even when the name outputs correctly ( ie. file1 )
the script still crashes.

it works fine when I use file1, or file6, or whatever the respective file name.

Code: Select all

 
for ( $i = 1; $i < 20; $i++  )
{
 
$filename =  $file[ $i ]; 
 
if ( $_FILES[$filename]['name'] != "" )
{
copy ($_FILES[$filename]['tmp_name'],
"" . $_FILES[$filename]['name'] )
or die ( "Could not copy file" );
}
else{ die( "No file specified" ); }
 
}
this seems like a syntax problem, but any help would be appreciated. there must be a way to use foor loops with copy().

Re: copying files from an array using for loop.

Posted: Tue May 26, 2009 5:31 pm
by TheFineArtist
please? :(

I need for loops for both copy file and gd library's imagecopyresampled so I can make thumbnails.

I can use

Code: Select all

$_FILES['file1']['name']
often, but doing

Code: Select all

 
for ( $i = 1; $i < 20; $i++ )
{
copy ($_FILES["file" . $i]['tmp_name'],
"" . $_FILES["file" . $i]['name'] )
 
}
or

Code: Select all

 
 
 
 
for ( $i = 1; $i < 20; $i++ )
  
{
 
$var = "file" . $i; 
 
copy ($_FILES[$var]['tmp_name'],
"" . $_FILES[$var]['name'] )
 
}
wont work.

Re: copying files from an array using for loop.

Posted: Tue May 26, 2009 10:27 pm
by t2birkey
Use a foreach loop. http://php.net/foreach

Code: Select all

 
#the if/else statement is not needed but I added it because you had it in your testing code. The if statement will quit the script if the file array is empty.
if(empty($file)) #check if there are files
     die('No file specified'); #quit the script if there are no files
else
     foreach($file as $fileName){ #for each value in the array $file i want in a variable called $fileName
          copy($_FILES[$filename]['tmp_name'], '' . $_FILES[$filename]['name'] ) or die ('Could not copy file');