我正在尝试将图像文件上传到本地文件夹(本地托管)。我设法做到了。问题是,我看不到sql表中的图像路径,包括假定插入表中的其余数据。以前我可以,以前我搞砸了。我之前对upload.php做了一些小改动。尽管我设法将图像文件上传到本地文件夹(与我的页面相同的目录)。我从早上就试过了,现在已经半夜了。我还收到一个错误"未定义索引:image..line 106"-->
$image = $_POST['image'];
请帮助.tq
以下是upload.php。
<?php
//echo var_dump($_POST);
//echo var_dump($_FILES);
session_start();
require 'connect-test.php';
if(isset($_POST["submit"])) {
$id = $_POST['id'];
$name2 = $_POST['name2'];
$color2 = $_POST['color2'];
$hobby2 = $_POST['hobby2'];
$radiobtn = $_POST['radiobtn'];
$image = $_FILE['image'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image or not
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$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.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$stmt = $conn->prepare("INSERT INTO useradvert (id,name2,color2,hobby2,radiobtn,image) VALUES (?,?,?,?,?,?)");
$stmt->bind_param("isssss",$id,$name2,$color2,$hobby2,$radiobtn,$target_file);
$stmt->execute();
}
?>
您想插入图像的路径吗?此变量已返回图像的路径
$target_file = $target_dir . basename($_FILES["image"]["name"]);
然后更改此
$stmt->bind_param("isssss",$id,$name2,$color2,$hobby2,$radiobtn,$image);
到这个
$stmt->bind_param("isssss",$id,$name2,$color2,$hobby2,$radiobtn,$target_file);
根据您的原始帖子https://stackoverflow.com/revisions/34568743/1
我们在这里处理的是$_FILES
,而不是$_POST
。
因此,对于$image = $_POST['image'];
,您需要将$_POST
更改为$_FILES
参考:
- http://php.net/manual/en/features.file-upload.post-method.php
-
确保您在表单中具有enctype='multpart/form data'
-
插入数据库时,请确保插入文件路径,即"$target_dir/filetempname"
$imagepath=$target_dir/filetempname
-
只有在move_uplooaded成功的情况下,请插入数据库。否则,由于安全原因,东西将是空的。
if(move_uploaded_file成功){//要插入数据库的代码。}
-
我们使用$_FILES变量而不是$_POST获取文件数据,即使文件是使用POST方法发布的。