PHP upload image different directory - php

i have a problem with uploading images into different directory.
$path = "../uploads/";
$path2 = "../uploads2/";
$imagename = $_FILES['photoimg']['name'];
$actual_image_name = $imagename;
$uploadedfile = $_FILES['photoimg']['tmp_name'];
$widthArray = array(600,240); //resize width.
foreach($widthArray as $newwidth)
{
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(move_uploaded_file($uploadedfile, $path2.$actual_image_name))
{}
i want to upload image into uploads and uploads2 folders also?
for example width width = 600px into uploads, width = 240px into folder upload2.
what's wrong with my code?

After moving the file with move_uploaded_file it isn't available in the location stored in $uploadedfile anymore. For the second file you have to use copy function.
Please try the following:
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(copy($path.$actual_image_name, $path2.$actual_image_name))
{}

Remove this line. I don't know for what purpose it's there.
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
To resize the uploaded image use any library to resize it then pass it.
But here is the full code to upload in different directory. But you will have to resize these two $file1 & $file2 to your expected resize file and replace the same in $file1 & $file2
To resize you can use any code suggested here
$path1 = "../uploads/";
$path2 = "../uploads2/";
$file1= $_FILES['photoimg'];
$file2= $_FILES['photoimg'];
$file1_imagename = $file1['name'];
$file2_imagename = $file2['name'];
$file1_actual_image_name = $file1_imagename;
$file2_actual_image_name = $file2_imagename;
$file1_uploadedfile = $file1['tmp_name'];
$file2_uploadedfile = $file2['tmp_name'];
$widthArray = array(600, 240); //resize width.
if (move_uploaded_file($file1_uploadedfile, $path1 . $file1_actual_image_name)) {
echo "Uploaded Successfully!";
}
if (move_uploaded_file($file2_uploadedfile, $path2 . $file2_actual_image_name)) {
echo "Uploaded Successfully!";
}

Related

how to prevent imagecreatefrom from creating a static gif - PHP

I have a script that sends an image it is saved as a .gif as declared in the movie.php file that will be listed below.
However, as I understand it, it creates an image from the gif making it useless for display because it simply becomes a static image .gif.
Anyway
I wanted to know how I can upload this file and ignore this function (imagecreatefromgif) I tried to change it in several ways and when I remove it I get an error, someone could help me work around this so that the gif will be sent and not be converted to a gif file static. basically I wanted that the way I sent the gif it would only be renamed with function imageGenerateName () but that it would keep all its size and property.
Every help is welcome.
Thanks in advance
.
Movie.php code:
<?php
class Movie {
public function imageGenerateName() {
return bin2hex(random_bytes(60)) . ".gif";
}
}
movie-process.php code
<?php
// Upload img
if(isset($_FILES["image"]) && !empty($_FILES["image"]["tmp_name"])) {
$image = $_FILES["image"];
$imageTypes = ["image/gif"];
$jpgArray = ["image/gif"];
// Check img type
if(in_array($image["type"], $imageTypes)) {
// Check img type
if(in_array($image["type"], $jpgArray)) {
$imageFile = imagecreatefromgif($image["tmp_name"]);
} else {
$imageFile = imagecreatefromgif($image["tmp_name"]);
}
// image name
$imageName = $movie->imageGenerateName();
imagegif($imageFile, "./img/movies/" . $imageName, 100);
$movie->image = $imageName;
}
}
// Upload img
if(isset($_FILES["image"]) && !empty($_FILES["image"]["tmp_name"])) {
$image = $_FILES["image"];
$imageTypes = ["image/gif"];
$jpgArray = ["image/gif"];
// Check img type
if(in_array($image["type"], $imageTypes)) {
// check type is gif
if(in_array($image["type"], $jpgArray)) {
$imageFile = imagecreatefromgif($image["tmp_name"]);
}
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
imagegif($imageFile, "./img/movies/" . $imageName, 100);
$movieData->image = $imageName;
}
}
Unfortunately, the imagecreatefromgif function will only read the first image of the gif as the PHP manual says.
I tried before to solve this, but there is no turnaround other than uploading the image without touching it. PHP uses the GD library and this library doesn't have the proper functionality to deal with gif images other than just saving the image with the *.gif extension.
So, this is my suggested solution:
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
move_uploaded_file($_FILES["image"]["tmp_name"],"./img/movies/" . $imageName);
$movieData->image = $imageName;
I think since you say you just want to save it as it is, with the same size and its all properties, you can use below code
<?php
$allowed = array('gif');
$filename = $_FILES["image"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $allowed)) {
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
$uploadResult = move_uploaded_file($_FILES['image']['tmp_name'], dirname( dirname( __FILE__ ) ).'/img/movies/'. $imageName );
if($uploadResult === true ){
$movie->image = $imageName;
}else{
throw new \Exception('Unable to copy file to the given path');
}
}
Or if you have access to the Imagick lib php extension refer to below link on how to install this php-extension
https://www.php.net/manual/en/imagick.setup.php
then using the functions in that library you can do
<?php
$allowed = array('gif');
$filename = $_FILES["image"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $allowed)) {
$image = new Imagick();
$image->readImage($_FILES["image"]["tmp_name"]);
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
$frame->thumbnailImage($size_w, $size_h);
$frame->setImagePage($size_w, $size_h, 0, 0);
}
$image = $image->deconstructImages();
$image->writeImages(dirname( dirname( __FILE__ ) ).'/img/movies/'. $imageName, true);
}
?>

