简体   繁体   English

PHP 使用一种形式将两种不同的文件类型与两种不同的输入上传到两个不同的目录中

[英]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.我的目标是使用两个不同的<inputs/>在同一表单中上传具有不同文件类型的两个不同文件,然后放入两个单独的目录中。

I currently have the $_FILES["photo"] working without the $_FILES["profileLink"] being in place.我目前有$_FILES["photo"]在没有$_FILES["profileLink"]到位的情况下工作。

After adding functionality for $_FILES["profileLink"] it stops working, including the insert for the database but reports back it has successfully added the details.在为$_FILES["profileLink"]添加功能后,它停止工作,包括数据库的插入,但报告它已成功添加详细信息。

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).注意: * max_file_uploads 设置为 4 * upload_max_filesize 设置为 4G(甚至不要接近那个大小)。

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 代码,但请注意与$_FILES["profileLink"]相关的任何内容都破坏了这一点,我故意没有检查该文件,因为我想测试它是否可以工作。

<?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.下面是带有输入字段的 HTML。

<?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"];
        }
    }
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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