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 ;
Related
I have a code:
<?php
$size = 2000000;
$types = array('image/png', 'image/jpeg');
if(isset($_POST['go'])){
$newName = $id . '.' . $type;
$directory = 'img/avatars/'; //path to folder with images
$picture = $directory . basename($newName);
if (!in_array($_FILES['picture']['type'], $types)) {
die('Wrong type of file. Try another');
} elseif ($_FILES['picture']['size'] > $size) {
die('File is too big. Try another');
} elseif (move_uploaded_file($_FILES['picture']['tmp_name'], $picture)) {
echo "Image was downloaded!";
}
$new_width = 66; //necessary width
$size = getimagesize($picture);
$width = $size[0];
$height = $size[1];
if ($type == 'png') {
$src=ImageCreateFromPng($picture);
}
if ($type == 'jpeg' || $type == 'jpg') {
$src=ImageCreateFromJPEG($picture);
}
$coefficient = $width/$new_width;
$new_height = ceil($height/$coefficient);
$empty_picture = ImageCreateTrueColor($new_width, $new_height);
ImageCopyResampled($empty_picture, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if ($type == 'png') {
ImagePNG($empty_picture, $picture, -1);
}
if ($type == 'jpeg') {
ImageJPEG($empty_picture, $picture, -1);
}
imagedestroy($src);
}
?>
It returns an error:
imagecreatefrompng(): 'img/avatars/6.png' is not a valid PNG file in
W:\domains\mysite\settings.php
I checked is it png image:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $picture); // image/png
finfo_close($finfo);
And it returns me: image/png (it is).
So I do not know what is wrong with this code. Would be grateful for any help!
I use this function for resize and upload image.
code:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function createThumbnail($widthbig,$widththumb,$image_directory,$image_directory_thumb,$newfilename,$newfilenamethumb,$source) {
define ("MAX_SIZE","5000");
$errors=0;
//$image =$_FILES["post_images"]["name"];
//$uploadedfile = $_FILES['file']['tmp_name'];
if ($newfilename)
{
$file = stripslashes($newfilename);
$extension = $this->getExtension($file);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size= filesize($source);
if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
//$source = $source;
$src = imagecreatefromjpeg($source);
}
else if($extension=="png")
{
//$uploadedfile = $source;
$src = imagecreatefrompng($source);
}
else
{
$src = imagecreatefromgif($source);
}
list($width,$height)=getimagesize($source);
$newwidth=$widthbig;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=$widththumb;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$dirfile = $image_directory. $newfilename;
$dirfile1 = $image_directory_thumb. $newfilenamethumb;
if($extension=="jpg" || $extension=="jpeg" )
{
$upload = imagejpeg($tmp,$dirfile,100);
$upload1 = imagejpeg($tmp1,$dirfile1,100);
}
else if($extension=="png")
{
$upload = imagepng($tmp,$dirfile,100);
$upload1 = imagepng($tmp1,$dirfile1,100);
}
else if($extension=="gif")
{
$upload = imagegif($tmp,$dirfile,100);
$upload1 = imagegif($tmp1,$dirfile1,100);
}
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
before, this function work in php 5.x but when in 7 this not work and give return null after i var_dump the imagejpg("xx","xx","xx"); end the result is false.
I have try to search in google but not get the same problem.
whats wrong whit this code, and how to fix this?
thanks
I was fix this : can't upload because permission denied in target folder
change to
chmod -r 0757 target_dir
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.
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);
?>
If possible please i'd ask a favor, i've been trying to change this it but i haven't succeeded, i wanted to change it in my php file, but no result!
now this script below is a resize script, but it renames my file... i don't need it to do so, can you please see it and tell me how to remove the renaming of the file?
I know it has something to do with : $image->createFile(md5($tempFile)); i tried removing the md5 and still nothing...
Thanks!
function setFile($src = null) {
$this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
if(is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
$this->img_r = ImageCreateFromJPEG($src);
} elseif(is_file($src) && $this->ext == "PNG") {
$this->img_r = ImageCreateFromPNG($src);
} elseif(is_file($src) && $this->ext == "GIF") {
$this->img_r = ImageCreateFromGIF($src);
}
$this->img_w = imagesx($this->img_r);
$this->img_h = imagesy($this->img_r);
}
function resize($largestSide = 100) {
$width = imagesx($this->img_r);
$height = imagesy($this->img_r);
$newWidth = 0;
$newHeight = 0;
if($width > $height){
$newWidth = $largestSide;
$newHeight = $height * ($newWidth / $width);
}else{
$newHeight = $largestSide;
$newWidth = $width * ($newHeight / $height);
}
$this->dst_r = ImageCreateTrueColor($newWidth, $newHeight);
imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$this->img_r = $this->dst_r;
$this->img_h = $newHeight;
$this->img_w = $newWidth;
}
function createFile($output_filename = null) {
if($this->ext == "JPG" OR $this->ext == "JPEG") {
imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
} elseif($this->ext == "PNG") {
imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
} elseif($this->ext == "GIF") {
imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
}
$this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
}
function setUploadDir($dirname) {
$this->uploaddir = $dirname;
}
function flush() {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
imagedestroy($this->dst_r);
unlink($targetFile);
imagedestroy($this->img_r);
}
}
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file ($tempFile, $targetFile);
$image = new Image();
$image->setFile($targetFile);
$image->setUploadDir($targetPath);
$image->resize(800);
$image->createFile(md5($tempFile));
try changing to
$image->createFile('resized_'.$_FILES['Filedata']['name']);
function createFile($output_filename = null) {
if($this->ext == "JPG" OR $this->ext == "JPEG") {
imageJPEG($this->dst_r, $this->uploaddir.$output_filename, $this->quality);
} elseif($this->ext == "PNG") {
imagePNG($this->dst_r, $this->uploaddir.$output_filename);
} elseif($this->ext == "GIF") {
imageGIF($this->dst_r, $this->uploaddir.$output_filename);
}
$this->output = $this->uploaddir.$output_filename;
}
You confuse the file's actual name ($_FILES['Filedata']['name']) with the temporary name ($_FILES['Filedata']['tmp_name']). The first is the file the client uploaded. The second is a temporary file that the server created one the server's machine. So you have to use the actual, client-side name here.
This will make your day
$image->createFile(preg_replace("/\.[^\.]*$/", "", $targetFile));