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();
}
Related
I have compressed images and now i want to resize them before move to temp files.
$query=mysqli_query($con,"select max(id) as pid from products");
$result=mysqli_fetch_array($query);
$productid=$result['pid']+1;
$dir="images/productimages/$productid";
if(!is_dir($dir)){
mkdir("images/productimages/".$productid);
}
$file_name = $_FILES["productimage1"]["name"];
$file_type = $_FILES["productimage1"]["type"];
$temp_name = $_FILES["productimage1"]["tmp_name"];
$file_size = $_FILES["productimage1"]["size"];
$error = $_FILES["productimage1"]["error"];
if (!$temp_name)
{
echo "ERROR: Please browse for 1st file before uploading";
exit();
}
$file_name2 = $_FILES["productimage2"]["name"];
$file_type2 = $_FILES["productimage2"]["type"];
$temp_name2 = $_FILES["productimage2"]["tmp_name"];
$file_size2 = $_FILES["productimage2"]["size"];
$error2 = $_FILES["productimage2"]["error"];
if (!$temp_name2)
{
echo "ERROR: Please browse for 2nd file before uploading";
exit();
}
$file_name3 = $_FILES["productimage3"]["name"];
$file_type3 = $_FILES["productimage3"]["type"];
$temp_name3 = $_FILES["productimage3"]["tmp_name"];
$file_size3 = $_FILES["productimage3"]["size"];
$error3 = $_FILES["productimage3"]["error"];
$file_name4 = $_FILES["productimage4"]["name"];
$file_type4 = $_FILES["productimage4"]["type"];
$temp_name4 = $_FILES["productimage4"]["tmp_name"];
$file_size4 = $_FILES["productimage4"]["size"];
$error4 = $_FILES["productimage4"]["error"];
$file_name5 = $_FILES["productimage5"]["name"];
$file_type5 = $_FILES["productimage5"]["type"];
$temp_name5 = $_FILES["productimage5"]["tmp_name"];
$file_size5 = $_FILES["productimage5"]["size"];
$error5 = $_FILES["productimage5"]["error"];
function compress_image($source_url, $destination_url, $quality)
{
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
//echo "Image uploaded successfully.";
}
if ($error > 0)
{
echo $error;
}
if ($error2 > 0)
{
echo $error;
}
if ($error3 > 0)
{
echo $error;
}
if ($error4 > 0)
{
echo $error;
}
if ($error5 > 0)
{
echo $error;
}
else if (($file_type == "image/gif") || ($file_type == "image/jpeg") || ($file_type == "image/png") || ($file_type == "image/pjpeg"))
{
$filename = compress_image($temp_name, "images/productimages/$productid/" . $file_name, 50);
$filename2 = compress_image($temp_name2, "images/productimages/$productid/" . $file_name2, 50);
$filename3 = compress_image($temp_name3, "images/productimages/$productid/" . $file_name3, 50);
$filename4 = compress_image($temp_name4, "images/productimages/$productid/" . $file_name4, 50);
$filename5 = compress_image($temp_name5, "images/productimages/$productid/" . $file_name5, 50);
}
else
{
echo "Uploaded image should be jpg or gif or png.";
}
When i'm trying to upload images(Resolution=5312*2988) it can't upload but when i upload low resolution images they all can be uploaded...So Can anyone help me to resize images according to my code or only resize according to my code...please
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;
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
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
}
Im making an image uploader, but i get the error: Only JPG, JPEG and PNG are allowed image types.
The uploader doesn't get the extension right. What do i do wrong?
The function to get the extension is at line 33. Ad from line 59 is where im trying to get the extension.
<?php session_start(); if ($_SESSION['username']) {} else { header("location:index.php"); exit(); } ?>
<?php
include 'db_connect.php';
$uploadSubmit = mysql_real_escape_string($_POST['imageSubmit']);
if ($uploadSubmit)
{
if ($_FILES['image'])
{
$contents = file_get_contents($_FILES['image']['tmp_name']);
if (stristr($contents, "<?php") || stristr($contents, "system(") || stristr($contents, "exec(") ||
stristr($contents, "mysql") || stristr($contents, "include(") || stristr($contents, "require(") ||
stristr($contents, "include_once(") || stristr($contents, "require_once(") || stristr($contents, "echo'") || stristr($contents, 'echo"'))
{
echo 'Are you really trying to hack this site? Enjoy your upload b&.';
$sql = "INSERT INTO banned (ip) VALUES ('".$_SERVER['REMOTE_ADDR']."')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
die();
}
}
else
{
$sql = "SELECT * FROM banned WHERE ip='".$_SERVER['REMOTE_ADDR']."'";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
$num_rows = mysql_fetch_row($result);
if ($num_rows[0] == 0)
{
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$I = strlen($str) - $i;
$ext = substr($str,$i+1,$I);
return $ext;
}
define ("MAX_SIZE","5000");
$error = 0;
$file = $_FILES['image']['name'];
if ($file = '')
{
echo 'You didn\'t select an image to upload.';
$error = 1;
}
else
{
$filename = stripslashes($file);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}
else
{
$size = filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo 'The max allowed filesize is 5MB.';
$error = 1;
}
$time = time();
$newImageName = 'wally-'.$time.'.'.$extension.'';
$imageFullPath = 'images/'.$newImageName.'';
if (!$errors)
{
if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageFullPath))
{
$error = 1;
}
}
if ($uploadSubmit && !$error)
{
include 'class.imageResizer.php';
$work = new ImgResizer($imageFullPath);
$work -> resize(125, "thumbs/".$newImageName."");
$uploader = $_SESSION['username'];
$sql = "INSERT INTO images (image, uploader, validated) VALUES ('$newImageName','$uploader','0')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
echo 'Your image has been uploaded and awaiting validation.';
echo 'The page will redirect in 2 seconds.';
echo '<meta http-equiv="Refresh" content="2;url=http://www.wallpapers.puffys.net">';
}
}
}
}
else
{
die("You are banned from uploading.");
}
}
}
?>
$i = strrpos($str,".");
if (!$i)
isn't a good way to test if the strrpos function returns a positive value.
You should use the === operator, like this :
$i = strrpos($str,".");
if ($pos === false)
Try using something like this:
$allowedExtensions = array("jpg","jpeg","png");
if (!in_array(end(explode(".",strtolower($file))),$allowedExtensions)) {
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}