上传文件或图片进行重命名是我们在php上传中会碰到的一个问题了,在重命名无非就是对你上传的文件生成一个随机的字符串了,包括有Md5,随机,或按时间日期来重命名了,下面我来给大家介绍。
如我们在上传文件页面中如下操作:
$name=$_FILES['userfile']['name']; //将所上传的文件名称赋予name
然后我们要对它进行重命名,代码如下:
- //文件名的自动生成
- list($usec, $new_name) = explode(" ", microtime());
- if(@$extension_name){//限制文件类型为jpg、gif、png、bmp
- move_uploaded_file($tmp_name,$new_dir.'/'.$new_name.'.'.$extension_name);//移动到目标文件夹
- echo '上传成功';
这样我们就把文件名以时间日期生成了一个新的文件名了,代码如下:
- <form action="upload_file.php" method="post"
- enctype="multipart/form-data">
- <label for="file">Filename:</label>
- <input type="file" name="file" id="file" />
- <br />
- <input type="submit" name="submit" value="Submit" />
- </form>
以下是我添加的将文件名重命名为系统时间的代码:
- <?php
- $date = date(ymdhis);
- //echo($date);
- if ((($_FILES["uppic"]["type"] == "image/gif")
- || ($_FILES["uppic"]["type"] == "image/jpeg")
- || ($_FILES["uppic"]["type"] == "image/pjpeg"))
- && ($_FILES["uppic"]["size"] < 2000000))
- {
- if ($_FILES["uppic"]["error"] > 0)
- {
- echo "Return Code: " . $_FILES["uppic"]["error"] . "<br />";
- }
- else
- {
- //echo "Upload: " . $_FILES["uppic"]["name"] . "<br />";
- //echo "Type: " . $_FILES["uppic"]["type"] . "<br />";
- //echo "Size: " . ($_FILES["uppic"]["size"] / 1024) . " Kb<br />";
- //echo "Temp file: " . $_FILES["uppic"]["tmp_name"] . "<br />";
- $uptype = explode(".", $_FILES["uppic"]["name"]);
- $newname = $date.".".$uptype[1];
- //echo($newname);
- $_FILES["uppic"]["name"] = $newname;
- if (file_exists("pics/" . $_FILES["uppic"]["name"]))
- {
- echo $_FILES["uppic"]["name"] . " already exists. ";
- }
- else
- {
- $_FILES["uppic"]["name"] =
- move_uploaded_file($_FILES["uppic"]["tmp_name"],
- "pics/" . $_FILES["uppic"]["name"]);
- echo "<script>alert('上传成功!')</script>";
- echo "<script>window.location.href='http://www.111cn.net';</script>";
- }
- }
- }
- else
- {
- echo "Invalid file";
- }
- ?>
新闻热点
疑难解答