PHP $_FILES same image name - php

I am trying to upload multiple images to php server, But for some reason it is using first image name for all the uploaded images, saving to same image name. I want it to save to their filename in the source folder. Like Banner1.jpg,Banner2.jpg and Banner3.jpg should be saved. But it is saving first image thrice.
$filesCount = count($_FILES['photos']['name']);
$success = 0;
for($i = 0; $i < $filesCount; $i++)
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
if($uploadedfile)
{
$filename = stripcslashes($_FILES['photos']['name'][$i]);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div>';
}
else
{
$size = filesize($_FILES['photos']['tmp_name'][$i]);
}
if($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1024;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=300;
$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);
$filenameee = "server/php/rental/". $_FILES['photos']['name'][$i];
$filenameee1 = "server/php/rental/small/". $_FILES['photos']['name'][$i];
imagejpeg($tmp,$filenameee,100);
imagejpeg($tmp1,$filenameee1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
if(mysql_query("INSERT INTO fc_rental_photos(product_image,product_id) VALUES('$filename','$prd_id')"))
{
$success++;
}
}
Here is the input field i am using to upload images.
<form id="imageform" method="post" enctype="multipart/form-data" action="/path-to-controller-method/">
<input type="file" name="photos[]" id="photoimg" multiple onchange="imageval();">
</form>
IMageVal
function imageval(){ /*Image size validation*/
var fi = document.getElementById('photoimg');
if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.
for (var i = 0; i <= fi.files.length - 1; i++) {
var fileName, fileExtension, fileSize, fileType, dateModified;
fileName = fi.files.item(i).name;
fileExtension = fileName.replace(/^.*\./, '');
if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fi.files.item(i));
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (width < 1450 || height < 500) {
alert("Image Height and Width should be Above 1450 * 500 px.");
return false;
}
<?php if($aws == 'Yes') echo "uploadImage_aws();";else echo "uploadImage();";?>
};
}
}
else
{
alert("Photo only allows file types of PNG, JPG, JPEG. ");
}
}
}
}
UploadImage
function uploadImage()
{
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
}
}).submit();
}

You have to check if the data already exists, and if not to rename it.
if(file_exists($new_path)) {
$id = 1;
do {
$new_path = $upload_folder.$filename.'_'.$id.'.'.$extension;
$id++;
} while(file_exists($new_path));
}
For example
$new_path = $upload_folder.$filename.'.'.$extension;

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();
}

can't upload image using imagejpg

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

Cannot upload images -- Request Entity Too Large The requested resource

In my situation, I have images upload form with resize method but it failed. I have below code but does not know why where is the problem. Do you have any ideas? I am using PHP of codeingiter. Below is the error that shown. I have hosted the web site on goDaddy.
Request Entity Too Large The requested resource
/index.php/newPost/createNewPost/2/Raymond Chiu/ does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
//----font end php html code with javascript------------//
<input id="image1" name="image1" class="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-tw" onclick="setup(); return false;">Submit</button>
<script>
$("#image1").fileinput({
'showPreview' : true,
'allowedFileExtensions' : ['jpg', 'png','gif'],
'showUpload' : false,
'maxFileCount':1,
'maxFileSize': 800000,
});
$('#image1').on('fileclear', function(event) {
img1 = null;
});
$('#image1').on('fileloaded', function(event, file, previewId, index, reader) {
img1 = file;
$("#uploadImgError").html('');
});
function getResizeImage(pic, callback)
{
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
// Create an image
//-----------------------------Image-------------------------
var img = document.createElement("img");
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//document.getElementById('image').src = dataurl;
callback(dataurl);
}
reader.readAsDataURL(pic);
}
function isEmptyUploadFile(callback)
{
if(img1 == null && img2 == null && img3 == null && img4 == null && img5 == null)
callback(true);
else
callback(false);
}
function setForm(callback)
{
setImg1(function(data1)
{
if(data1 == true)
{
$('.progress-bar').css('width', 100+'%').attr('aria-valuenow', 100);
callback(true);
}
});
}
function setImg1(callback)
{
if(img1 != null)
{
getResizeImage(img1,function(tempPic)
{
document.getElementById('img1').value = tempPic;
getResizeThumbnailImage(img1,function(tempTPic)
{
document.getElementById('timg1').value = tempTPic;
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
});
});
}else{
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
}
}
function setup()
{
var myform = document.getElementById("newPost");
//console.log(myform.checkValidity());
if(!myform.checkValidity())
{
document.getElementById("validate").click();
return false;
}
isEmptyUploadFile(function(r)
{
var up1 = document.getElementById('image1').value;
var up2 = document.getElementById('image2').value;
var up3 = document.getElementById('image3').value;
var up4 = document.getElementById('image4').value;
var up5 = document.getElementById('image5').value;
if(r == true || (up1 == "" && up2 == "" && up3 == "" && up4 == "" && up5 == "") )
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
//var loc = document.getElementById('uploadImgError'); //Getting Y of target element
//window.scrollTo(0, loc);
location.href = "#uploadImgError"; //Go to the target element.
return false;
}
else if(r == false)
{
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
console.log(data);
if(data == true)
{
document.getElementById("newPost").submit();
}
return data;
});
}
});
}
</script>
// ------- controller ---------------------------//
$image1 = $this->input->post('img1');
$timage1 = $this->input->post('timg1');
$imgPath = '';
$timgPath = '';
$date=date_create();
if (isset($image1)) {
$currentTimeStamp = date_timestamp_get($date);
$imgPath = $upload_dir . '/['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($image1, false, $imgPath);
}
if (isset($timage1)) {
$currentTimeStamp = date_timestamp_get($date);
$timgPath = $upload_dir . '/[T]['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($timage1, true, $timgPath);
}
function uploadImg($input, $isThumbnail, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,'.base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
$maxFilesAllowed = 10;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
return true;
}
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
// this code said null value.
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
//-------------------end --------//
You have to configure your server to accept Large Files.
Also you're using GET.Use Post instead.
See So why should we use POST instead of GET
I may find out the reasons. After I am using native session in PHP from codeigniter session, I find that when I upload small images which will corrupt and cannot see picture. The image file that uploaded after resize in client side with above code.
Should it be reason??

