php performance for get and load avatar image - php

I add/upload image avatar using md5 user id and file_put_contents like this:
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = md5(Session::get('user_id')) . '.png';
file_put_contents(Config::get('PATH_UPLOAD') . '/' . Session::get('user_id') . '/' . $imageName, $data);
with this method I add only one image avatar for each user into my directory with this structure :
public
upload
images
avatar
77 <-- userID
d41d8cd98f00b204e9800998ecf8427e.png
Now I have two way for get image.
add image name/type into database and retrieve data from database and show in view page
get image name with session unique userId from file folder/directory without database
which way is better for performance(fast load)?!

Related

How to fetch images that stored in comma separated format in single row in MySQL?

I am uploading multiple images in the database in a single column with comma separated format. I am first creating a folder for each user and inside that folder, images are stored. car_images is my root directory inside that with the name of logged_in user new directory will create.
My images are stored in below format :
Here, emp_code is unique I am using this as SESSION and for the name of the folder of each user.
as you see car_images column where I am storing image name with ,.
I am using below code to stored images in folders and database. I don't know idea how to fetch all images of a single user.
$car_images_all="";
for($i=0; $i<count($_FILES['car_images']['name']); $i++)
{
$tmpFilePath = $_FILES['car_images']['tmp_name'][$i];
if ($tmpFilePath != "")
{
if (!file_exists('car_images/'.$emp_code))
{
mkdir('car_images/'.$emp_code, 0777, true);
}
$location = 'car_images/'.$emp_code.'/';
$name = $_FILES['car_images']['name'][$i];
$size = $_FILES['car_images']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
if(move_uploaded_file($_FILES['car_images']['tmp_name'][$i], $location.$filename))
{
$car_images_all.=$filename.",";
}
}
}
First of all,
Select all images from database by emp_code (as you want all images of a particular user/emp).
select car_images from TableName where emp_code = $emp_code;
Now, by this you will get one or more rows.
So, add one by one images to array with using explode() function per row (i.e. if row has multiple image name with comma separated).
Use the array as per your choice of manipulation.
Below code will fetch the data from table and save images in array. For more details check the explode function.
$query = "select car_images from table_name where emp_code = 'emp_code'";
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($result);
$images = $row['car_images'];
$images = explode(',',$images);
foreach($images AS $image){
echo '<img src="car_images/'.$emp_code.'/'.$image.'">';
}
You can use GROUP_CONCAT() function
SELECT GROUP_CONCAT(car_images) FROM TableName
You can use group by also with emp_code or brand_id or any other column whatever your business logic is met.
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY emp_code
OR
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY brand_id
<?php
$x=0;
$car_img =explode(",",$car_images);
foreach($car_img as $car_images{
$x+=1;0
?>
<?php echo '<img src="'."images/".$car_images.'" width="70" height="70" />';?>

images upload of any user in database

I have two tables:
first and parent "register"
and second is
What I wanted is to create a script in which one User with unique SN whenever upload a pic that pic path save in "userimg" i user SN as foreign key in userimg
code is below
if(isset($_POST['SN']))
{
$filename = $_FILES['upload_image']['name'].$user_SN;
$filesize = $_FILES['upload_image']['size'];
$filetype = $_FILES['upload_image']['type'];
$target_path ="uploads/". basename( $filename );
if (move_uploaded_file($_FILES['upload_image']['tmp_name'], $target_path))
{
$result = $target_path ;
$sql="INSERT INTO userimg (src, size, type,SN ) VALUES ('".$result."', '".$filesize."','".$filetype."','".$user_SN."')";
echo $sql." ";
echo $filesize." ";
echo $filetype." ";
$inst=mysql_query($sql);
if (!$inst)
{
print "error";
}
}
}
This script is working for one picture but what I want is like multiple uploads (just like a gallery) by user and saving that path in my second table.
Do I need to create a userimg table for each SN means user? What am I missing?
[EDIT]
Problem solved. Mistake was Making SN in userimg a unique and i rename image like this(code is below ) - Thankx Tuhin!
if(isset($_POST['SN']))
{
$filename = $_FILES['upload_image']['name'];
$filesize = $_FILES['upload_image']['size'];
$filetype = $_FILES['upload_image']['type'];
$timeSt = time();
$info = pathinfo($filename);
$name = $info['filename'];
$format = $info['extension'];
$target_path ="uploads/".basename( $name )."_".$user_SN."_".$timeSt.".".$format;
}
If the same user (means same SN value) tries to upload the same image (means already uploaded by him with same image name in this app) then the 'src' column in the second table will be same. Also if the uploaded folder first image file will be replaced by the newer file. Thats why I proposed you to add time stamp and rename the uploaded image file and store it into the DB.

Delete files that are not in my database

I'm trying to delete photos from a folder, which is called, "photos", that are NOT currently in my database. (These are all photos that have stacked up as I've been building the website and testing it and such, so now it's time to take the site live and I don't want all this waste in it)
I have three tables with photo information in them, and a number of columns throughout. Below is a mockup query of about what I THINK it should look like.
SELECT left_image, right_image, photo1, photo2, photo3, photo4, home_photo
FROM about_photos, facilities, home
left_image and right_image go with about_photos.
photo1, photo2, photo3 and photo4 go with facilities.
home_photo goes with home.
Also, I need to use a wildcard for the end of the photo, because the files have thumbnails, so for instance the original photo would be called, abcimage.jpg but there would be abcimage.jpg, abcimage_medium.jpg, abcimage_thumb.jpg also in the database I only store, photos/abcimage and add the rest of the filename depending on where it goes.
$directory = "../path/to/photos_directory/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT id FROM table WHERE photo1='$name' OR photo2='$name'");
if(mysql_num_rows($sql) == 0)
unlink($directory . $image);
}
You have two options:
One:
With an SQL query, get a complete list of all the photos referenced in your database
iterate through the files in your directory
if the file is an image AND it is not in your list, delete the file.
Two:
iterate through the files in your directory
if the file is an image
query the database for that filename
if the response is empty, delete the file
The exact SQL query depends on your table structure, which you have not provided.
The best option depends mostly on scale. If there are lots of images in the database, then the first option involves having a very large list in memory. However the second version involves many more database queries. So it's a tradeoff.
There are more sophisticated options involving caching and pre-emptive queries, but I imagine you don't want to go that deep yet.
Something like the following. I've also got original files in the folder and I limit to 500 deletions at a time. Tweak as you need. Hope it saves somebody time...
<?php
require 'session.php';
require 'settings.php';
/* Execute the query. */
$DBH = new PDO($mssql_driver.'='.$mssql_server.';'.$mssql_dbkey.'='.$mssql_database, $mssql_username, $mssql_password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$tsql = 'select * from ProductImage';
$PRE = $DBH->prepare($tsql);
$PRE->execute();
$pictures =$PRE->fetchAll(PDO::FETCH_ASSOC);
$directory = $_SERVER["DOCUMENT_ROOT"]."\..\..\products\pictures/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
$counter =0;
foreach($images as $image)
{
$name = explode('pictures/',$image);
$name = $name[1];
$foundImage = false;
print "checking: ".$name;
foreach ($pictures as $picture){
$original_file = explode('.', $picture['Image_Big']);
$original_file = $original_file[0].'-original.'.$original_file[1];
if ( ($picture['Image_Small'] == $name)|| ($picture['Image_Big'] == $name) || ( $original_file == $name) || ($picture['Image_Thumb'] == $name) || ($picture['Image_PriceList'] == $name)){
$foundImage = true;
break;
}
}
if (!$foundImage) {
unlink($directory . $name);
print "....deleting";
$counter += 1;
}
print "<br />";
if ($counter> 500){
exit;
}
}
?>

Deleting a product with related pictures with PHP

In my PHP application I have products which have images in 3 sizes - big, thumbnails and small thumbnails. Each image is stored in a separate folder:
Images - /gallery
Thumbnails - /gallery/bigthumbs
Small thumbnails - /gallery/thumbs
Each product has its unique ID. The file names of all images of a certain product are the same. The path to the images for the product are being stored in the database with the same ID as the associated product ID.
Each product can have more than 1 image but in the database, where I store the paths and the names of the images for each product, all the images are stored with the same ID, the same as the product ID.
So, if a product with ID 56 has 2 images in the database, those images will be stored like this:
ID->56, image1name, bigthumb1name, thumb1name
ID->56, image2name, bigthumb2name, thumb2name
What I'm trying to do is - delete all the images associated with the product which is being deleted. The code I've written is as follows:
$imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);
$imagename_result = mysql_fetch_array($imagename_query);
foreach($imagename_result as $imagename) {
$bigimage = "../gallery/$imagename";
unlink($bigimage);
$picture = "../gallery/bigthumbs/$imagename";
unlink($picture);
$thumb = "../gallery/thumbs/$imagename";
unlink($thumb);
}
$gallery_query = mysql_query("DELETE FROM gallery WHERE id='$productid'", $connect);
$query = mysql_query("DELETE FROM products WHERE ID='$productid'", $connect);
The problem is that the code above deletes only 1 image - no difference how many images there are with the same ID.
Could anybody help me figure this out?
Thanks in advance.
this line is the problem
$imagename_result = mysql_fetch_array($imagename_query);
should be
while ($row = mysql_fetch_array($imagename_query))
{
$bigimage = "../gallery/{$row['image']}";
unlink($bigimage);
// etc
}
I not sure is it truth for your case -- do you have multiple products with same name?
your approach could be a bit risky ...
you can make the folder path unique by embed the product id
such as
/gallery/{$product_id}/{$product_name}.*
since you have more images you shoud use:
while ($current_imagename_result = mysql_fetch_array($imagename_query))
instead of
$imagename_result = mysql_fetch_array($imagename_query);
and after you will have to use $current_imagename_result instead of yor varable
Thanks everybody for help. I've managed to solve this in the following way:
$imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);
$rows_count = mysql_num_rows($imagename_query);
for($i=0; $i<$rows_count; $i++){
$id = mysql_result($imagename_query, $i, 'image');
$bigimage = "../gallery/$id";
unlink($bigimage);
$picture = "../gallery/bigthumbs/$id";
unlink($picture);
$thumb = "../gallery/thumbs/$id";
unlink($thumb);
}
Hope this will help somebody else.

