我正在尝试创建一个表单,当用户选择文件时,通过转到表单中的操作,所选文件将自动上传到数据库。我使用了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/>";
}
}
}
答案 0 :(得分:1)
它没有保存,因为在php文件中您有这行
if (isset($_POST['submit'])) {
以隐藏字段的形式添加
<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();">
<input type="hidden" name="submited" value="1" />
</form>
然后在php中更改行
if (isset($_POST['submit'])) {
到
if (isset($_POST['submited'])) {
应该这样做
答案 1 :(得分:0)
请尝试检查请求是否为$ _POST,而不是执行$ _POST ['submit']验证。
为此,您可以使用
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
或
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
我建议您使用第一个。