php保存带有特定文件名的图像,不会互相覆盖

I hope someone can help me with this php code. 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.

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:

$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, e.g.

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.

$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. 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