-1

I have a form with 2 inputs with the same name attribute:

<form enctype="multipart/form-data" method="POST">
    <input type="file" name="file_upload" required="required" aria-required="true">
    <input type="file" name="file_upload" required="required" aria-required="true">
</form>

Before I had only one upload file input, with PHP I upload that file to temp folder and attach it to an email using phpMailer:

if (array_key_exists('file_upload', $_FILES)) {
    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['file_upload']['name']));
    if (move_uploaded_file($_FILES['file_upload']['tmp_name'], $uploadfile)) {
        $mail->addAttachment($uploadfile, $_FILES['file_upload']['name']);
    } else{
        echo 'Failed!';
        exit;
    }
}

How to do the same for 2 file inputs?

Both files are required.

Would it be better to use different name for one of them and repeat the same PHP code?

User_125
  • 41
  • 4
  • Possible duplicate: https://stackoverflow.com/questions/9291061/upload-two-files-using-php –  Oct 06 '19 at 15:18
  • Possible duplicate of [Upload two files using PHP](https://stackoverflow.com/questions/9291061/upload-two-files-using-php) – Tom Rudge Oct 06 '19 at 16:00

1 Answers1

1

In your HTML rename them like img1 and img2 (or u can change this code) .

$uploadStatus = 1;
$uploadedFile = '';
if (!empty($_FILES["img1"]["name"]))
{
    $fileName = basename($_FILES["img1"]["name"]);
    $filenamewithoutextension = strtolower(pathinfo($fileName, PATHINFO_FILENAME));
    $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    $filename_to_store = $filenamewithoutextension. '_' .uniqid(). '.' .$fileType;

    $allowTypes = array(
        'jpg',
        'png',
        'jpeg'
    );
    if (in_array($fileType, $allowTypes))
    {
        if (move_uploaded_file($_FILES["img1"]["tmp_name"], $uploadDir.$filename_to_store))
        {
            $uploadedFile = $filename_to_store;
        }
        else
        {
            $uploadStatus = 0;
        }
    }
    else
    {
        $uploadStatus = 0;
    }
}

$uploadStatus1 = 1;
$uploadedFile1 = '';
if (!empty($_FILES["img2"]["name"]))
{
    $fileName = basename($_FILES["img2"]["name"]);
    $filenamewithoutextension = strtolower(pathinfo($fileName, PATHINFO_FILENAME));
    $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    $filename_to_store = $filenamewithoutextension. '_' .uniqid(). '.' .$fileType;

    $allowTypes = array(
        'jpg',
        'png',
        'jpeg'
    );
    if (in_array($fileType, $allowTypes))
    {
        if (move_uploaded_file($_FILES["img2"]["tmp_name"], $uploadDir.$filename_to_store))
        {
            $uploadedFile1 = $filename_to_store;
        }
        else
        {
            $uploadStatus1 = 0;
        }
    }
    else
    {
        $uploadStatus1 = 0;
    }
}

if($uploadStatus==1 && $uploadStatus1==1)
{
    //send mail
}
Popescu Ion
  • 142
  • 10