php 以时间命名文件,php – 如何在上传到服务器之前重命名每个文件到时间戳

有关文件上传和解释的正确示例,请参阅

this website.此外,

this site似乎是您发现此特定脚本的地方,如果没有提供一个很好的解释.

我已修改您的代码以包含一些注释,以便您和其他人可以更好地了解正在发生的事情.从理论上讲,代码不应该像你说的那样覆盖现有文件,但我已经添加了你需要更改的内容,以便将文件名设置为随机字符串.

此外,您将原始文件名存储到会话中,而不是修改后的文件名.

define("UPLOAD_DIR", "/path/to/uploads/");

if (!empty($_FILES["ambum_art"]))

{

// The file uploaded

$myFile = $_FILES["ambum_art"];

// Check there was no errors

if ($myFile["error"] !== UPLOAD_ERR_OK) {

echo "

An error occurred.

";

exit;

}

// Rename the file so it only contains A-Z, 0-9 . _ -

$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

// Split the name into useful parts

$parts = pathinfo($name);

// This part of the code should continue to loop until a filename has been found that does not already exist.

$i = 0;

while (file_exists(UPLOAD_DIR . $name)) {

$i++;

$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];

}

// If you want to set a random unique name for the file then uncomment the following line and remove the above

// $name = uniqid() . $parts["extension"];

// Now its time to save the uploaded file in your upload directory with the new name

$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);

// If saving failed then quit execution

if (!$success) {

echo "

Unable to save file.

";

exit;

}

// Set file path to the $Dir variable

$Dir = UPLOAD_DIR .'/'. $name;

// Set the permissions on the newly uploaded file

chmod($Dir, 0644);

// Your application specific session stuff

unset($_SESSION['video']);

$_SESSION['album_art'] = $Dir; // Save the file path to the session

$ambum_art_result = array();

$ambum_art_result['content'] = $Dir;

echo json_encode($ambum_art_result);

}

阅读有关PHP uniqid的更多信息.

我还强烈建议做一些文件类型检查,因为它似乎可以上传任何文件.上面的第二个链接有一个标题为“安全注意事项”的部分,我建议您仔细阅读.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值