1

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

2 Answers 2

5
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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works perfect and I understand the way it's written - thanks a lot for the quick help !
I just saw you need to add something like $nr++ in the end as otherwise all files will get the same name.
3
$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;

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.