简体   繁体   中英

PHP Upload Two Different File Types Using One Form With Two Different Inputs Into Two Different Directories

My aim is to have two different files with different file types uploaded within the same form using two different <inputs/> , then placed into two seperate directories.

I currently have the $_FILES["photo"] working without the $_FILES["profileLink"] being in place.

After adding functionality for $_FILES["profileLink"] it stops working, including the insert for the database but reports back it has successfully added the details.

The way I might be doing this could be wrong and more complex than it should be so I am open to improvements.

Notes: * max_file_uploads is set to 4 * upload_max_filesize is set to 4G (Don't even go near that size).

Below is the PHP code but please note anything related to $_FILES["profileLink"] breaks this and I purposely did not check the file since I wanted to test if it would work.

<?php

if (isset($_POST['convoy_add']) && $_POST['convoy_add'] == "Add") {
    if ($ConvoyPerms['new-convoy'] == '1' || $staffPerms['dev'] == '1') {
        $cname = $_POST['cname'];
        $server = $_POST['server'];
        $startdate = $_POST['startdate'];
        $starttime = $_POST['starttime'];
        $stpoint = $_POST['startpoint'];
        $startcomp = $_POST['startcomp'];
        $endpoint = $_POST['endpoint'];
        $endcomp = $_POST['endcomp'];
        $profile = $_POST['profile'];

        #image handling
        // Check if file was uploaded without errors
        if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0 && isset($_FILES["profileFile"]) && $_FILES["profileFile"]["error"] == 0){

            //Image
            $imgAllowed = array("jpg" => "video/mp4", "image/jpg", "jpeg" => "image/jpeg", "png" => "image/png");
            $filename = $_FILES["photo"]["name"];
            $filename2 = $_FILES["profileFile"]["name"];
            $filetype = $_FILES["photo"]["type"];
            $filesize = $_FILES["photo"]["size"];

            // Verify file extension (Image)
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if(!array_key_exists($ext, $imgAllowed)) die("Error: Please select a valid file format.");

            // Verify file size - 2GB maximum
            $maxsize = 2000000 * 1024 * 1024;
            if($filesize > $maxsize) die("Error: File size is larger than the Allowed limit.");

            $files = array();

            // Verify MYME type of the file
                if (in_array($filetype, $imgAllowed)) {
                    // Check whether file exists before uploading it
                    if (file_exists("upload/" . $_FILES["photo"]["name"])) {
                        echo $_FILES["photo"]["name"] . " already exists.";
                    } else {
                        try {
                            $host = $_SERVER['HTTP_HOST'];

                            $id = uniqid();
                            $ext = pathinfo($filename, PATHINFO_EXTENSION);
                            $ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
                            move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $id . "." . $ext);
                            move_uploaded_file($_FILES["profileFile"]["tmp_name"], "upload/" . "test" . "." . $ext2);
                            $url = "https://" . $host . "/hub/convoycontrol/upload/$id.";

                            $query = $db->prepare("INSERT INTO convoys (eventname, server, startcity, startcompany, endcity, endcompany, startdate, starttime, image, profilelink) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                            $query->execute(array($cname, $server, $stpoint, $startcomp, $endpoint, $endcomp, $startdate, $starttime, $url . $ext, $profile));


                            echo '<div class="alert alert-success" role="alert"><a href="#" class="alert-link">Convoy details successfully added!</a></div>';
                        }
                        catch (PDOException $e)
                        {
                            echo '<div class="alert alert-danger" role="alert"><a href="#" class="alert-link">Convoy details failed to added!</a></div>';
                        }
                    }
                } else {
                    echo "Error: There was a problem uploading your file. Please try again.";
                }
        } else{
            echo "Image Error: " . $_FILES["photo"]["error"];
        }
    }
}
?>

Below is the HTML with the input fields.

<?php

$json = file_get_contents('https://api.truckersmp.com/v2/servers');
$data = json_decode($json);

echo '<form action=new_convoy method=post enctype=multipart/form-data>';
  echo '<tr>';
  echo '<td>'."<input class='form-control' type=text autocomplete='off' name=cname value=''</td>";
  echo '<td>'."<select name=server>";
  foreach($data->response as $name) {
        echo"<option value='$name->shortname'>$name->shortname</option>";
  }
  echo'</select>';
  echo '<td>'."<input class='inputdate' type=date autocomplete='off' name=startdate value=''</td>";
    echo '<td>'."<input class='inputtime' type=text autocomplete='off' id=time placeholder=Time name=starttime value=''</td>";
  echo '<td>'."<input class='form-control' type=text autocomplete='off' name=startpoint value=''</td>";
echo '<td>'."<input class='form-control' type=text autocomplete='off' name=startcomp value=''</td>";
  echo '<td>'."<input class='form-control' type=text autocomplete='off' name=endpoint value=''</td>";
