我正在保存新闻'我的文件系统中的图片,也保存在我的mysql数据库中的路径。但我想通过自行设置名称来保存文件,而不是上传者设置的文件名。我希望这可以防止在我的目录中可能重复文件名。我正考虑用它上面的唯一编号保存它们。
发送文件:
$target_dir_image = "../upload/image/";
$target_file1 = $target_dir_image. basename($_FILES["nimg"]["name"]);
$move_images1=move_uploaded_file($_FILES["nimg"]`["tmp_name"],$target_file1);
// after connect the db
$nimg2=$target_file1;
答案 0 :(得分:1)
只需替换basename()
变量中的$target_file1
,假设您已经有办法生成新文件名。
$newfilename = "YourNewGeneratedFilename.png";
$target_dir_image = "../upload/image/";
$target_file1 = $target_dir_image.$newfilename;
move_uploaded_file($_FILES["nimg"]["tmp_name"],$target_file1);
$nim2 = $target_file1;
然后在你的查询上
if($stmt = $con->prepare("INSERT INTO tablename (image,path) VALUES (?,?)")){
$stmt->bind_param("ss",$newfilename,$nim2);
...
但是如果你没有,你可以利用时间生成一个新的唯一文件名(增加不上传相同文件名的机会,但我仍然希望在最后添加一个唯一的id你的文件名。)。
生成新文件名及其上传时间:
$file = explode(".",$_FILES["nimg"]["name"]); /* STORE THE UPLOADED FILE NAME */
$extension = pathinfo(stripslashes($_FILES["nimg"]["name"]), PATHINFO_EXTENSION); /* STORE THE FILE EXTENSION */
$extension = strtolower($extension);
$timenow = date('his'); /* GET THE TIME NOW */
$count = count($file); /* COUNT HOW MANY STRINGS HAVE BEEN PRODUCED */
$count = $count - 1; /* TO REMOVE THE EXTENSION ON THE COUNT */
$newfilename = ""; /* ESTABLISH A CLEAN VARIABLE */
for($x = 0;$x<$count; $x++){
$newfilename .= $file[$x]; /* STORE THE EXPLODED STRING TO THE CLEAN VARIABLE */
} /* END OF FOR LOOP */
$newfilename = $newfilename."_".$timenow.".".$extension; /* PUT THE TIME AT THE END OF THE FILE NAME */
/* ...PUT HERE YOUR UPLOAD AND INSERT QUERY CODE... */