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

时间:2018-11-02 11:29:10

标签: php

我的目标是使用两个不同的<inputs/>在同一表单中上传两个文件类型不同的不同文件,然后将其放置在两个单独的目录中。

我目前在$_FILES["photo"]不在位的情况下运行$_FILES["profileLink"]

在为$_FILES["profileLink"]添加功能之后,该功能将停止工作,包括为数据库插入内容,但会报告已成功添加了详细信息。

我执行此操作的方式可能是错误的,并且比应有的方式更复杂,因此我愿意进行改进。

注释: * max_file_uploads设置为4 * upload_max_filesize设置为4G(甚至不超过该大小)。

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

下面是带有输入字段的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>';
?>

1 个答案:

答案 0 :(得分:1)

经过更多的思考和测试,我终于使脚本按要求工作了。

我在相关位置添加了评论,以帮助其他人了解正在发生的事情,因此他们希望可以以此为自己的工作做出贡献。

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