所以我有一个简单的图片上传网站,我正在为一个小项目创建。除了数据库中的文件路径列外,它的工作效果都很好。
出于某种原因,它有时会包含我告诉它的变量,有时也不包括。
$user = $_SESSION['user'];
//file properties
$fileName = $_FILES["uploadedImage"]["name"];
$fileType = $_FILES["uploadedImage"]["type"];
$fileSize = $_FILES["uploadedImage"]["size"];
$fileTempName = $_FILES["uploadedImage"]["tmp_name"];
$error = $_FILES["uploadedImage"]["error"];
$random = substr(md5(microtime()),rand(0,26),16); //create random characters to avoid name duplication.
$path = "uploads/" . $_SESSION['userName'] . $random . $fileName;
路径始终包含"上传/"但有时只包含会话用户名,随机,很少包含文件名,即使在相同的文件上也是如此。我在提交表单之前回应这些变量,在提交表单并上传到数据库之前它们都是正确的。提交表单时,所有其他列都已正确填写。
if ( isset( $_POST['formSubmit'] )) {
//prevent SQL injections and invalid inputs
$title = trim($_POST['title']);
$title = strip_tags($title);
$title = htmlspecialchars($title);
$title = mysqli_real_escape_string($db, $title);
$description = trim($_POST['description']);
$description = strip_tags($description);
$description = htmlspecialchars($description);
$description = mysqli_real_escape_string($db, $description);
if (empty($title) || strlen($title) < 1) {
$titleError = "Title required.";
$formError = true;
}
if ($formError) {
$errorMessage = "Please fill out the upload form properly.";
} else {
$query = mysqli_query($db, "INSERT INTO IMAGE(imageID,userID,title,description,path)
VALUES('','$user','$title','$description','$path')");
这是形式本身:
<form method="POST" action="<?php $_SERVER['PHP_SELF'] ?>">
<div class="row">
<div class="col-sm-12">
<span class="errorText"><?php echo $errorMessage; ?></span>
<br><br>
</div>
</div>
<div class="row">
<div class='col-sm-1'><!--spacer--></div>
<div class="col-sm-2">
<label for="title">Title:</label>
</div>
<div class="col-sm-6">
<input type="text" id="title" name="title" placeholder="Enter your image title here..." >
</div>
<div class="col-sm-2"><span class="errorText"><?php echo $titleError; ?></span></div>
<div class='col-sm-1'><!--spacer--></div>
</div>
<br>
<div class="row">
<div class='col-sm-1'><!--spacer--></div>
<div class="col-sm-2">
<label for="description">Description:</label>
</div>
<div class="col-sm-6">
<input type="text" id="description" name="description" placeholder="Describe your image here...">
</div>
<div class="col-sm-2"><span class="errorText"><?php echo $descriptionError; ?></span></div>
<div class='col-sm-1'><!--spacer--></div>
</div>
<br>
<br>
<input type="submit" value="Submit" name = "formSubmit" id="formSubmit" class="btn">
<br>
<br>
</form>
答案 0 :(得分:1)
表单缺少enctype =“multipart / form-data”属性。
<form method="POST" enctype="multipart/form-data">
此外,即使这与问题无关,我强烈建议您使用MySQLi prepared statement。它可以帮助您避免SQL injection,而无需手动转义参数。