简体   繁体   English

php使用特定文件名保存图像不会相互覆盖

[英]php save image with specific file name not overwriting each other

I hope someone can help me with this php code.我希望有人可以帮助我处理这个 php 代码。 At the moment its just saving an image with the file name "img.png" to the server but with every time a new canvas screenshot is taken the image is just overwritten.目前它只是将文件名为“img.png”的图像保存到服务器,但每次拍摄新的画布屏幕截图时,图像都会被覆盖。

My aim is to create a new unique (like numbered chronological by time taken) file name for the images with every new screenshot and save it on the server.我的目标是为每个新屏幕截图的图像创建一个新的唯一(如按时间顺序编号)文件名,并将其保存在服务器上。

Here the php code so far:到目前为止的 php 代码:

$data = $_REQUEST['base64data']; 
echo $data;

$image = explode('base64,',$data); 

file_put_contents('img.png', base64_decode($image[1])); 

Thank you.谢谢你。 regards问候

Try尝试

$filename = 'img_'.date('Y-m-d-H-s').'.png';
file_put_contents($filename, base64_decode($image[1]));

This will save your file with a filename containing the current date and time, eg这将使用包含当前日期和时间的文件名保存您的文件,例如

img_2013-09-19-21-50.png

Try using a session variable to increment a counter like so:尝试使用会话变量来增加计数器,如下所示:

<?php
session_start();
if(!isset($_SESSION['counter'])){
    $_SESSION['counter'] = 0;
}
$_SESSION['counter']++;

$data = $_REQUEST['base64data']; 
echo $data;

$image = explode('base64,',$data); 

file_put_contents('img'.$_SESSION['counter'].'.png', base64_decode($image[1])); 
?>

There's several ways to do it, but the easiest is just to add a timestamp/datestamp to the image name.有几种方法可以做到这一点,但最简单的方法是在图像名称中添加时间戳/日期戳。 Format the name as you want.根据需要格式化名称。

$img_name = 'img'.date('YmdHisu').'.png'; // Date & time with microseconds
$img_name = 'img'.time().'.png'; // unix timestamp

Leave the base64data structure use this one it will work fine.让 base64 数据结构使用这个它会正常工作。

$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); 
$image = explode(".", $fileName);

It will give a random number to each image file.它将为每个图像文件提供一个随机数。

either create a UID using uniqid() function for the filename or create a folder with the name of the username who is uploading the file and leave the original filename.要么使用 uniqid() 函数为文件名创建一个 UID,要么创建一个带有上传文件的用户名的文件夹并保留原始文件名。 The disadvantage of the first one is that you will have to save the original filename somewhere to show to the user.第一个的缺点是您必须将原始文件名保存在某处以显示给用户。

https://stackoverflow.com/a/4371988/2701758 https://stackoverflow.com/a/4371988/2701758

** **

 /* simply for local time first give your continent then '/' then your country's capital. */ date_default_timezone_set('Asia/Dhaka'); $now = new DateTime(); $now = $now->format("Ymd H:i:su"); $new_name = $now.$image; /*what you want to add just write with dot,such $new_name = 'img'.$now.$image; */

** **

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM