File uploads fails when file name contains space - php

I have googled this question but did not find an answer. I am using the ng-file-upload Angular directive to upload images to my back-end. At the back-end I am using php to retrieve the image. It works fine if I select an image which contains no white space. But if I select an image which contains white space it throws an error. This is what I did
//app.js
Upload.upload({
url: "api/index.php/postNewFeedsWithPicture",
file: $scope.file,
method: "post"
}).then(function (response) {
$scope.isShowing = false;
if (response.data.error) {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error(response.data.message, {timeOut: 5000});
}
else {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.success(response.data.message, {timeOut: 5000});
$scope.file = null;
}
}, function (reason) {
$scope.isShowing = false;
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error('Message not posted! Network error', {timeOut: 5000});
});
in my html file i did this
<div role="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB">Upload</div>
in my php file I wrote a function that saves the image
function savePictureToDb($fileName, $dirName) {
$target_dir = "../image/" . $dirName . "/";
$target_file = $target_dir . basename($_FILES[$fileName]["name"]);
$uploadOk = 1;
$errorMsg = null;
$report = array();
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size. //20mb
if ($_FILES[$fileName]["size"] > 20000000) {
$uploadOk = 0;
$errorMsg = "File size is greater than 20 mega bytes";
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
$uploadOk = 0;
$errorMsg = "The file selected is not an image";
}
if ($uploadOk == 0) {
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES[$fileName]["tmp_name"], $target_file)) {
rename($target_file, $target_dir . generateRandStr_md5(500) . "." . $imageFileType);
$response['path'] = basename($_FILES[$fileName]["name"]);
$report[ERROR] = FALSE;
$report[PATH] = $response['path'];
return $report;
} else {
$errorMsg = "Unexpected error";
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
}
}
}
It works fine, but if the image contains white space this is the error i get when debugging
array (
'file' =>
array (
'name' => 'Age Declaration.jpg',
'type' => '',
'tmp_name' => '',
'error' => 1,
'size' => 0,
),
)

Rename the file name with random value
$filename1=explode(".", $file);
$extension=end($filename1);
$file=rand().time().".".$extension;
Or Use pathinfo() for extention
$ext = pathinfo($filename, PATHINFO_EXTENSION);

Related

Cannot upload images using angular and php

I cannot upload the images while using angular and php using this code.
please assist..
I got an error undefined index error on line 2 from php
angular side
const formData = new FormData();
formData.append('date', this.uploadRequest.date.toString());
formData.append('description', this.uploadRequest.description);
formData.append('title', this.uploadRequest.title);
this.imageDetails.forEach((image, i) => {
formData.append('images[' + i + ']', image.file);
});
const params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', '/api/upload', formData, options);
return this.http.request(req).subscribe();
php side
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if (!empty($_FILES['image'])) {
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}
You need to put your code inside the if statement. You are trying to execute a code before the if statement is ran and that code is crucial for the if statement to function properly.
if (!empty($_FILES['image'])) {
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}

PHP - values not saved in array

Apologies, but couldn't find an answer to this already...
I have some PHP code that hits an error, which I echo and save to an array:
echo "File is not an image.";
$errors[] = "File is not an image";
The array is defined earlier:
$errors = array();
When I debug my web page, I can see the echo (so I know it's hitting that error) but the array is empty...screenshot below:
screenshot of web page
Any idea what I'm doing wrong? Or how to debug further?
Thanks!
Simon
EDIT: I noticed the array was declared twice. Removed that, no change.
Full code below
<?php
class BanditquotecustomformModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$varCountry = '';
$varRemarks = '';
$varContactEmail = '';
$varCustomerName = '';
$varPhone = '';
$varUrgency = '';
$sql = '';
$user_id ='';
/* For when I get this working!
$id_lang = Context::getContext()->language->id;
$category = Category::searchByName($id_lang,"personalised",true);*/
/*parent::initContent();*/
if ($this->context->customer->isLogged())
{
$this->setTemplate('customform.tpl');
$custfirstname = $this->context->customer->firstname;
$custlastname = $this->context->customer->lastname;
$custemail = $this->context->customer->email;
$this->context->smarty->assign('firstname', $custfirstname);
$this->context->smarty->assign('lastname', $custlastname);
$this->context->smarty->assign('customer_email', $custemail);
parent::initContent();
}
else
{
Tools::redirect('index.php?controller=authentication&back='.urlencode($this->context->link->getModuleLink('banditquote', 'customform')));
}
}
/* adds a new product for every quote */
private function addProduct($LastId)
{
$reference = 'CUST'.$LastId;
$name = $reference;
$product = new Product();
$languages=Language::getLanguages();
foreach($languages as $lang){
$product->name[$lang['id_lang']]=$name;
$product->link_rewrite[$lang['id_lang']]=$name;
$product->description[$lang['id_lang']]=$name;
}
$product->reference=$reference;
$product->active='1';
$product->available_for_order='1';
$product->is_virtual='1';
/* add product to category */
$product->id_category='2';
$product->id_category_default='2';
try{
$product->save();
} catch (PrestaShopException $e){
echo $e->displayMessage();
}
$product->addToCategories(array(2));
$product->save();
$prod_shopupdate = Db::getInstance()->Execute('
UPDATE `'.pSQL(_DB_PREFIX_).'product_shop`
SET `active` = "1",`available_for_order` = "1"
WHERE `id_product` = "'.((int)$product->id).'"');
return $product->id;
}
/* checking attachment */
private function checkImage()
{
$target_dir = '_THEME_PROD_PIC_DIR_';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 0;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$errors[] = $this->module->l('File is an image', 'customform');
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image";
$errors[] = "File is not an image";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errors[] = $this->module->l('Sorry, file already exists', 'customform');
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$errors[] = $this->module->l('Sorry, your file is too large', 'customform');
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errors[] = $this->module->l('Sorry, only JPG, JPEG, PNG & GIF files are allowed', 'customform');
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$errors[] = $this->module->l('Sorry, your file was not uploaded', 'customform');
// if everything is ok, try to upload file
}
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else {
$errors[] = $this->module->l('Sorry, there was an error uploading your file', 'customform');
}
}
return $uploadOk;
}
public function postProcess()
{
if (Tools::isSubmit('submit'))
{
$errors = array();
$failed = false;
$varUserId = (int)$this->context->customer->id;
$varRemarks = Tools::getValue('formRemarks');
$newRemarks = str_replace("'","''", $varRemarks);
$varCountry = Tools::getValue('formCountry');
$varContactEmail = Tools::getValue('formContactEmail');
$varCustomerName = Tools::getValue('formCustomerName');
$varPhone = Tools::getValue('formPhone');
$varUrgency = Tools::getValue('formUrgency');
if (empty($varRemarks))
{
$errors[] = $this->module->l('The message cannot be blank.', 'customform');
//d($errors);
}
else
{
$sql = "INSERT INTO `ps_quotes` (`quote_destin`,`quote_remarks`,`quote_email`,`quote_submitter_name`,`quote_phone`,`quote_urg`,`quote_user_id`)
VALUES('{$varCountry}','{$newRemarks}','{$varContactEmail}','{$varCustomerName}','{$varPhone}','{$varUrgency}','{$varUserId}');";
if (!Db::getInstance()->execute($sql))
{
die('Error creating Custom Order - Please contact admin#banditbirds.co.uk');
}
$quoteid = Db::getInstance()->Insert_ID();
$prod_id = $this->addProduct(Db::getInstance()->Insert_ID());
if ($prod_id == null )
{
die('Error creating Custom Product for Custom Order - Please contact admin#banditbirds.co.uk');
}
$updatesql = "UPDATE `ps_quotes` SET `quote_product_link` = $prod_id WHERE `quote_id` = $quoteid;";
Db::getInstance()->execute($updatesql);
//Check the uploaded attachment - if there
if ( $this->checkImage() )
{
// add ps_attachment
// link ps_attachment to product with ps_product_attachment
}
else
{
$this->context->smarty->assign('errors', $errors);
$failed = true;
d($errors);
}
//Mailing
$confirmation1 = '';
$template = 'banditquote';
$template_owner = 'banditquote_owner';
$template_vars = array(
'{banditquote_contactaddress}' => '',
'{banditquote_contacttown}' => '',
'{shop_url}' => Tools::getShopDomain(true),
/* in case we need to check ssl $this->ssl_enable ? Tools::getShopDomainSsl(true) : Tools::getShopDomain(true);*/
'{remarks}' => $varRemarks,
'{shipping_destination}' => $varCountry,
'{phone}' => $varPhone,
'{name_cust}' => $varCustomerName,
'{shipping_quantity}' => '',
'{paypal}' => '',
'{first_order}' => '',
'{urgency}' => $varUrgency,
'{language}' => (int)$this->context->language->id,
'{webmaster}' => 'admin#banditbirds.co.uk',
'{email}' => $varContactEmail,
'{shop_name}' => Configuration::get('PS_SHOP_NAME'),
'{owner_email}' => Configuration::get('PS_SHOP_EMAIL'));
$language = (int)$this->context->language->id;
$maildir = '/home/banditbi/public_html/modules/banditquote/mails/1.5/';
if ((Mail::Send($language, $template, Configuration::get('PS_SHOP_NAME'), $template_vars, $varContactEmail, null, null, null, null, null, $maildir,false,null)) &&
(Mail::Send($language, $template_owner, Configuration::get('PS_SHOP_NAME'), $template_vars, 'admin#banditbirds.co.uk', null, null, null, null, null, $maildir,false,null)))
$this->context->smarty->assign('confirmation1', 1);
else
{
if (is_null($confirmation1))
{
$this->_html .= '<div style="background:#F00; padding:5px; border:thin; border-color:#030; text-align:center">'.$this->l('CAPTCHA Error, please go back and try once more.').'</div><br />';
return $this->_html;
}
}
if( !$failed )
{
Tools::redirect('index.php');
}
}
$this->context->smarty->assign(array(
'id_customer' => (int)$this->context->customer->id,
'errors' => $errors,
'form_link' => $errors,
));
$this->setTemplate('customform.tpl');
}
}
}
?>
Make sure you are defining the array before attempting to store values into it.
$errors = array();
$errors[] = 'File is not an image';
Do not try to redefine the array after you add items to this array. Otherwise, you will reset the array effectively removing any items previously added.

