Check current image being displayed on page - php

I currently have this code:
$img_dir = 'tsimgs/';
$images = array();
$files = scandir($img_dir);
foreach($files as $f) {
$extension = end(explode('.',$f));
if($extension == 'jpg') {
$images[] = $f;
}
elseif($extension == 'png') {
$images[] = $f;
}
}
$random = array_rand($images);
$chosen = $images[$random];
if(end(explode('.',$chosen)) == 'jpg') {
$image = imagecreatefromjpeg($img_dir.$chosen);
}
elseif(end(explode('.',$chosen)) == 'png') {
$image = imagecreatefrompng($img_dir.$chosen);
}
// WRITE OUT THE IMAGE //
header('Content-type: image/jpeg');
imagejpeg($image, NULL, 100);
imagedestroy($image);
Basically this displays a random image on webpage visit. How would I make a script to check which image is currently being displayed to the user. Is that even possible?

This might not be a perfect solution, but if you are already using sessions you could set a session variable when selecting the image to show to the user, and then fetch it when you want to know which image is being displayed.
You have to remember though, that if the user has multiple windows open there is no guarantee that this works.

Related

php getimagesize mixes up width and height for IOS GIFs (Live Photos)

i am using php getimagesize to set width and height columns in the database. works fine with with every image except some GIFs shot by an Iphone camera(Live Photos). in that case the width and height are switched. my first thought was to use exif_read_data to check orientation and rotate. But i do not believe this it supports GIFs. what is the best way to identify disoriented images? if this is indeed the issue?
$img = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $media));
if (!$img) {
echo "!img media: $media";
return false;
}
$tfn = $user_id.''.time().'tmp';
file_put_contents($tfn, $img);
$info = getimagesize($tfn);
unlink($tfn);
if (($info[0] > 0 && $info[1] > 0 && $info['mime'])) {
$mfa = explode('/', $info['mime']);
if($mfa[0] != 'image'){
echo "not an image";
return 0;
}
$media_format = $mfa[1];
if($media_type = "gif") {$media_format = "gif";$media_type = "image";}
$media_name = md5("kaa".$page_id."".time()."".$user_id).".".$media_format;
$file = rand(0,1000000);
$path = "/var/www/html/api/media/posts/".$file;
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $media));
if(!file_exists($path))
mkdir($path, 0777, true);
if(!file_put_contents($path.'/'.$media_name, $data)){
return 0;
}
$media_p = $file.'/'.$media_name;
$dimens = $info[0].'x'.$info[1];
//echo "info[3] = ";echo $info[3];
}
`

Issue when uploading image to tmp folder, resize and then upload to S3 bucket

I've spend all day figuring out how to store an image in tmp, change its size and then upload it to my S3 bucket. The S3 bucket works fine and i am able to upload images when i don't resize. The resize function is the createThumbnail function and works fine when not combined with S3 probably because it's a wrong format or something. The second file "init.php" contains all the functions. The images are uploaded to the temp folder but when i run the script it doesn't get uploaded after it's resized. I don't get any error logs on localhost and when i upload the code to my AWS instance it just returns a internal server error but the error log in my instance is oddly empty... I need some fresh eyes on this issue.
banner_image.php
<?php
include "init.php";
if (#session($_SESSION["buddy"])){
$valid_file_formats = array("jpg","png","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST" && !empty($_FILES['banner_image']['tmp_name']) && !empty($_FILES['banner_image']['name'])){
$folder = usernameFromEmail($_SESSION["user"]); // session based on users email
$buddy = $_SESSION["user"];
$name = $_FILES['banner_image']['name'];
$size = $_FILES['banner_image']['size'];
$path = $folder."/cover/"; // path to image folder
$temp = explode(".", $name);
$newfilenameKey = round(microtime(true)); // generating random file name
$newfilename = $newfilenameKey . "." . "png"; // always using png
if(strlen($newfilename) && strlen($name)) {
$ext = explode(".", $name);
$ext = end($ext);
if(in_array($ext,$valid_file_formats)) { // valid file format array check
if($size<=(10485760)) { // size check in bits
$tmp = $_FILES['banner_image']['tmp_name'];
$file_name = $path.$newfilename; // full path including file name
if(putS3IMG($bucket, $file_name, $tmp)){ // upload untouched image to S3 bucket
list($width, $height) = getimagesize($tmp);
$type = 2;
$w = 300;
$h = 300 * ($height / $width);
// getting new dimensions for the new image
if(createThumbnail(1,$tmp,$w,$h,$path,$file_name) == 1){ // function for smaller image
return json_encode(array("succ" => 1));
}
}
}
}
}
}
}
?>
here is my init.php file included in the banner_image.php file which contains my functions.
<?php
// connection to S3Client .... $client
function createThumbnail($type,$image_name,$new_width,$new_height,$uploadDir,$moveToDir){
global $bucket;
//$type: defines the name of the new file
//image_name: tmp name
//uploadDir: path
//moveToDir: files new path incl. file name
$mime = getimagesize($image_name);
if($mime['mime']=='image/png') {
$src_img = imagecreatefrompng($image_name);
} else if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$src_img = imagecreatefromjpeg($image_name);
}
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
$thumb_w = $new_width;
$thumb_h = $new_height;
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
$background = imagecolorallocate($dst_img, 0, 0, 0);
imagecolortransparent($dst_img, $background);
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
$image_name_new = explode(".", $moveToDir);
if ($type == 1){
$new_image_name = $image_name_new[0] . "_thumb." . $image_name_new[1];
} else if ($type == 2){
$new_image_name = $image_name_new[0] . "_image." . $image_name_new[1];
}
$tmpPath = tempnam(sys_get_temp_dir(), $new_image_name); // getting temporary directory
if($mime['mime']=='image/png') {
imagepng($dst_img,$tmpPath,8);
} else if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
imagejpeg($dst_img,$tmpPath,80);
}
imagedestroy($dst_img);
imagedestroy($src_img);
if(putS3IMG($bucket, $image_name, $tmpPath)){ // this part does not work
return 1;
} else {
return 2;
}
}
function putS3IMG($bucket, $file_name, $tmp){ // function uploading to my bucket
//file_name is with directories
//tmp is $_FILES tmp_name
global $client;
$result = $client->putObject([
'Bucket' => $bucket,
'Key' => $file_name,
'SourceFile' => $tmp
]);
if ($result){
return true;
}
return false;
}
SOLUTION:okay, so eventually i ended up using AWS lambda which solved the issue but it isn't a free solution. So, if any of you come up with a solution that allow you to resize without using third party tools feel free to comment it in order to make life easier for the next programmers viewing this question.

resize multiple images while uploading

Hi im trying to resize multiple image while uploading i have the function that resize but its only work for one image so please can anyone shom me how to loop this for multiple file upload
if( $_FILES['image']['size']< $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $w => $h) {
$files[] = resize($w, $h);
}
} else {
$msg = 'Unsupported file';
}
} else{
$msg = 'Please upload image smaller than 200KB';
}
This is untested, but might give you an idea.
The way this works is by looping through all of the $_FILES of the variable $iname which is 'image'. I set this since it's used multiple times, so if you ever change it, its easier.
I create a new variable called $image which will be the variables for that specific image. I do this by looping through all of the variables of $_FILES[$iname]. I set the $image variable to the $key and the new value, which will be an array. We reference the correct array using the $i variable.
Next I simply use your existing code. Since the resize() function only calls for width and height, I am unsure what happens here. Another parameter should be passed to reference the image you want to resize, which will be $image.
From the visible code I typed, not knowing what resize() is, this code is insecure. You should really check more than just the file extension since it can easily be changed. I usually use exif to check the image header. I also never store the data users upload unless I re-encode it using a GDI function in PHP.
Hopefully this will get you started.
$i = 0;
$iname = 'image';
for($i = 0; $i < count($_FILES[$iname]['size']); $i++) {
// Create new Image Array
$image = array();
foreach($_FILES[$iname] as $key => $val) {
$image[$key] = $val[$i];
}
if( $image['size'] < $max_file_size ) {
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
foreach ($sizes as $w => $h) {
// How is resize getting the $_FILES?
// Should pass a variable of $image and use it instead
$files[] = resize($w, $h);
}
} else {
$msg = 'Unsupported file';
}
} else{
$msg = 'Please upload image smaller than 200KB';
}
}

How can I allow other image formats to be uploaded

This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);

refresh image on upload

I have a script which uploads an image to the server under the id of the user. To change teh picture the first gets overwritten. The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
Script:
function uploadProfilePicture($memberID,$extension)
{
##### FIND ERRORS #####
$error = "";
// check if larger than 5mb
$avatar = $_FILES['uploadedAvatar'];
if( $avatar["size"] > 5000000 ){ //5mb
$error = SETTINGSphoto_less_5meg;
}
//check if member selected a photo
if( $avatar['name'] == "" ){
$error = SETTINGSphoto_no_upload;
}
//check if photo is of allowed formats
if( $avatar["type"] != "image/png" ){
if( $avatar["type"] != "image/gif" ){
if( $avatar["type"] != "image/jpg" ){
if( $avatar["type"] != "image/jpeg" ){
if( $avatar["type"] != "image/pjpeg" ){
$error = SETTINGSphoto_file_type;
}
}
}
}
}
#### END FIND ERRORS #####
##### DISPLAYS ERRORS ######
if( $error != ""){
echo '<span style="background-color:#E05641;" class="pint2">'.$error.'</span>';
##### END DISPLAYS ERRORS ######
##### PROCESS THUMBNAIL AND UPLOAD PICTURE #####
}else{
$ext = substr($avatar["name"], -4); //take off extention.
$fileName = $memberID.$extension.$ext; // rename picture with member's ID.w
unlink("photos/".$memberID.$extension.".jpg");
unlink("photos/".$memberID.$extension."Thumb.jpg");
copy($avatar['tmp_name'], "photos/".$fileName); //upload temp
//create virual image
if(preg_match('/[.](jpg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
} else if (preg_match('/[.](gif)$/', strtolower($avatar["name"]))) {
$im = imagecreatefromgif("photos/".$fileName);
} else if (preg_match('/[.](png)$/', strtolower($avatar["name"]))) {
$im = imagecreatefrompng("photos/".$fileName);
} else if (preg_match('/[.](jpeg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
}else{
$im = imagecreatefromjpeg("photos/".$fileName);
}
//get height and width
$ox = imagesx($im); $oy = imagesy($im);
$final_width_of_image = 200;
$final_height_of_image = 200;
//$ratio = $final_width_of_image / $ox; //find ratio to apply to height
//$nx = $final_width_of_image; $ny = $oy * $ratio;
if( $ox < $oy ){
$nx = 200;
$ny = floor($oy * (200 / $ox));
}else{
$ny = 200;
$nx = floor($ox * (200 / $oy));
}
//$nm = imagecreatetruecolor($nx, $ny);
//imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy); //create new pic
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
unlink("photos/".$fileName); //delete temp image
imagejpeg($nm, "photos/".$memberID.$extension.".jpg",100); //save image // 100 = quality
$im = imagecreatefromjpeg("photos/".$memberID.$extension.".jpg");
$nm = imagecreatetruecolor(200, 200);
imagecopyresampled($nm, $im,0,0,0,0,200,200,200,200);
imagejpeg($nm, "photos/".$memberID.$extension."Thumb.jpg",100);
$sql = "UPDATE exchange SET photo = 1 WHERE id = '$memberID'"; //update db
$mysql = new mysql();
$mysql->query($sql);
##### END PROCESS THUMBNAIL AND UPLOAD PICTURE #####
echo '<span class="pint2">'.SETTINGSphoto_chage_success.' <a style="color:#ffffff" href="'.$_ENV['rootURL'].'/'.( in_array($_GET['lang'],$_ENV['supportedLanguages']) ? $_GET['lang']."/" : $nothing).HEADlanguage_exchange.'/id/'.$memberID.'">'.SETTINGSphoto_view_profile.'</a></span>';
}
}
The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
You can solve this by telling the user she should clear the browser cache.
If that is not an option, you want to actually prevent the user to cache the image.
So you need to make a difference between each revision of the image. Add a integer field to your database you store the revision number of the image. Then each time you output the user's image, fetch the actual revision number from the database as well. Add it as the query-info-part of the image URL:
<img src="avatars/user/929292/photo.jpg?revision">
^^^^^^^^
The browser will still cache profile pictures but you make him aware of the revision, so a specific revision is cached.
Old avatar picture:
<img src="avatars/user/929292/photo.jpg?1">
Then the user uploads a new image, you increment the revision field, the new avatar image is:
<img src="avatars/user/929292/photo.jpg?2">
If the revision changes, the browser notices that and will pick the image from the server.
You could give the new image a slightly different filename, so the browser loads the new image rather than using the old cached one.
In your PHP code for the image source you can append a timestamp to force the photo to always appear as a new photo. Throw some logic in to only do this for updated records and you'll be more cache friendly.
<img src="your_profile_url.jpg?<?= time(); ?>"/>

Categories