PHP/HTML/mySQL URL Caching Problem

I have this function: http://pastebin.ca/2058418
It basically checks to see if a tables contains some URLs to pictures of a band. If it does, then it will order the table by random, choose the first result and then output the html code to insert the picture. If the table does not have the pictures of that specific band, then it downloads an XML file which contains the image URL's, parses the XML and inserts in into the table, and then gets the HTML code for the image like before.
In terms out html output, you can't tell if the image URL has been cached or not. HOWEVER, when the image URL is cached (for the first time), whatever web browser you use will not display the image. The HTML is fine - the image is linked correctly.
Do you have any ideas? A live version of the site which contains this function is here: http://redfern.me/similar/. I have just emptied the tables, so there shouldn't be many cached URL's. Try choosing a band, and then see if the image loads. You can tell if the URL's where cached or not by looking at the bottom of the page.
basically looks like you wasn't returning after you fetched the image first time.
<?php function getimage($artist){
$api_key = "XXXXXXXXX";
$iquery = mysql_query("SELECT url FROM `images` WHERE artist = '".$artist."' ORDER BY RAND() LIMIT 1");
if($artist != ""){
$artist = str_replace(" ", "+", $artist);
if(mysql_num_rows($iquery) == 0){
$url = "http://developer.echonest.com/api/v4/artist/images?format=xml&api_key=".$api_key."&name=".$artist."&results=20";
$data = file_get_contents($url);
if($data=false){return 'Error Getting Image';}
$images = new SimpleXMLElement($data);
foreach($images as $image){
foreach($image->image as $indimage){
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
return "<img src=\"".$indimage->url."\" alt=\"$artist image\" />";
}else{
$imgurl = mysql_fetch_array($iquery);
return"<img src=\"".$imgurl['url']."\" alt=\"$artist image\" />";
}
}
else{
return"Image Aquire Function Error: <i>No Band Specified</i>";
}
return null;
}?>
echo getimage('Britney Spears');
That's simply because when you enter to the "xml call" your var "$imgurl[0]"
is empty :
try something like this :
$images = new SimpleXMLElement($data);
$xmlImgUrl = array();
foreach($images as $image){
foreach($image->image as $indimage){
$xmlImgUrl[] = $indimage->url;
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
}
$imgurl = $nrows == 0 ? $xmlImgUrl : mysql_fetch_row($iquery);
if(!empty($imgurl)) echo "<img src=\"".$imgurl[0]."\" alt=\"$artist image\">";
which instantiate an array of image urls when no results in mysql.

Categories