PHP 上传带有日期和时间的文件

PHP Upload File with date and time

我正在使用这个功能上传文件 我如何将文件名更改为:例如当前日期和时间。作为上传文件的任何用户,它被上传到用户 ID 文件,但使用实际文件的名称,而不是当前的日期和时间。例如:14/09/02/18:32

<?php

    session_start();

if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"])) {
      // redirect to login page
}



$target_dir = ('users/'.$_SESSION["user"]["id"].'/');
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image


// Check if file already exists

// Check file size

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo header('Location: main.php');
    }
}
?>

:

它是 $target_file 变量。请注意,斜杠在文件名中无效。对于日期,请参阅 Manual.

中的日期函数

更好的方法是使用默认的 img 名称和附加日期,

看看这一行:

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

这就是文件路径的形成方式。要给文件一个自定义名称,请将 $target_dir . 之后的代码替换为其他名称以命名您的文件。

试试 -

$name = $_FILES["fileToUpload"]["name"];
$nameArr = explode('.', $name);
$ext = $nameArr[count($nameArr) - 1];
$newName = date('your-prefered-format').'.'.$ext;

尝试在上传前重命名您的文件。

$target_dir = ('users/'.$_SESSION["user"]["id"].'/');
$removeExtension = explode('.',basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir .date("m-d-y").date("h-i-sa").".$removeExtension[1]"); //renamin the file to the current time as e.g. 02-03-15-01-13-18pm.jpg
$uploadOk = 1;