我正在做一个创建高考在线考试的项目。我正在寻找解决方案来上传图像和创建文件夹使用用户序列号,因为这是根据mysql数据库的主要增量idsave的文件夹内的图像。
这是我的解决方案,将图像上传到已创建的名为uploads的文件夹中。如何为我所需要的修改它。
<?php
session_start();
include('../connect.php');
$a = $_POST['name'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'your_site_name_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../uploads/'.$file_name_new;
/* check if the file uploaded successfully */
if(@move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
header("location: students.php");
}
?>
发布于 2019-02-02 13:39:01
第一:在没有正确检查文件类型的情况下要小心上传文件;
第二:正如Sean提到的,这种方法可能会失控。
--
下面的示例更改了您尝试的步骤。
首先插入用户以获取其ID,然后使用它在'../uploads‘下创建文件夹。
这样就不需要上传文件两次(将文件移动到../,插入用户,然后再次将文件移动到..//userID)
<?php
...
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
// Get user id
$studentId = $db->lastInsertId();
// Create path with new userId just inserted
$path = "../uploads/$studentId/";
if(!file_exists($path)) { // maybe "&& !is_dir($path)" ?
// IMPORTANT NOTE: the second argument is the permission of the folder. 0777 is the default and may cause security flaws
mkdir($path, 0777, true);
}
// Move the uploaded file to new path with the userId
@move_uploaded_file($_FILES['file']['tmp_name'], $path.$file_name_new);我认为你需要在插入之前检查用户是否已经存在(但我不知道你项目的细节)
https://stackoverflow.com/questions/54490020
复制相似问题