0

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

Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
Mazey
  • 37
  • 1
  • 2
  • 9

6 Answers6

1

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
Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
  • perfect thx. Is it also possible to get the IP of the user who clicked or unique browser data to implement into the file name? – Mazey Sep 19 '13 at 20:10
  • 1
    You might want to include information from [the PHP `$_SERVER` variable](http://php.net/manual/en/reserved.variables.server.php). For example: `$filename = 'img_'.$_SERVER['REMOTE_ADDR'].'.png';`. – Gottlieb Notschnabel Sep 19 '13 at 20:15
0

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])); 
?>
Andy Gee
  • 3,149
  • 2
  • 29
  • 44
0

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
aynber
  • 22,380
  • 8
  • 50
  • 63
0

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.

Aitazaz Khan
  • 1,609
  • 1
  • 13
  • 35
0

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

Community
  • 1
  • 1
0

**

 
 /* 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("Y-m-d H:i:s.u");
    
    $new_name = $now.$image;
  /*what you want to add just write with dot,such 
    $new_name = 'img'.$now.$image;
   */

**