I am creating code to upload images in a folder using PHP, & before upload an image I check that if any image with same name already exists in the folder by using below syntax:
if (file_exists('profilephoto/' . 'frame.gif')) {
}
But actually I don't want to restrict the user to upload more images with same name & obviously it is impossible to save two images with same name , but there is a way to just find total number of images with same name & upload the next image with appending total number + 1 with image name.
Now I just want to know that using PHP how could we find total number of images having same name in a folder?
<?php
$i = '';
while ( file_exists($filename = ('profilephoto/' . "frame$i.gif")) )
++$i;
echo $filename;
?>
Obviously it's subject to "race conditions," but that's probably the least of your concerns.
Related
I am currently developing a web application and need some help.
The functionality is the following: A website connected to a mysql database. You need to select two times brand and then products from that brand solved via interlinked dynamic dropdowns. Based on that selections happen two queries selecting color values from the database, showing them in textfields.
Solved via jquery, PHP and JSON.
Now I have created a section, which will show an image in the color from the selected RGB values from the DB. PHP needs to create the JPG image using the RGB values from the DB and save the image on the server.
When I implement imagecreate in php and hand over the path to jquery to allocate it to a '"#target", I get the issues.
I considered two ways:
a) generate image on the fly, name it 1.jpg and overwrite the image in every instance. Then I run into issues with the browser cache, loading the previous image although the new image is already stored in the folder.
b) generate new images and save them for better performance named with the RGB values (i.e 151|50|22.jpg) and load if already existing, create if not, but there I cannot save the path when a variable is in the imagejpeg() function in PHP?
I can save i)a combination of path elements and a string '1.jpg' and ii)a path made from a pure string but not a path made from a combination of text and a variable carrying the right image name.
Propably it is done with right escaping of the variable???
Errors are:
Warning: imagejpeg(images\rgb\225|151|169.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\COLOMETRIX\get_swatch_1a.php on line 39
{"decision":"images\rgb\225|151|169.jpg"} this is the Json output
Code is a follows:
<?php
$prod1 = $_GET['q'];
include('db_config.php');
// clear variables
$decision='';
$data='';
// select dataset
$result=$db->query("SELECT R, G, B, Get_Col, Selection
FROM farbdatenbank.farbdatenbank
WHERE Name ='".$prod1."' ")
or die($db->error);
$datensatz=$result->fetch_array(MYSQLI_ASSOC);
// define paths and filename
$file=$datensatz['Get_Col'];
$filename=$file.".jpg";
$path_rgb='images'.DIRECTORY_SEPARATOR.'rgb'.DIRECTORY_SEPARATOR.$filename;
if($datensatz['Selection'] == "Excel"){
// get color values
$R=$datensatz['R'];
$G=$datensatz['G'];
$B=$datensatz['B'];
//check if file already exists
if (file_exists($path_rgb) == true) {
$decision=$path_rgb;
}
else
{
// create new image
$im1=imagecreatetruecolor(150, 70);
$colim1=imagecolorallocate($im1, $R, $G, $B);
imagefill($im1,0,0,$colim1);
$old = 'images'.DIRECTORY_SEPARATOR.'rgb'.DIRECTORY_SEPARATOR.'zzz.jpg';
imagejpeg($im1,$path_rgb,100);
$decision=$path_rgb;
}
}
Else
{
$decision='images'.DIRECTORY_SEPARATOR.'pics'.DIRECTORY_SEPARATOR.$filename;
}
// build output array and encode in JSON format
$data=array("decision"=>$decision);
echo json_encode($data);
mysqli_close($db);
?>
Thanks for your time
Michael
I was trying to insert images into banner dynamically, and is now working correctly. I upload my images and insert on database name of image if there are no validotor errors.
But I'd like to ask you a question that came to my mind, and I'm not finding the answer.
To insert an image, I want to check if the image already exists and also if there are more than 5 images, 5 images because I just want the maximum of 5 images at time on banner.
Im doing this, consulting my directory folder when I save images, and not consulting database.
What do you think better in terms of performance? Or is it the same? Do you see any advantage like Im doing?
heres my code example:
extAlllowed = array('image/jpeg','image/pjpeg','image/png','image/gif');
$myDirectory = ../banner-images/;
if(in_array($img['type'][$i],$extAlllowed))
{
$fi = new FilesystemIterator($myDirectory, FilesystemIterator::SKIP_DOTS);
echo iterator_count($fi);
if(file_exists($myDirectory.$image))
{
echo'Image selected already exist';
}
else if(iterator_count($fi)>=5)
{
echo'You can have only 5 images at time in banner.';
}
else
{
uploadImage($img['tmp_name'][$i],$image,'2000',$myDirectory);
$inseretBanner = $pdo->prepare("INSERT INTO banners (img) VALUES (:img)");
$inseretBanner->bindValue(':img', $image);
$inseretBanner->execute();
echo'Image inserted with sucess';
}
}
Considering having several image files it would be faster to maintain a counter in the database, that contains the current image amount. The FilesystemIterator will internally run over all files to count them, what can lead to poor performance. A simple query (for example: SELECT image_amount FROM users WHERE id = [your current user]) to a database will be faster in most cases.
If you do so, you have to update the counter each time you insert/delete an image in the database.
Hope that helps.
I'm doing a check like this:
// ADDITIONAL PRODUCT IMAGE
$add1 = #get_headers("https://{image_server_link}/DIx.jpg_RB2000,2000,255,255,255,127/-/article/" . $product_number . "_1.jpg");
if(strpos($add1[0], "404") === FALSE) {
// Image found, so let's print it out
}
It's inside a CSV generator, and because of the csv contains 2000+ products the get_headers slows down generation from 3 to 4 MB/S to 10-15KB/s. As our CSV is 6.9 MB this will take ages.
Is their any other option to check if an additional image exists which is faster?
By the way, the images are hosted on a seperate image-server with varnish caching, so it's not possible to do a is_file function or something..
You could make a php script on the other side that gives you a list of available images or checks for availability of multiple images at once (a web service).
Edit:
Or just use the index page of the image directory.
I would like to change the code on my php uploading page so it uploaded photos with sequential numbering 1.jpg 2.jpg 3.jpg... 9999999.jpg
I want to name images in an ascending order starting with 1 and going to infinity.
I don't want any images to be over written and I think a counter can be used for this, but i'm unaware of how to code it properly.
Uploaded images are stored in two directories. 1. original file 2. thumbnail
$DestinationDirectory = 'user-uploads/'; //original file
$DestinationDirectorytn = 'user-uploads-thumbnails/'; //original file thumbnail
Currently it names the file by the time() function
// current time value, will be added as the new image name
$CurrentTime = time();
//Construct a new image name (time) for our new image.
$NewImageName = $CurrentTime.'.'.$ImageExt;
You can count the files in directory and increment the value for to name of file.
The link have example: http://www.brightcherry.co.uk/scribbles/php-count-files-in-a-directory/
After that count the files, you set the name of file: concat value with name.
Thanks
But have many other ways.
Try this:
$directory = "user-uploads/";
$filecount = count(glob($directory . "*"))+1;
//Construct a new image name (time) for our new image.
$NewImageName = $filecount.'.'.$ImageExt;
I have a form whereby Users upload pictures as part of their registration process. But my issue is that, users that save the names of their image with the same name might cause some issues when they view the profile pictures. How can i make the picture name unique at the point of uploading to the filesystem..
Thanks.
I would suggest using one of the following schemes:
make the filename a function of the username/userid
make the filename a random value
make the filename a function of the file content (e.g. an MD5 checksum)
If this helps
$t = uniqid();
$filename='user-'.$t;
echo $filename; // user-1335601088 (always a different name)