Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am new to PHP and have created a little code for a file upload on a form.

The code works fine but I was wondering if I could achieve the same using a foreach loop so that it could also handle more files and I dont have to write a separate line for each of them.

Can someone here help me with this and tell me how to write it properly.

My Code (working):

session_start();

$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];

$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);

move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);

echo $varUID;

Thanks for any help with this, Tim

share|improve this question

2 Answers 2

up vote 5 down vote accepted
foreach ($_FILES as $key => $file) {
    $name = $file["name"];
    $ext = pathinfo($name, PATHINFO_EXTENSION);
    preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
    $nr = $match[1];
    move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
}
share|improve this answer
1  
Very elegant +1 –  Sal00m Oct 9 '13 at 11:30
    
This works perfect and I understand the way it's written - thanks a lot for the quick help ! –  user2571510 Oct 9 '13 at 11:41
    
I just saw you need to add something like $nr++ in the end as otherwise all files will get the same name. –  user2571510 Oct 9 '13 at 16:21
    
Oh, there was a mistake in the code, I corrected it –  schokocappucino Oct 10 '13 at 14:08
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];

$i = 1;

foreach ($_FILES as $key => $file) {
    $varFile = $file[$key]["name"];
    $varExt = pathinfo($varFile, PATHINFO_EXTENSION);
    move_uploaded_file($file[$key]["tmp_name"], "uploads/" . $varUID . "_" . $i . "." . $varExt);
    $i++;
}

echo $varUID;
share|improve this answer
    
Hi, thanks a lot for the quick response. I tried but this doesnt work. Do I need to change anything here ? My names and IDs of my input fields are file1, file2 and file3. –  user2571510 Oct 9 '13 at 11:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.