开发者

Append date to filename before copy in php

I am trying to append date to the file name before copying in PHP.

$fileS = "file.csv";
$date = date('m-d-Y H:i:s A e');
$fileD = "file$date.csv";

I have even tried

$fileD = "file"."date('m-d-Y H:i:s A e')".".csv";

Then I copy the files

$Confirm = copy($fileS, $fileD);

I know I should check if the file exists etc etc but for the sake of simplicity to ask the question I am using this :).

I am assuming it's something to do with the copy function that doesn't read concatenated strings. I may be wrong here.

Any help with this is great appreciated.

EDIT: The colon seems to be the problem not the $fileD. Any type of concatenation would work. (Thanks to Greenisha).

This one works but any ideas to make it work with the colon. It seems weird to have the time with '-' instead of ':'.

$date = date('m-d-Y H-i-s A e');

Never mind. Colons are not allowed in the file naming convention in windows. Overlooked that part. Thanks Michael.

I am creating this in windows now but when it goes to production it will b开发者_开发技巧e in in UNIX. So will the colon work there if I change it? Any suggestion will be useful down the road. Thanks for your help.


Try it using a date format that doesn't include colons. Colons are not permitted in Windows filenames, and perhaps other filesystem types.

// Try, for example
$fileD = "file".date('m-d-Y-His A e').".csv";


As far as I see, your problem is because of identifier:

e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores

But filename can't be with "/" inside. Try using another date format


You know, I'm always wary of putting spaces in file names, call it a throwback to the 80's and 90's. What happens if you just try:

var_dump(preg_replace('-\W-','_',date('m-d-Y H:i:s A e')));


You could do: $fileD = "file".$date.".csv";

Or: $fileD = "file{$date}.csv";


When you concatenate a statement (such as your date function) it should not be surrounded by quotes. So your second example should work written like so:

$fileD = "file".date('m-d-Y H:i:s A e').".csv";


Try this utility function:

public static function appendDateTimeToFileName($fileName) {
    $appended = date('_Y_m_d_H_i_s');
    $dotCount = substr_count($fileName, '.');
    if (!$dotCount) {
        return $fileName . $appended;
    }
    $extension = pathinfo($fileName, PATHINFO_EXTENSION);
    $fileName = pathinfo($fileName, PATHINFO_FILENAME);
    return $fileName . $appended . '.' . $extension;
}

Example:

sample.jpg  -> sample_2017_02_19_01_09_10.jpg
sample      -> sample_2017_02_19_01_09_44
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