Why $conigf['quality'] parameter not working with png file but works awesome with jpg while image upload in codeigniter?

I have been trying to use imagemagic in my codeigniter API. The problem is that below code works fine with my jpg image compression. When I upload ".jpg" image of 2MB size it successfully resizes it to perfect 80kb file on server but when I use ".png" extension the size goes down but not that much it still gives me image size of 300kb and I observed that with png format "quality" does not effect. I tried putting quality 100 and 50 but still same result of big image size for ".png".
And also that if I remove "width" and "height" config parameter than only "quality" does not affect the image file it uploads image of very big size... no image file size compression bases on "quality" parameter.
Can anyone help where I am making mistake or missing something???
My API:
public function multi_image_upload()
{
$aa = array();
if (!empty($_FILES['images'])) {
foreach ($_FILES['images']['name'] as $key => $image) {
$extFile = $_FILES['images']['name'][$key];
$ext = pathinfo($extFile, PATHINFO_EXTENSION);
$nm = date('ymdhis') . '-bingo' . rand(11111, 99999);
$filnm = $nm . ".png";
$file = APPPATH . '../upld/biz/' . $filnm;
$newname = $filnm;
$source_image = $file;
if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$this->fun->imageupload("upld/biz/", $newname, $source_image);
if (file_exists($file)) {
unlink($file);
}
}
}
$res = $this->responce(false, $aa);
} else {
$res = $this->responce(true, "Please select image");
}
echo $res;
}
IMAGE UPLOAD MODEL:
public function imageupload($url, $newname, $source_image)
{
$path = APPPATH . '../' . $url;
$imgsz = array(256,700);
foreach ($imgsz as $imxs) {
$sizefolder = $imxs . "x" . $imxs . "/";
if (!file_exists($path . $sizefolder)) {
mkdir($path . $sizefolder, 0777);
}
$size = getimagesize($source_image);
$filekb = filesize($source_image); // $config['image_library'] = 'gd2';
$config['image_library'] = 'ImageMagick';
$config['library_path'] = '/usr/bin/';
$config['overwrite'] = TRUE;
$config['source_image'] = $source_image;
$config['new_image'] = $path . $sizefolder . $newname;
$config['quality'] = 100;
if ($size[1] > $size[0]) {
$config['height'] = $imxs;
} else {
$config['width'] = $imxs;
}
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
}
JPEG is a lossy compression, meaning that you can limit the size of the output image by setting quality settings, resulting in lower quality image and also lower file size.
PNG is a lossless compression, so you cannot limit quality - it always stays the same. But you can limit compression - the effort that Imagemagick puts into making the PNG file smaller - but like with e. g. ZIP compression the output size is largely dependent on data type - and most images do not compress particularly well.
Also see Compress a PNG image with ImageMagick for some more options on limiting PNG file sizes.

cannot remove jpg using unlink function

Delete Function
function delete_news($id,$img)
{
$sql = $this->con->prepare("DELETE FROM `nm_news` WHERE news_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/".$img);
header('Location: all_news.php');
$this->con = null;
}
Here I am able to delete all image like jpeg and png but unable to delete jpg
Inserting Image function
function update_category($id, $category_title, $sort_order, $status)
{
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
}
$image = basename($_FILES["imageUpload"]["name"], ".jpg");
if ($image) {
$sql = $this->con->prepare("UPDATE nm_category SET category_title=:category_title,category_image=:category_image,category_order=:category_order,category_status=:category_status WHERE category_id=:id");
$sql->bindParam(':category_title', $category_title);
$sql->bindParam(':category_image', $image);
$sql->bindParam(':category_order', $sort_order);
$sql->bindParam(':category_status', $status);
$sql->bindParam(':id', $id);
}
}
Insertion of image is working fine, but unlink on jpg is not working only working on jpeg and png
Result o/p: after pressing delete button, the whole data gets deleted but the image still remains in the folder of uploads
Change $image = basename($_FILES["imageUpload"]["name"], ".jpg"); to $image = basename($_FILES["imageUpload"]["name"]);
This was only storing the complete filename including extension for .jpeg and .png files. When you uploaded a .jpg file you stored the file in your uploads/ folder including the extension but saving to database without the extension.
So for example myJpgFile.jpg exists in your uploads/ folder, but you were trying to unlink myJpgFile from your uploads/ folder - which doesn't exist.

