Extend variable from one function to another - php

I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file.
I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content.
If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified.
What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function.
is there a way to do this? in a smart way? :D
Here is my code:
<?php
function EditFrontPage($db)
{
$stmt = $db->prepare("SELECT `id`, `heading`, `content`, `image` FROM `content` WHERE `page` = 'forside';");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['EditFrontpageSubmit']))
{
imageUpload(10000, 100, 100, '', 5);
global $newname;
echo $newname;
}
?>
<form class="adminForm" enctype="multipart/form-data" action="" method="post">
<h2>Overskrift</h2>
<input type="text" value="<?=$row['heading']?>" />
<input type="file" name="image[]" />
<h2>Tekst</h2>
<textarea><?=br2nl($row['content'])?></textarea>
<input type="submit" name="EditFrontpageSubmit" value="Opdater nyhed" />
</form>
<?php
}
function imageUpload($maxsize = 2000, $quality = 95, $imgwidth = 400, $imgheight = '', $numOfImages = 5, $path = '/lucas/images/')
{
// Turn on error reporting
error_reporting(-1);
//Set the max upload size in kilobytes
define("MAX_SIZE", "$maxsize");
if(empty($imgheight) && empty($imgwidth))
{
echo "<h1>Fejl: Definer bredde eller højde</h1>";
die();
}
//Makes a function that check the extension
function getExtension($str){
$i = strrpos($str, ".");
if(!$i){return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//Set errors to 0 from standard
$errors = 0;
//Define the size as a variable
$size = '';
//foreach image selected
foreach($_FILES['image']['error'] as $key => $error)
{
//If no errors, return true
if($error == UPLOAD_ERR_OK)
{
//Gets the filename
$filename = stripslashes($_FILES['image']['name'][$key]);
//Gets the extension
$extension = getExtension($filename);
//convert the extension to lowercase
$extension = strtolower($extension);
//if the file extension doesn't match, return error
if(($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "<h1>Unknown Extension!</h1>";
$errors = 1;
}
//This check if the amount of images is over 5.
elseif(count($_FILES['image']['name']) > $numOfImages)
{
//If it's over 5 images, return error and exit
echo "Too many images";
exit();
}
else
{
//Get the filesize of the image (total amount if multiple images).
$size += filesize($_FILES['image']['tmp_name'][$key]);
//if the filesize is over the defined amount
if($size > MAX_SIZE*1024)
{
echo "<h1>Du har overskredet maksimum fil-upload størrelse!</h1>";
$errors = 1;
}
//This renames the image, to contain, the microtime, and a unique ID + extension
$image_name = microtime(true) . uniqid('',true) . '.' . $extension;
//This sets the path of the image.
$newname = $_SERVER['DOCUMENT_ROOT'] . $path . $image_name;
//It moves the file(s) to the path defined above!
$copied = move_uploaded_file($_FILES['image']['tmp_name'][$key], $newname);
//Check if the extension is png
//if($extension == "png")
//{
//converts the quality from 'jpeg/gif' quality to png compression method
//$pngquality = round($quality/100 * 9);
//Executes a shell command optimizing the png
//shell_exec("gm mogrify -quality $pngquality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//}
//else
//Executes a shell command optimizing the jpeg/gif
//shell_exec("gm mogrify -quality $quality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//If the image isn't copied, return an error
if(!$copied)
{
echo "<h1>Der skete en fejl!</h1>";
$errors = 1;
}
//Creates an array of the images
$array[] = $newname;
}
}
}
//If the submit is set, and errors = 0 return true
if(isset($_POST['Submit']) && $errors != 1)
{
echo "<h1>Fil blev uploaded som den skulle!</h1>";
//Makes a for loop, that echo's out all uploaded images
for($i = 0; $i < count($array); $i++)
{
echo "<img src='{$array[$i]}' /><p>".preg_replace("/.*\//i", '', $array[$i])."</p>";
}
}
}
?>
Thank you a lot guys!

Have the imageupload() function return the $newname variable, and then set it like so on the EditFrontPage() function:
$newName = imageUpload(10000, 100, 100, '', 5);

just return $newname at the end of imageUpload function and modify this part:
if(isset($_POST['EditFrontpageSubmit']))
{
echo imageUpload(10000, 100, 100, '', 5);
}

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

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

Multiple image upload with PHP

I'm trying upload multiple images. Below you can see my code.
Image uploaded massage repenting (exactly the amount of image chosen to upload.)
How can i show "Image uploaded" massage only ones on successful submit?
If i put the message after the loop it will start to show no matter if there is any errors.
This is my PHP code:
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
echo "Image uploaded";
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Any help will be appropriated.
You can implement a counter and when an upload completes successfully you can increment that counter variable then compare it against total number of array items after foreach loop completes. I modified your code for this (haven't checked it but should work).
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
$successfulUploads = 0;
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)) {
if ($size < (MAX_SIZE*1024)) {
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
//echo "Image uploaded";
$successfulUploads = $successfulUploads + 1;
} else {
echo '<span class="imgList">Moving unsuccessful! </span>';
}
} else {
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
} else {
echo '<span class="imgList">Unknown extension!</span>';
}
}
if($successfulUploads === count($_FILES['photos'])){
echo 'UPLOAD SUCCESS!';
} else {
echo 'NOT ALL IMAGES WERE UPLOADED SUCCESSFULLY';
}
}
*If you wanted to get more complex with it you could create another array variable instead of a counter and if the upload fails you could add the file name to the array and then check the length of the array where I'm doing the comparison. If count > 0 then you would know there was an error and you could echo the filenames that failed to upload