Just Inserting Blank array() inside in mysql error

I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.

How to Upload Photo and return GPS co-ords

All,
I'm tinkering with a simp[le form to upload a photo, store it within my server & then return the GPS co-ordinates.
I'm using the standard PHP file upload script and a GPs solution i found here. It allows me to upload files but does not return the GPS co-ordinates. Can anyone help identify the issue please?
My complete php is:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
read_gps_location($target_file);
/**
* Returns an array of latitude and longitude from the Image file
* #param image $file
* #return multitype:number |boolean
*/
function read_gps_location(){
if (is_file($target_file)) {
$info = exif_read_data($target_file);
if (isset($info['GPSLatitude']) && isset($info['GPSLongitude']) &&
isset($info['GPSLatitudeRef']) && isset($info['GPSLongitudeRef']) &&
in_array($info['GPSLatitudeRef'], array('E','W','N','S')) && in_array($info['GPSLongitudeRef'], array('E','W','N','S'))) {
$GPSLatitudeRef = strtolower(trim($info['GPSLatitudeRef']));
$GPSLongitudeRef = strtolower(trim($info['GPSLongitudeRef']));
$lat_degrees_a = explode('/',$info['GPSLatitude'][0]);
$lat_minutes_a = explode('/',$info['GPSLatitude'][1]);
$lat_seconds_a = explode('/',$info['GPSLatitude'][2]);
$lng_degrees_a = explode('/',$info['GPSLongitude'][0]);
$lng_minutes_a = explode('/',$info['GPSLongitude'][1]);
$lng_seconds_a = explode('/',$info['GPSLongitude'][2]);
$lat_degrees = $lat_degrees_a[0] / $lat_degrees_a[1];
$lat_minutes = $lat_minutes_a[0] / $lat_minutes_a[1];
$lat_seconds = $lat_seconds_a[0] / $lat_seconds_a[1];
$lng_degrees = $lng_degrees_a[0] / $lng_degrees_a[1];
$lng_minutes = $lng_minutes_a[0] / $lng_minutes_a[1];
$lng_seconds = $lng_seconds_a[0] / $lng_seconds_a[1];
$lat = (float) $lat_degrees+((($lat_minutes*60)+($lat_seconds))/3600);
$lng = (float) $lng_degrees+((($lng_minutes*60)+($lng_seconds))/3600);
//If the latitude is South, make it negative.
//If the longitude is west, make it negative
$GPSLatitudeRef == 's' ? $lat *= -1 : '';
$GPSLongitudeRef == 'w' ? $lng *= -1 : '';
return array(
'lat' => $lat,
'lng' => $lng
);
}
}
return false;
}
?>
You invoke function read_gps_location($target_file); but you don't print the output
try changing this line
read_gps_location($target_file);
to
print_r(read_gps_location($target_file));
To see the output. It should be either array or false.

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