How do I easily resize and rename images on upload? (php)

What code would I use to:
Resize all images being uploaded to 600px width while maintaining aspect ratio for height
Rename the file being uploaded to the current time-stamp
and how exactly would I add that to or edit my existing code (preferably without using classes):
$target_dir2 = "creature_pics/";
$target_file2 = $target_dir2 . basename($_FILES["u_c2pic"]["name"]);
$uploadOk2 = 1;
$imageFileType2 = pathinfo($target_file2,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check2 = getimagesize($_FILES["u_c2pic"]["tmp_name"]);
if($check2 !== false) {
$uploadOk2 = 1;
} else {
$uploadOk2 = 0;
}
}
if (file_exists($target_file2)) {
$uploadOk2 = 0;
}
if ($_FILES["u_c2pic"]["size"] > 5000000) {
$uploadOk2 = 0;
}
if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg"
&& $imageFileType2 != "gif" ) {
$uploadOk2 = 0;
}
if ($uploadOk2 == 0) {
$ercode2 = "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["u_c2pic"]["tmp_name"], $target_file2)) {
} else {
$ercode2 = "Sorry, there was an error uploading your file.";
}
}
I'm new to php coding and would like the simplest solution possible.
If you can use Imagick on your server then the following code should help you out.
First the function to do the resizing.
if(!defined('APPLICATION_PATH')) define('APPLICATION_PATH', dirname(__FILE__));
function popupImage($width, $height, $code, $name) {
$file = APPLICATION_PATH.'/creature_pics/'.$name.'.jpg';
$im = new Imagick($file);
$imageprops = $im->getImageGeometry();
$r_width = $imageprops['width'];
$r_height = $imageprops['height'];
if($width > $height){
$newHeight = $height;
$newWidth = ($width / $r_height) * $r_width;
}else{
$newWidth = $width;
$newHeight = ($height / $r_width) * $r_height;
}
$im->resizeImage($newWidth,$newHeight, imagick::FILTER_LANCZOS, 0.9, true);
$im->cropImage ($width,$height,0,0);
$im->writeImage(APPLICATION_PATH.'/creature_pics/'.$code.'.jpg');
$im->destroy();
$newFile = APPLICATION_PATH.'/creature_pics/'.$code.'.jpg';
}
then in your code just add
if (move_uploaded_file($_FILES["u_c2pic"]["tmp_name"], $target_file2)) {
//This is the new line calling the function
$timestamp = microtime(true);
$newFile = popupImage(600,1200,$timestamp,$_FILES["u_c2pic"]["tmp_name"]);
} else {
$ercode2 = "Sorry, there was an error uploading your file.";
}
That should create a new file in /creature_pics/ which will be named something like 142023023.9777.jpg which is the timestamp passed into the function as the code.
EDIT
Missed the timestamp element so this is now added in

how can I add imaging handling got this script effectively

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Categories