【发布时间】:2019-02-09 12:43:04
【问题描述】:
我正在尝试创建一个表单,当用户选择一个文件时,选择的文件将通过转到表单中的操作自动上传到数据库。我使用了onchange 函数,它只是将我发送到我的 php 文件,其中该文件包含我的上传系统。我认为我的问题是关于我的$_POST['asdasd'],但我真的想不出任何其他解决方案。
这是我的表格:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
PHP 文件:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
【问题讨论】:
-
isset($_POST['submit'])- 您在前端点击了多少个名为submit的按钮以获取要提交的表单...? -
没什么,我改了,表格会自动发送到数据库,但我真的不知道我会放什么到
isset($_POST['submit']) -
$_POST['asdasd']在哪里我看不到? -
只是一个例子
-
这用于检查是否在 POST 参数中找到提交按钮的值 - 以确定表单是否实际提交,或者这是否只是第一个 GET request,在这种情况下只需要显示表单。现在您不再有提交按钮,因此您需要根据其他因素做出决定。要么检查另一个值(
file字段不会出现在 $_POST 中),要么只是通过 $_SERVER 数组检查请求方法。
标签: javascript php forms post upload