how to avoid duplicate upload in php?

i used from function crop_compress() to crop and compress image and then upload them
function crop_compress($source_url,$target_file,$qual) {
$image = imagecreatefromjpeg($source_url);
$width = imagesx($image);
$height = imagesy($image);
$thumb_width = $width;
$thumb_height = (9/16)*$width;
.
.
.
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
imagejpeg($thumb , $target_file,$qual);
return $target_file;}
$filename= 'crop_compress($_FILES["fileToUpload"]["tmp_name"][$key],$target_fileL,90)'
and it work fine.
now i want to upload this image with ftp and use ftp_put:
ftp_put($connecti,$target_file, $filename, FTP_BINARY);
and it work fine too, but it upload 2 times that i dont want.
one image in my directory and one with ftp
my question is how to avoid upload in my directory?
i know that ftp_put() and crop_compress() upload separately but i dont know which one should come first and how create a tmp_file to source in another or something else to avoid this problem?!
more info:
$target_dirL = "user"; #in the main host
$tempL=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_fileL = $target_dir .$username1. '.' . end($tempL);
$target_dir = "user/$username/"; #another host
$temp=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_file = $target_dir .$username1. '.' . end($temp);
$connecti = ftp_connect($anotherHost) or die('Couldn\'t connect to ftp server');
Use unlink( $filename ); after ftp_put($connecti,$target_file, $filename, FTP_BINARY);
This will delete the file after it had been uploaded via FTP.

How to save uploaded image to file using php

I have been trying to save uploaded images to a folder using PHP. I have been stuck on this because the name of the image saves differently to the database than the folder.
Database:assets/images/profile_pics/john_doe5a153efc8731359393775e3355df0b77n.jpg
Folder: john_doe_original.5a153efc8731359393775e3355df0b77njpeg
include("includes/header2.php");
$profile_id = $user['username'];
$imgSrc = "";
$result_path = "";
$msg = "";
/***********************************************************
0 - Remove The Temp image if it exists
***********************************************************/
if (!isset($_POST['x']) && !isset($_FILES['image']['name']) ){
//Delete users temp image
$temppath = 'assets/images/profile_pics/'.$profile_id.'_temp.jpeg';
if (file_exists ($temppath)){ #unlink($temppath); }
}
if(isset($_FILES['image']['name'])){
/***********************************************************
1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/name/assets/images/profile_pics';
//Set File name
$file_temp_name = $profile_id.'_original.'.md5(time()).'n'.$type; //the temp file name
$fullpath = $uploaddir."/".$file_temp_name; // the temp file path
$file_name = $profile_id.'_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id.md5(time());
$fullpath_2 = "assets/images/profile_pics/".$finalname."n.jpg"; //for the final resized image
//Move the file to correct location
$move = move_uploaded_file($ImageTempName,$fullpath) ;
chmod($fullpath, 0777);
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc= "assets/images/profile_pics/".$file_name; // the image to display in crop area
$msg= "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
if (isset($_POST['Submit'])){
//Insert image into database
$insert_pic_query = mysqli_query($con, "UPDATE users SET profile_pic='$fullpath_2' WHERE username='$userLoggedIn'");
//header("Location: account.php");
}
Thank you for your help. Let me know how I can improve my question as well.
Use $fullpath_2 in your move_uploaded_file(). change upload directiry to $uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
if (isset($_FILES['image']['name'])) {
/***********************************************************
* 1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
//Set File name
$file_temp_name = $profile_id . '_original.' . md5(time()) . 'n' . $type; //the temp file name
$fullpath = $uploaddir . "/" . $file_temp_name; // the temp file path
$file_name = $profile_id . '_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id . md5(time());
$fullpath_2 = "assets/images/profile_pics/" . $finalname . "n.jpg"; //for the final resized image
//Move the file to correct location
if (move_uploaded_file($ImageTempName, $uploaddir . $fullpath_2)) {
chmod($uploaddir . $fullpath_2, 0777);
}
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc = "assets/images/profile_pics/" . $file_name; // the image to display in crop area
$msg = "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
Personally I have used imagecreatefromjpeg
http://php.net/manual/en/function.imagecreatefromjpeg.php
Passed the temp uploaded file directly to this function.
Then this allows me to use imagescale for profile pic sizing.
http://php.net/manual/en/function.imagescale.php
Finally I find file-put-contents is a rather clean way to save the content.
http://php.net/manual/en/function.file-put-contents.php

Categories