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


PHP Upload File with date and time

我正在使用此功能上传文件例如,如何将文件名更改为:当前日期和时间。与上传文件的任何用户一样,该文件将上传到用户标识文件,但具有实际文件的名称,而不是当前日期和时间。例如: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');
    }
}
?>

尝试使用 -

$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;
它是

$target_file变量。请注意,斜杠在文件名中无效。有关日期,请参阅手册中的日期函数。

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

请看这一行:

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

这就是文件的结果路径的形成方式。若要为文件指定自定义名称,请将 $target_dir . 后的代码替换为其他内容以命名文件。