重命名并上传文件

时间:2016-11-19 08:53:03

标签: php image

我正在使用此代码(来自w3schools),我想在上传前为每个图片名称添加随机数,如: <?php $randomnum = rand(470000,900000); ?> 我怎么能这样做?

if($_FILES["image"]){
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
$error =  "Sorry, file already exists. Rename the file and try again.";
$uploadOk = 0;
}
if ($_FILES["image"]["size"] > 500000) {
$error =  "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error =  "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
    $image = basename($_FILES["image"]["name"]);
} else {
    $error = "Sorry, there was an error uploading your file.";
}
}
}

1 个答案:

答案 0 :(得分:2)

我在我的项目中使用了这个。

$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
$newfilename = 'files/uploads/' . $name;
move_uploaded_file($_FILES["image"]["tmp_name"], $newfilename);