Upload image with resize in php - php

I have a problem with image uploading in php
I want uploading with resizing image to width=600px
ex, when I uploaded an image with width of 2000px it should be uploaded with width of 600px
and of course smaller size on disk...
php file is:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>
the result is a big image without resizing
can you help?

try this:
function upload_resize($file,$newwidth,$resolution,$location,$prefix){
define ("MAX_SIZE","2048");
error_reporting(0);
$image =$file["name"];
$uploadedfile = $file['tmp_name'];
if ($image) {
$filename = stripslashes($file['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//Unknown Image extension
return 1;
}
else
{
$size=filesize($file['tmp_name']);
if ($size > MAX_SIZE*1024){
//You have exceeded the size limit
return 2;
}
if($extension=="jpg" || $extension=="jpeg" ) {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png") {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $location.$prefix.$file['name'];
imagejpeg($tmp,$filename,$resolution);
imagedestroy($src);
imagedestroy($tmp);
}
}
return 0;
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// get file from user and send to this function:
$res=upload_resize($_FILES["image"],600,100,'../images','');
switch ($res){
case 0 : echo 'images saved'; break;
case 1 : echo 'Unknown file type'; break;
case 2 : echo 'file size error'; break;
}
i use this function for upload and resize image.

// for outputting a jpeg image, Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($tmp,$uploadedfile,75);
try this..

You create a new pattern file (using imagecreatetruecolor), but u didn't use a original picture.
Try use imagecopyresampled
like this:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$buff = imagecreatefromjpeg($uploadedfile);
imagecopyresampled($tmp, $b, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>

Related

Php multiple image upload processing error

In the form and process file below I am trying to upload 3 sizes of multiple images upload and it is uploading 3 size perfectly fine.
But it is uploading the same image on all sizes of the last image selected.
UPDATE
What i have observed that something has to be played with $src i tried below and when i do this images saved black. $src does not accept [$Kv]
foreach($_FILES['file']['tmp_name'] as $src[$Kv]) {
if($extension[$Kv]=="jpg" || $extension[$Kv]=="jpeg" ){
$uploadedfile[$Kv] = $_FILES['file']['tmp_name'][$Kv];
$src[$Kv] = imagecreatefromjpeg($uploadedfile[$Kv]);
}
list($width,$height)=getimagesize($uploadedfile[$Kv]);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp[$Kv]=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp[$Kv],$src[$Kv],0,0,0,0,$newwidth,$newheight,$width,$height);
}
.
Suppose I selected 3 images to upload.
Image A
Image B
Image C
It is converting and uploading all sizes of all images (3x3) but image shows on all sizes of all images selected is the image of Image C.
Can you please help on this issue that where I am wrong?
Thanks.
form.php
<form action="process.php" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-9 col-sm-12" id="thumb-output">
<div class="m-dropzone dropzone m-dropzone--primary" id="m-dropzone-two">
<h3 class="m-dropzone__msg-title">
Drop files here or click to upload.
</h3>
<input id="files" class="" type="file" name="file[]" multiple>
</div>
</div>
</form>
process.php
$change="";
$abc="";
if(count($_FILES['file']['name']) > 0){
$Kv = 0;
define ("MAX_SIZE","12000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
$image =$_FILES["file"]["name"][$Kv];
if ($image) {
foreach($_FILES['file']['name'] as $filename) {
$filename = stripslashes($_FILES['file']['name'][$Kv]);
$extension = getExtension($filename);
$extension = strtolower($extension);
}
foreach($_FILES['file']['size'] as $size) {
$size=filesize($_FILES['file']['tmp_name'][$Kv]);
}
if ($size > MAX_SIZE*1024){
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'][$Kv];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$Kv];
$src = imagecreatefrompng($uploadedfile);
}else {
$src = imagecreatefromgif($uploadedfile);
}
//echo $scr;
list($width,$height)=getimagesize($uploadedfile);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
////// 2nd Size of Image
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
////// 3rd Size of Image
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
/////////////////////////////////////////////////////
foreach($_FILES['file']['name'] as $name) {
$name = $_FILES["file"]["name"][$Kv];
$ext = end((explode(".", $name))); # extra () to prevent notice
}
$folderPath = "../images/combo2_images";
if (file_exists($folderPath)){
}else{
mkdir("$folderPath");
}
//mkdir($folderPath);
if ($execute == true) {
if ($type == 'm') {
foreach($_FILES['file']['name'] as $filenames) {
$filenames = "../images/combo2_mimages/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmps,$filenames,100);
}
//$savefilenames = 'sc1_'.$id.'.'.$ext;
foreach($_FILES['file']['name'] as $filenamesz) {
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmpsz,$filenamesz,100);
}
//$savefilenamesz = 'sc1_'.$id.'.'.$ext;
}
$filename = "../images/combo2_images/".$idz.'.'.$ext;
imagejpeg($tmp,$filename,100);
$savefilename = $idz.'.'.$ext;
if ($_FILES['file']['size'] !== 0 && $_FILES['file']['error'] == 0) {
if ($type == 'm') {
$querys = "insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes = $dba->query($querys);
}
$queryu = "update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu = $dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp); ////// 1st Size of Image
imagedestroy($tmps); ////// 2nd Size of Image
imagedestroy($tmpsz); ////// 3rd Size of Image
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}
}
Finally i got i working as i want.
if(count($_FILES['file']['name']) > 0){
define ("MAX_SIZE","12000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
$i=1; // auto increment number
$uploaddir = "../images/combo2_images"; //a directory inside
foreach ($_FILES['file']['name'] as $name => $value) {
$filename = stripslashes($_FILES['file']['name'][$name]);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
echo "\n This is the extension: ",$extension;
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//print error message
?>
<h4>Unknown extension!</h4>
<?php
$errors=1;
} else {
$size=filesize($_FILES['file']['tmp_name'][$name]);
if ($size > MAX_SIZE*1024) {
?>
<h4>You have exceeded the size limit!</h4>
<?php
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" && $extension!=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="jpg" || $extension=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension!=="jpg" || $extension!=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefrompng($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
//$image_name=($i++).$filename.'.'.$extension;
//$newname="files/".$image_name;
//$copied = copy($_FILES['file']['tmp_name'][$name], $newname);
if ($execute == true) {
if ($type == 'm') {
$filenames = "../images/combo2_mimages/m".$idz.'.'.$extension;
//imagejpeg($tmps,$filenames,100);
$copied1 = copy(imagejpeg($tmps,$filenames,100));
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.($i++).'.'.$extension;
//imagejpeg($tmpsz,$filenamesz,100);
$copied2 = copy(imagejpeg($tmpsz,$filenamesz,100));
}
$filename = "../images/combo2_images/".$idz.'.'.$extension;
imagejpeg($tmp,$filename,100);
$savefilename=$idz.'.'.$extension;
if ($type == 'm') {
$querys="insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes=$dba->query($querys);
}
$queryu="update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu=$dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmps);
imagedestroy($tmpsz);
}
if (!$copied) {
?>
<h4>Copy unsuccessfull!</h4>
<?php
$errors=1;
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}

not able to insert image height and image width in database using codeigniter

This is my controller code:
if ($files != '0') {
//echo "1";
if (isset($is_anonymous)) {
$is_anonymous = $is_anonymous;
} else {
$is_anonymous = "0";
}
$file_ary = $this->Jayesh($_FILES['files']);
$post_Id = $this->post_m->add_new_post($is_anonymous, $college_id, $writepost, $post, $article, $askq, $user_id, curr_date(), $v_id, $art_title, $art_image, $art_domain, $art_url, $article);
foreach ($file_ary as $file) {
$srt = explode('.', $file['name']);
$ext = $this->getExtension($file['name']);
$fiel_name = uniqid() . date("YmdHis") . "." . $ext;
$mime = $file['type'];
if (strstr($mime, "video/") || strstr($mime, "application/")) {
$filetype = "video";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/video/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "audio/")) {
$filetype = "audio";
}
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
if (!empty($user_id)) {
$user = $this->post_m->check_user_exist_timeline($user_id);
if (!empty($user)) {
if ($filetype == 'video') {
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/video/" . $fiel_name);
$image_width = '0';
$image_height = '0';
$video_width = '300';
$video_height = '160';
}
if ($filetype == 'image') {
//echo "https://d2c8oti4is0ms3.cloudfront.net/images/healthwall_media/image/".$fiel_name;
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];
$video_width = '300';
$video_height = '160';
}
//exit();
/* $last_user_id = $this->post_m->insert_image_post_into_media($fiel_name, $filetype,curr_date());
if (!empty($last_user_id))
{ */
$result = $this->post_m->insert_image_post_into_post_media($post_Id, curr_date(), $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype);
//}
}
}
}
}
Model code:
public function insert_image_post_into_post_media($post_Id, $cdate, $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype) {
$sql = "INSERT INTO college_post_media( `post_id`,`type`, `source`, `img_height`, `img_width`, `video_height`, `video_width`, `created_at`, `updated_at`, `deleted_at`)
VALUES ('$post_Id','$filetype','$fiel_name','$image_height', '$image_width','$video_height', '$video_width', '$cdate','$cdate','$cdate')";
return $result = $this->db->query($sql);
}
I'm facing an issue when inserting img_height and img_width in to the table. It is going in empty.
Try getting the image size while it is still on your domain:
Excerpt:
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
list($image_width, $image_height) = getimagesize($file['tmp_name']);
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
}
Assuming that $file['tmp_name'] is a fully qualified path.
Then you can remove:
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];

Directory being deleted randomly by unknown script

I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}

Resize image when uploaded

What is wrong with my code I need to resize image when upload in variable $new_width and $new_height is dimension for image. I think it's problem in $newname variable because it is working before when I added :D
<meta charset="utf-8" />
<?php
include 'config.php';
mysqli_set_charset($db, 'utf8');
$id = $_COOKIE["id"];
if (isset($_POST["action"])){
$newname = substr(md5(rand() * time()), 5,10);
$folder = "image/";
$folder2 = "image/thumb/";
$filetmp = $_FILES["filep"]["tmp_name"];
$filename = $_FILES["filep"]["name"];
$filetype = $_FILES["filep"]["type"];
$filesize = $_FILES["filep"]["size"];
$fileinfo = getimagesize($_FILES["filep"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "$folder".$newname.$filename;
$filepath_thumb = "$folder".$filename;
if($filetmp == ""){
echo "Upload image";
}
else {
if($filesize > 2097152){
echo "Less then 2 mb";
}
else{
if($filetype != "image/jpeg" && $filetype != "image/png"
&& $filetype != "image/gif" && $filetype != "image/jpg"){
echo ".jpeg, .jpg, .gif, .png";
}
else{
move_uploaded_file($filetmp,$filepath);
if($filetype == "image/jpeg"){
$imagecreate = "imagecreatefromjpeg";
$imageformat = "imagejpeg";
}
if($filetype == "image/png"){
$imagecreate = "imagecreatefrompng";
$imageformat = "imagepng";
}
if($filetype == "image/gif"){
$imagecreate= "imagecreatefromgif";
$imageformat = "imagegif";
}
if($filetype == "image/jpg"){
$imagecreate= "imagecreatefromjpg";
$imageformat = "imagejpg";
}
$new_width = "200";
$new_height = "150";
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $filewidth, $fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
$res = mysqli_query($db, "UPDATE Imager SET Cover='".$newname.$filename."' WHERE IDImg ='$id'");
if($res) {
echo "Good.";
}
else {
echo "Not Good.";
}
}
}
}
}
header( "Refresh:2; url=img.php", true, 303);
?>
I would suggest you use a library like Imagine - it will make this process much simpler.

How can i upload file with rename?

I have a file uploading code. everything is ok but i want to rename the file when it up loaded. my code is here. i need only the rename function and where it should be put. this code is very long because there crop the big image to small.
example: if file is 10MB it will be 40 or 50 KB
error_reporting(0);
$change = "";
$abc = "";
define("MAX_SIZE", "400");
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) {
return "";
} $l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$errors = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$image = $_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image) {
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$change = '<div class="msgdiv">Unknown Image extension</div>';
$errors = 1;
} else {
$size = filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE * 1024) {
$change = '<div class="msgdiv">You have exceeded the size limit!</div>';
$errors = 1;
} if ($extension == "jpg" || $extension == "jpeg") {
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
} else if ($extension == "png") {
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
} echo $scr;
list($width, $height) = getimagesize($uploadedfile);
$newwidth = 280;
$newheight = ($height / $width) * $newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename = "../adimages/" . $_FILES['file']['name'];
imagejpeg($tmp, $filename, 100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
Just use the name you want instead of $_FILES['file']['name']
For example:
$filename = "../adimages/". time();
This will name each uploaded file with the current timestamp.
change Your below line
$filename = "../adimages/" . $_FILES['file']['name'];
with the below:-
$new_name = "new_file_name".time();
$filename = "../adimages/" . $new_name;
time() is added for uniqueness. and at the place of new_file_name , You can also put $_FILES['file']['name'];
try this --
just replace your line
$filename = "../adimages/" . $_FILES['file']['name'];
with this new line
$filename = "../adimages/" .time().'.'.$extension ;

Categories