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
**
/* 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;
*/
**
Related
how to put date time in my image upload name code?
$allowed_types=array('image/jpg','image/png');
$image_name=$_FILES['thumnail']['name'];
$image_name=$image_name;
$tmp_name=$_FILES['thumnail']['tmp_name'];
move_uploaded_file($tmp_name,"upload/".$image_name);
Try this.
$allowed_types=array('image/jpg','image/png');
$image_name=$_FILES['thumnail']['name'];
$array = explode('.', $image_name);
$fileName=$array[0];
$fileExt=$array[1];
$image_name=$fileName."_".time().".".$fileExt;
$tmp_name=$_FILES['thumnail']['tmp_name'];
move_uploaded_file($tmp_name,"upload/".$image_name);
I am a newbie at PHP and I'm learning.
I've made a basic script where you can upload an image to a director on the server. I want the image names to get a number at the end so that the name won't be duplicated.
This is my script to add 1 to the name (I'm really bad at "for loops"):
for(x=0; $imageName => 50000; x++){
$imageFolderName = $imageName.$x;
}
Please tell me if I'm doing this totally wrong.
Adding to Niet's answer, you can do a foreach loop on all the files in your folder and prepend a number to the file name like so:
<?
$directory = 'directory_name';
$files = array_diff(scandir($directory), array('.', '..'));
$count = 0;
foreach($files as $file)
{
$count++;
rename($file, $count.'-'.$file);
}
?>
Alternatively you could rename the file to the timestamp of when it was uploaded and prepend some random characters to the file with the rand() function:
<?
$uploaded_name = 'generic-image.jpeg';
$new_name = time().rand(0, 999).$uploaded_name;
?>
You'll need to handle and move the uploaded files before and after the rename, but you get the general gist of how this would work.
Here's a potential trick to avoid looping:
$existingfiles = count(glob("files/*"));
// this assumes you are saving in a directory called files!
$finalName = $imageName.$existingfiles;
So right now I am trying to upload a .txt file and send it to mysql. That part works fine. But I have my code looking for a set file name, like text.txt. The txt file is being ftp'd into a directory, then a button in a php file is pressed and it looks for that file, reads it and sends it to the db. However, the file is going to be ftp'd with different names everday, like date. It will be uploaded like this: test20130802.txt
How do I get my code to look for that date variable? It won't always be today's date either.
Here is part of my current code:
$handle = #fopen("test.txt", "r");
$values='';
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
//MYSQL QUERY......
}
Any help is greatly appreciated. Thank you.
It is fairly straightforward I think.
First you take the name of the file "test20130802.txt" into a variable. e.g.
$readTestFile = "test20130802.txt"; //Or however you are taking the file name as input
Hopefully, you are getting a standard file name. (By standard I mean that the first few letters are consistently the same always.)
In case of standard file name:
$dateYearChar = array();
$dateMonthChar = array();
$dateDateChar = array();
for($i=0;$i<4;$i++)
$dateYearChar[$i] = $readTestFile[$i+4];
for($i=0;$i<2;$i++)
$dateMonthChar[$i] = $readTestFile[$i+8];
for($i=0;$i<2;$i++)
$dateDateChar[$i] = $readTestFile[$i+10];
$dateYear = intval($dateYearChar);
$dateMonth = intval($dateMonthChar);
$dateDate = intval($dateDateChar);
Edit: And you can do the reverse thing if you want to look for a filename with the specified format.
e.g.
$fileName = "test" . $dateYear . $dateMonth . $dateDate . ".txt"
I have the following code which uploads images to a rackspace cdn account.
error_reporting(E_ALL);
ini_set('display_errors', 1);
// include the API
require("cloudfiles.php") ;
// cloud info
$username = ''; // username
$key ='' ; // api key
$container = ''; // container name
ob_start();
$localfile = $_FILES['media']['tmp_name'];
$filename = $_FILES['media']['name'];
ob_flush();
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
// Get the container we want to use
$container = $conn->create_container($container);
// store file information
ob_flush();
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
$uri = $container->make_public();
//print "Your URL is: " . $object->public_uri();
$imagePageUrl = $object->public_uri();
//echo '<mediaurl>' . $imagePageUrl . '</mediaurl>';
ob_end_flush();
//echo '<mediaurl>' . $imagePageUrl . '</mediaurl>';
echo '<mediaurl>http://url.com/'.$filename.'</mediaurl>';
So each time i am uploading an image, say, image.jpg, it is overwriting the previous image.jpg in the container. I want to prevent that. Even if the filename is the same, is there a way to convert the filename to a random name, characters and then upload it?
Help plz.
Reading the other answers, while time() approach seems good, it does not provide real unique ids, its accuracy is only 1 second.
But PHP provides a way for having real unique IDS which is more accurate and provide a better solution. You could use it like:
$filename=uniqid().$_FILES['media']['tmp_name'];
Of course changing $_FILES['media']['tmp_name'] for whatever you prefer.
ok ... some code is missing ...
but you can try to give the new filename (uploaded image)... one name that is unique
simple example:
$filename = time()."-".$_FILES['media']['tmp_name'];
like this way your images will be named like '1333221458-my_image.jpg'
You can add the time to the filename, so assuming you will always have a .jpg:
$filename=explode(".",$filename);
$filename[0].="_".time();
$filename=implode(".",$filename);
I have a project that needs to create files using the fwrite in php. What I want to do is to make it generic, I want to make each file unique and dont overwrite on the others.
I am creating a project that will record the text from a php form and save it as html, so I want to output to have generated-file1.html and generated-file2.html, etc.. Thank you.
This will give you a count of the number of html files in a given directory
$filecount = count(glob("/Path/to/your/files/*.html"));
and then your new filename will be something like:
$generated_file_name = "generated-file".($filecount+1).".html";
and then fwrite using $generated_file_name
Although I've had to do a similar thing recently and used uniq instead. Like this:
$generated_file_name = md5(uniqid(mt_rand(), true)).".html";
I would suggest using the time as the first part of the filename (as that should then result in files being listed in chronological/alphabetic order, and then borrow from #TomcatExodus to improve the chances of the filename being unique (incase of two submissions being simultaneous).
<?php
$data = $_POST;
$md5 = md5( $data );
$time = time();
$filename_prefix = 'generated_file';
$filename_extn = 'htm';
$filename = $filename_prefix.'-'.$time.'-'.$md5.'.'.$filename_extn;
if( file_exists( $filename ) ){
# EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted
$filename = $filename_prefix.'-'.$time.'-'.$md5.'-'.uniqid().'.'.$filename_extn;
# IMPROBABLE that this will clash now...
}
if( file_exists( $filename ) ){
# Handle the Error Condition
}else{
file_put_contents( $filename , 'Whatever the File Content Should Be...' );
}
This would produce filenames like:
generated_file-1300080525-46ea0d5b246d2841744c26f72a86fc29.htm
generated_file-1300092315-5d350416626ab6bd2868aa84fe10f70c.htm
generated_file-1300109456-77eae508ae79df1ba5e2b2ada645e2ee.htm
If you want to make absolutely sure that you will not overwrite an existing file you could append a uniqid() to the filename. If you want it to be sequential you'll have to read existing files from your filesystem and calculate the next increment which can result in an IO overhead.
I'd go with the uniqid() method :)
If your implementation should result in unique form results every time (therefore unique files) you could hash form data into a filename, giving you unique paths, as well as the opportunity to quickly sort out duplicates;
// capture all posted form data into an array
// validate and sanitize as necessary
$data = $_POST;
// hash data for filename
$fname = md5(serialize($data));
$fpath = 'path/to/dir/' . $fname . '.html';
if(!file_exists($fpath)){
//write data to $fpath
}
Do something like this:
$i = 0;
while (file_exists("file-".$i.".html")) {
$i++;
}
$file = fopen("file-".$i.".html");