error handling and image type cat get it to work

I been working on this image script for too long now, and I still can't seem to get two things to work - the image type and error handling (if the fields are empty). I have the code for this, but every place I try to add it, it doesn't work.
my code:
$error_message="";
$MaxSize = "600000";
if (isset($_POST['btn_update'])){
function createRandomPassword() {
$chars = "abcde!##%^fghijkmnoABCDEFGHIJKpqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWZ!##%^&";
srand((double)microtime()*10000000);
$i = 0;
$pass = '' ;
while ($i <= 19) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
if ($_FILES['aMyUploads0']['size'] > $MaxSize || $_FILES['aMyUploads1']['size'] > $MaxSize || $_FILES['aMyUploads2']['size'] > $MaxSize)
{
$error_message = "ERROR: File too big!";
}
$aMyUploads = array();
$password = createRandomPassword();
foreach($_FILES as $aFile)
{
$newLocation = 'uploads/'.$password .$aFile["name"];
if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
{
$aMyUploads[] = $newLocation;
}
else
{
$aMyUploads[] = '';
}
}
$error_message="Journal successfully saved.";
$connection = mysql_connect("localhost", "????", "???");
mysql_select_db("????", $connection);
$insert = "INSERT INTO photos (image1, image2, image3) VALUES
(
' ".$aMyUploads[0]." ',
' ".$aMyUploads[1]." ',
' ".$aMyUploads[2]." '
)";
$add_member = mysql_query($insert) or die(mysql_error());
}
code im trying to add with no luck:
//ERROR HANDLING CODE:
if(empty($aMyUploads[0]) || empty($aMyUploads[1]) || empty($aMyUploads[2]))
{
$error_message="Please fill in all fields.";
}
else
{
$error_message="Journal successfully saved.";
//IMAGE TYPE CODE:
$allowed_filetypes = array(".jpg", ".gif", ".jpeg", ".png");
$ext = substr($newLocation, strpos($newLocation,'.'), strlen($newLocation)-1);
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
Try this for checking required fields, inserted before the code that checks the file sizes.
// ERROR HANDLING CODE:
if (empty($_FILES) || empty($_FILES['aMyUploads0']) || empty($_FILES['aMyUploads1']) || empty($_FILES['aMyUploads2']))
{
// Handle error
}
And this for validating file types, inserted into your foreach.
// IMAGE TYPE CODE:
$allowed_filetypes = array("jpg", "gif", "jpeg", "png");
$ext = pathinfo($aFile['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_filetypes))
{
// Handle error
}

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