echo '<td>'."<input class='form-control' type=text autocomplete='off' name=endcomp value=''</td>";
echo '<td>'."<input class='form-control' type='file' name='profileFile'</td>";
  echo '<td>'."<input class='form-control' type='file' name='photo'</td>";

  echo '<td>'."<input class='btn btn-primary btn-outline' type=submit name='convoy_add' value=Add".' </td>';

  echo '</tr>';
  echo '</form>';

echo '</table>
</div>';
?>

After more thinking and testing I am finally got the script working as required.

I have added comments in the relevant places to help other understand what is happening and so they can hopefully use this to contribute to their work.

<?php
if (isset($_POST['convoy_add']) && $_POST['convoy_add'] == "Add") {
    //Checks against the session `$_SESSION['con_perms'];` and `$_SESSION['perms'];` for the users permissions
    if ($ConvoyPerms['new-convoy'] == '1' || $staffPerms['dev'] == '1') {
        $cname = $_POST['cname'];
        $server = $_POST['server'];
        $startdate = $_POST['startdate'];
        $starttime = $_POST['starttime'];
        $stpoint = $_POST['startpoint'];
        $startcomp = $_POST['startcomp'];
        $endpoint = $_POST['endpoint'];
        $endcomp = $_POST['endcomp'];

        //Image and Rar file handling
        // Check if files was uploaded without errors
        if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0 && isset($_FILES["profileLink"]) && $_FILES["profileLink"]["error"] == 0){

            //Allowed file types
            $filesAllowed = array("jpg" => "video/mp4", "image/jpg", "jpeg" => "image/jpeg", "png" => "image/png", "rar" => "application/octet-stream");

            //Properties of the image file being uploaded
            $filename = $_FILES["photo"]["name"];
            $filetype = $_FILES["photo"]["type"];
            $filesize = $_FILES["photo"]["size"];

            //Properties of the Rar file being uploaded, ("rar" => "application/octet-stream")
            $filename2 = $_FILES["profileLink"]["name"];
            $filetype2 = $_FILES["profileLink"]["type"];
            $filesize2 = $_FILES["profileLink"]["size"];

            // Verify file extension (Image)
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            $ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
            if(!array_key_exists($ext, $filesAllowed)) die("Error: Please select a valid image format.");
            if(!array_key_exists($ext2, $filesAllowed)) die("Error: Please select a valid rar format.");

            // Verify file size - 2GB maximum
            $maxsize = 2000000 * 1024 * 1024;
            if($filesize > $maxsize) die("Error: Image size is larger than the Allowed limit.");
            if($filesize2 > $maxsize) die("Error: Rar size is larger than the Allowed limit.");

            // Verify MYME type of the files
            if (in_array($filetype, $filesAllowed) && in_array($filetype2, $filesAllowed)) {
                // Check whether file exists before uploading it
                if (file_exists("upload/" . $_FILES["photo"]["name"])) {
                    echo $_FILES["photo"]["name"] . " already exists.";
                } else {
                    try {
                        $host = $_SERVER['HTTP_HOST'];

                        //Used for unique ID of the image being stored and inserted into the database
                        $id = uniqid();

                        $ext = pathinfo($filename, PATHINFO_EXTENSION);
                        move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $id . "." . $ext);
                        $url = "https://" . $host . "/hub/convoycontrol/upload/$id.";

                        //Using to allow for unique timestamp of folder without duplicating IDs
                        $timezone = date("d-m-Y").date("h:i:s");

                        //Check if directory exists
                        if (!file_exists("upload/profiles/$timezone/")) {
                            mkdir("upload/profiles/$timezone/", 0777, true);
                        }

                        $ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
                        move_uploaded_file($_FILES["profileLink"]["tmp_name"], "upload/profiles/$timezone/$filename2.".$ext2);
                        $url2 = "https://" . $host . "/hub/convoycontrol/upload/profiles/$timezone/$filename2.";

                        $query = $db->prepare("INSERT INTO convoys (eventname, server, startcity, startcompany, endcity, endcompany, startdate, starttime, image, profilelink) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $query->execute(array($cname, $server, $stpoint, $startcomp, $endpoint, $endcomp, $startdate, $starttime, $url . $ext, $url2 . $ext2));


                        echo '<div class="alert alert-success" role="alert"><a href="#" class="alert-link">Convoy details successfully added!</a></div>';
                    }
                    catch (PDOException $e)
                    {
                        echo '<div class="alert alert-danger" role="alert"><a href="#" class="alert-link">Convoy details failed to added!</a></div>';
                    }
                }
            } else {
                echo "Error: There was a problem uploading your file. Please try again.";
            }
        } else{
            //Displays errors upon failure to upload
            echo "Image Error: " . $_FILES["photo"]["error"];
            echo "Image Error: " . $_FILES["profileLink"]["error"];
        }
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM