我有两张表,一张用于用户,一张用于图片我想要实现的是,如果我登录,我可以为用户上传图片因为不允许用户上传图片我想上传图片他们和每个用户都将能够查看自己的图像。我有一个工作代码来上传多个图像,但现在如何将它们分配给特定用户。下面的代码只是上传多张图片。
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>
<?php
$username = (isset ($_POST['username']));
if(isset($_FILES['files'])){
$query = "INSERT into tish_images(`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`)
VALUES(:FILE_NAME,:FILE_SIZE,:FILE_TYPE)";
$stmt = $con->prepare($query);
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $error ){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['files']['name'][$key] . ' was not uploaded.';
continue;
}
$file_name = $key.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[] = 'File size must be less than 2 MB';
continue;
}
try{
$stmt->bindParam( ':FILE_NAME', $file_name , PDO::PARAM_STR );
$stmt->bindParam( ':FILE_SIZE', $file_size, PDO::PARAM_STR );
$stmt->bindParam( ':FILE_TYPE', $file_type, PDO::PARAM_STR );
$stmt->execute();
$desired_dir="image_uploads";
if(is_dir($desired_dir)==false){
mkdir($desired_dir, 0700);// Create directory if it does not exist
}
if(is_file($desired_dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$desired_dir.'/'.$file_name);
}else{ //rename the file if another one exist
$new_file=$desired_dir.'/'.$file_name.time();
move_uploaded_file($file_tmp,$new_file) ;
}
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
if(empty($error)){
echo "Success";
}
}
?>