500 Error from PHP upload script [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
So I've been banging my head against my desk for about a couple of days now trying to figure out is causing this 500 Error. every time I try and post a file image its throws me a error : POST http://example.com/server/uploadProfile.php 500 (Internal Server Error)
Not to sure exactly what it means and how to go about and fixing it.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
function image_upload($max_size,$input_file,$path,$new_width) {
if(!define("MAX_SIZE",$max_size)) {
define("MAX_SIZE",$max_size);
}
$errors = 0;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$img = $_FILES[$input_file]['name'];
$tmp_file = $_FILES[$input_file]['tmp_name'];
}
if($img) {
$file_name = stripcslashes($_FILES[$input_file]['name']);
$extension = getExtension($file_name);
$extension = strtolower($extension);
if($extension != 'jpg' && $extension != 'jpeg' && $extension != 'png' && $extension != 'gif') {
//echo "Unknown image type.";
$errors = 1;
return "Wrong file type.";
}
else {
$size = filesize($_FILES[$input_file]['tmp_name']);
if($size > MAX_SIZE*1024) {
$error = 1;
return "File size too big";
//echo "You have exceeded the size limit";
}
if($extension == 'jpg' || $extension == 'jpeg') {
$uploadedfile = $_FILES[$input_file]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension == 'png') {
$uploadedfile = $_FILES[$input_file]['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else if($extension == 'gif') {
$uploadedfile = $_FILES[$input_file]['tmp_name'];
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newheight = ($height/$width)*$new_width;
$tmp = imagecreatetruecolor($new_width,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$new_width,$newheight,$width,$height);
$rnd = rand(0,9999999999999999999999);
$file_name = $rnd.'_'.$_FILES[$input_file]['name'];
$upload_path = $path .$rnd.'_'.$_FILES[$input_file]['name']
switch($_FILES[$input_file]['type']) {
case 'image/jpeg':
imagejpeg($tmp, $upload_path, 100);
break;
case 'image/jpg' :
imagejpeg($tmp, $upload_path, 100);
break;
case 'image/png':
imagepng($tmp, $upload_path, 0);
break;
case 'image/gif' :
imagegif($tmp, $upload_path);
break;
}
}
}
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
if(isset($_FILES['profilePhoto']['tmp_name'])) {
image_upload("320000","profilePhoto","/profile",250);
}
?>

$upload_path = $path .$rnd.'_'.$_FILES[$input_file]['name']
You are missing a ; at the end of the line. Syntax errors that make the script uncompilable will result in a server error 500

Related

Error while creating thumbnail in php for multiple image upload

I use following code to upload, rename, compress, create thumbnail everything works fine, And recently i noticed while creating thumb it creates fresh copy of thumb images for previously uploaded images also(create thumbnail for uploaded and uploading images too)
Problem:
When form is submitted it crates thumb for uploading image and uploaded images(image file that are present in older).
how do i solve this problem
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if
(move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['tmp_name'][$key], 0);
}
} else {
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key + 1) . ' = $row[0];';
eval($codestr);
} else {
$codestr = '$file' . ($key + 1) . ' = NULL;';
eval($codestr);
}
}
}
$orig_directory = "$desired_dir";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$dir_handle = opendir($orig_directory);
if ($dir_handle > 1) {
$allowed_types = array('jpg', 'jpeg', 'gif', 'png');
$file_type = array();
$ext = '';
$title = '';
$i = 0;
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..') {
continue;
}
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
if (in_array($ext, $allowed_types)) {
$nw = 125;
$nh = 90;
$source = "$desired_dir{$file_name}";
$stype1 = explode(".", $source);
$stype = $stype1[count($stype1) - 1];
$dest = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/" . $file_name, 50);
}
}closedir($dir_handle);
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file1, PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file2, PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file3, PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file4, PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: /post/price_plan.php');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
Bounty Edit
if there is any good and faster function to do please.
all i need is to upload, rename, compress, create thumbnail and save name to DB
The code is need much more optimization. you are iterating the file folder again every time instead of looping the just uploaded files.
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$file = [];
$nw = 125;
$nh = 90;
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
$file_name_with_ext = $file_name . $sExt;
$source = = $desired_dir . $file_name_with_ext ;
if(!move_uploaded_file($file_tmp, $source)) {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$file[] = NULL;
}else{
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($sExt) {
case '.gif':
$simg = imagecreatefromgif($source);
break;
case '.jpg':
$simg = imagecreatefromjpeg($source);
break;
case '.png':
$simg = imagecreatefrompng($source);
break;
}
$dest = $thumb_directory. $file_name_with_ext ;
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
// imagewebp($dimg, $dest);
compress($source, "$desired_dir" . $file_name_with_ext , 50);
compress($dest, $dest , 50);
$file[] = $file_name_with_ext ;
}
}else{
// TODO: error handling
}
}
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file[0], PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file[1], PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file[2], PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file[3], PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: https://google.com');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
?>
As part of your question you asked if there was "any good and faster function to do please."
https://github.com/delboy1978uk/image
Try this! (install via Composer or just require each of the classes in if you just drop the code in yourself)
<?php
use Del\Image;
$image = new Image('/path/to/your.jpg'); //or gif , etc
// Or...
$image = new Image();
$image->load('/path/to/my.png');
You'll then have all of these commands at your disposal:
$image->crop($width, $height, 'center'); // Crops the image, also accepts left or right as 3rd arg
$image->destroy(); // remove loaded image in the class. Frees up any memory
$image->getHeader(); // returns image/jpeg or equivalent
$image->getHeight(); // returns height in pixels
$image->getWidth(); // returns width in pixels
$image->output(); // output to browser
$image->output(true); // passing true returns raw image data string
$image->resize($width, $height); // resize to the given dimensions
$image->resizeAndCrop($width, $height); // resize to the given dimensions, cropping top/bottom or sides
$image->save(); // Save the image
$image->save('/path/to/save.jpg', $permissions, $compression); // Save as a different image
$image->scale(50); // Scale image to a percentage
Loop through your POSTed uploads, load them up, save the original, resize the image, and save the thumbnail. Existing images shouldn't be touched.
There are plenty bad php-programming-habits in that code (e.g. use of eval and general data-flow).
To break it down: The script first validates the uploaded files and moves them to a temp directory. Then it calculates thumbnails for all files in the temp directory.
To change that we use an array which contains the filenames of uploading images.
// ...
$file_type = array();
$ext = '';
$title = '';
$i = 0;
// First change:
$validFileNames = array_column($uploadedFiles, 0);
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..' || !in_array($file_name, $validFileNames)) {
continue;
}
// Nothing changed beyond this point
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
// ...
}
array_column($uploadedFiles, 0) reads the index 0 of every entry in $uploadedFiles, which contains the filename. So $validFileNames contains only filenames of uploading images.
We then check for every file in the temp-directory if its name is included in $uploadedFiles. If not then it was not uploading and can be ignored.
As for the request of a more general optimization:
<?php
$desired_dir = $_SERVER['DOCUMENT_ROOT'].'/upload/file/';
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $uploadedFileName) {
$errors = array();
$destFilename = md5(uniqid('uploads', true).time());
$uploadedSize = $_FILES['files']['size'][$key];
$uploadedTmpName = $uploadedFileName;
$uploadedType = $_FILES['files']['type'][$key];
$sExt = null;
if ($uploadedType == 'image/gif') {
$sExt = '.gif';
} elseif ($uploadedType == 'image/jpeg' || $uploadedType == 'image/pjpeg') {
$sExt = '.jpg';
} elseif ($uploadedType == 'image/png' || $uploadedType == 'image/x-png') {
$sExt = '.png';
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = 'Image types alowed are (.gif, .jpg, .png) only!';
}
if ($uploadedSize > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (!empty($errors)) {
// Todo: Error handling of $errors
continue;
}
if (is_dir($desired_dir) == false) {
mkdir($desired_dir, 0700);
}
$destFilePath = "$desired_dir/".$destFilename.$sExt;
if (!move_uploaded_file($uploadedTmpName, $destFilePath)) {
echo "Couldn't upload file ".$uploadedTmpName;
}
$nw = 125;
$nh = 90;
$source = $destFilePath;
$stype1 = explode('.', $source);
$stype = $stype1[count($stype1) - 1];
$dest = $_SERVER['DOCUMENT_ROOT'].'/upload/thumb/'.$destFilename.$sExt;
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/".$file_name, 50);
$uploadedFiles[] = $destFilePath;
}
$stmt = $conn->prepare('INSERT INTO allpostdata(im1, im2, im3, im4)'
.' VALUES (?, ?, ?, ?)');
if ($stmt->execute($uploadedFiles)) {
header('Location: /post/price_plan.php');
}
}
exit;
}

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

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 ;

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