Related
I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.
I am running Prestashop 1.6.1.7 and I have the following pictureUpload() method that allows users to upload files of their choosing. By default Prestashop allows uploads of GIF, JPG, JPEG or PNG only.
I'm trying to allow users the ability to upload a few more types (pdf, ai and eps specifically)
Here is the pictureUpload() method in the productController override:
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
//$file_name = md5(uniqid(rand(), true));
$file_name = $file['name']; // In this
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
}
}
return true;
}
This is looking to the ImageManager class, which has this method (that I have updated the error message on):
public static function validateUpload($file, $max_file_size = 0, $types = null)
{
if ((int)$max_file_size > 0 && $file['size'] > (int)$max_file_size) {
return sprintf(Tools::displayError('Image is too large (%1$d kB). Maximum allowed: %2$d kB'), $file['size'] / 1024, $max_file_size / 1024);
}
if (!ImageManager::isRealImage($file['tmp_name'], $file['type']) || !ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
return Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png, .pdf, .ai, .eps'); //I Updated This - this is the error kicking off when I try to upload AI
}
if ($file['error']) {
return sprintf(Tools::displayError('Error while uploading image; please change your server\'s settings. (Error code: %s)'), $file['error']);
}
return false;
}
The place where that method fails is pointing to two additional methods posted below. I updated the isRealImage method to try and allow the types I wanted through, but it still fails (and I commented where it fails).
public static function isRealImage($filename, $file_mime_type = null, $mime_type_list = null)
{
// Detect mime content type
$mime_type = false;
if (!$mime_type_list) {
//I UPDATED THIS LIST TO ALLOW FOR OTHER FILETYPES
$mime_type_list = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'application/illustrator', 'application/ai', 'application/eps', 'application/x-eps', 'image/eps', 'image/x-eps', 'application/pdf', 'application/acrobat', 'application/x-pdf', 'text/pdf', 'text/x-pdf');
}
// Try 4 different methods to determine the mime type
if (function_exists('getimagesize')) {
$image_info = #getimagesize($filename);
//HERE IMAGE_INFO IS SHOWING AS 'FALSE' SO IT GOES NO FURTHER WHEN UPLOADING A .AI FILE
if ($image_info) {
$mime_type = $image_info['mime'];
} else {
$file_mime_type = false;
}
} elseif (function_exists('finfo_open')) {
$const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$finfo = finfo_open($const);
$mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$mime_type = mime_content_type($filename);
} elseif (function_exists('exec')) {
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($filename)));
if (!$mime_type) {
$mime_type = trim(exec('file --mime '.escapeshellarg($filename)));
}
if (!$mime_type) {
$mime_type = trim(exec('file -bi '.escapeshellarg($filename)));
}
}
if ($file_mime_type && (empty($mime_type) || $mime_type == 'regular file' || $mime_type == 'text/plain')) {
$mime_type = $file_mime_type;
}
// For each allowed MIME type, we are looking for it inside the current MIME type
foreach ($mime_type_list as $type) {
if (strstr($mime_type, $type)) {
return true;
}
}
return false;
}
I also updated the isCorrectImageFileExt method:
public static function isCorrectImageFileExt($filename, $authorized_extensions = null)
{
// Filter on file extension
if ($authorized_extensions === null) {
//ADDED ALLOWED TYPES I WANT
$authorized_extensions = array('gif', 'jpg', 'jpeg', 'jpe', 'png', 'pdf', 'ai', 'eps');
}
$name_explode = explode('.', $filename);
if (count($name_explode) >= 2) {
$current_extension = strtolower($name_explode[count($name_explode) - 1]);
if (!in_array($current_extension, $authorized_extensions)) {
return false;
}
} else {
return false;
}
return true;
}
Thoughts on this?
Help on this?
You have gone too deep :). This is the pictureUpload method of ProductController that I've already made, you don't need others overrides. With my override you can upload pdf, ai, cdr and eps, but obviously you can change with your needs.
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
$file_name = md5(uniqid(rand(), true));
// Bad check, but rapid
$extension = substr($file['name'], -3, 3);
if($extension == 'jpg' OR $extension == 'gif' OR $extension == 'png'){
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
} elseif ($extension == 'pdf' OR $extension == '.ai' OR $extension == 'cdr' OR $extension == 'eps') {
$file_name = $file_name.'.'.str_replace('.', '', $extension);
if (!move_uploaded_file($file['tmp_name'], _PS_UPLOAD_DIR_.$file_name)) {
return false;
}
chmod(_PS_UPLOAD_DIR_.$file_name, 0777);
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
} else {
$this->errors[] = Tools::displayError('This format is not accepted');
}
}
}
return true;
}
After that you have to customize product.tpl, the cart summary of your template, and the backoffice order detail :)
Another solution if you do not want to hack your PrestaShop installation, which is not recommended if you want to be able to upgrade PretaShop safely, is to develop or use an existing module.
This module on the PrestaShop marketplace is probably what you are looking for:
https://addons.prestashop.com/en/front-office-features-prestashop-modules/88383-upload-any-file-type-in-product-customization.html
I am trying to move an existing image file from a temp folder to a proper location with a proper filename, for some reason it always fails.
function move_temp_image($article_id)
{
global $db, $config;
if (($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.jpg", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.png", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.gif", 'r+')))
{
$this->error_message = "Could not find temp image to load?";
return false;
}
else
{
$image_info = getimagesize($image_load);
$image_type = $image_info[2];
$file_ext = '';
if( $image_type == IMAGETYPE_JPEG )
{
$file_ext = 'jpg';
}
else if( $image_type == IMAGETYPE_GIF )
{
$file_ext = 'gif';
}
else if( $image_type == IMAGETYPE_PNG )
{
$file_ext = 'png';
}
// give the image a random file name
$imagename = rand() . 'id' . $article_id . 'gol.' . $file_ext;
// the actual image
$source = $image_load;
// where to upload to
$target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename;
if (rename($source, $target))
{
// remove old temp image
if ($image['article_top_image'] == 1)
{
unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/temp/' . $image_load);
}
unset($_SESSION['temp_tagline']);
$db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id));
return true;
}
else
{
$this->error_message = 'Could not move temp file to tagline uploads folder!';
return false;
}
}
}
I am not sure what I am doing wrong, I read rename is the way to do this, but I am obviously overlooking something.
You don't have the filename in $source - In your code, $source contains a file resource...
rename doesn't work only with file names, so you have to change your code.
i.e. replace your condition with the following code
$types = array('jpg', 'png', 'gif');
$file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.";
$image_load = false;
foreach ($types as $type) {
if (file_exists($file . $type)) {
$image_load = $file . $type;
break;
}
}
if (!file_exists($image_load))
My upload code is this. I submit the image to it with postdata. I want to make the file select box accept multiple picutes, and have it work on the backend. I can get the header location to work just fine on my own, but using an array of files has proved to be difficult, even though I've spent hours on stack overflow and google. I'd love it if somebody could show me how to do it.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$browse = $_POST["browse"];
preg_match('/\.([a-zA-Z]+?)$/', $_FILES['userfile']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['userfile']['size'] <= $maxsize) {
$newname = md5_file($_FILES['userfile']['tmp_name']).'.'.$matches[1];
$browse = $_POST["browse"];
if ($browse == "1") {
$filedir = 'img';
} else if ($browse == "2") {
$filedir = 'zega';
} else if ($browse == "3") {
$filedir = 'noimg';
} else if ($browse == "4") {
$filedir = 'adult';
} else if ($browse == "5") {
$filedir = 'temp';
} else {
$filedir = 'noimg';
}
move_uploaded_file($_FILES['userfile']['tmp_name'], $filedir.'/'.$newname);
$path = $filedir.'/'.$newname;
if (strpos($path,'jpg') !== false){
$img = imagecreatefromjpeg ($path);
imagejpeg ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'gif') !== false){
$img = imagecreatefromgif ($path);
imagegif ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'bmp') !== false){
$img = imagecreatefrombmp ($path);
imagebmp ($img, $path, 100);
imagedestroy ($img);
}
header("Location: index.php?p=uploaded&img=$newname");
} else
header("Location: index.php?p=error&num=2");
} else
header("Location: index.php?p=error&num=1");
}
?>
foreach($_FILES as $key_file=>$file_info){
//your code here instead $_FILES['userfile']['tmp_name'] use $file_info['tmp_name']
}
i wrote a class for uploads sometimes ago.
this class has ability to upload mutiple files at the same time(such as picture .etc).
it also has other ability such as :
-if you upload mutiple files with the same name it will automatically change their name
-you can add permitted types
-set maximum size of uploaded files
...
class Upload {
protected $_uploaded = array();
protected $_destination_upload_folder;
//Constraint
protected $_max_upload_size = 512000;
protected $_permitted_files = array('image/gif', 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg');
protected $_error_messages = array();
protected $_renamed_file = false;
public function __construct($input_upload_path) {
if(!is_dir($input_upload_path) || !is_writable($input_upload_path)){
throw new Exception("$input_upload_path must be a valid,writable path!");
}
$this->_destination_upload_folder = $input_upload_path;
$this->_uploaded = $_FILES;
}
protected function checkError($fileName, $error){
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_error_messages[] = "$fileName exceeds maximum file size : "
.$this->getMaxSize();
return true;
case 3:
$this->_error_messages[] = "Error while uploading $fileName.please try again.";
return false;
case 4:
$this->_error_messages[] = "No file selected.";
return false;
default:
$this->_error_messages[] = "System Error uploading $fileName.Please contact administrator.";
return false;
return false;
}
}
protected function checkSize($fileName, $size){
if($size == 0){
return false;
}else if($size > $this->_max_upload_size){
$this->_error_messages[] = "$fileName exceeds maximum size : ".
$this->_max_upload_size;
return false;
}else{
return true;
}
}
protected function checkType($fileName, $type){
if(!in_array($type, $this->_permitted_files)){
$this->_error_messages[] = 'This type of file is not allowed for uploading '
.'.please upload permitted files.';
return false;
}else{
return true;
}
}
public function checkName($input_file_name, $overwrite)
{
$input_file_name_without_spaces = str_replace(' ', '_', $input_file_name);
if($input_file_name_without_spaces != $input_file_name){
$this->_renamed_file = true;
}
if(!$overwrite){
$all_files_in_upload_directory = scandir($this->_destination_upload_folder);
if(in_array($input_file_name_without_spaces, $all_files_in_upload_directory)){
$dot_position = strrpos($input_file_name_without_spaces, '.');
if($dot_position){
$base = substr($input_file_name_without_spaces, 0, $dot_position);
$extension = substr($input_file_name_without_spaces, $dot_position);
}else{
$base = substr($input_file_name_without_spaces);
$extension = '';
}
$i = 1;
do{
$input_file_name_without_spaces = $base.'_'.$i++.$extension;
}while(in_array($input_file_name_without_spaces, $all_files_in_upload_directory));
$this->_renamed_file = true;
}
}
return $input_file_name_without_spaces;
}
protected function getMaxSize(){
return number_format(($this->_max_upload_size)/1024, 1).'kb';
}
protected function isValidMime($types)
{
$also_valid_mimes = array('application/pdf', 'text/plain', 'text/rtf');
$all_valid_mimes = array_merge($this->_permitted_files, $also_valid_mimes);
foreach($types as $type){
if(!in_array($type, $all_valid_mimes)){
throw new Exception("$type is not a valid permitted mime type!");
}
}
}
public function addPermittedType($input_type_name)
{
$input_type_name_array = (array)$input_type_name;
$this->isValidMime($input_type_name_array);
$this->_permitted_files = array_merge($this->_permitted_files, $input_type_name_array);
}
protected function processFile($fileName, $error, $size, $type, $tmp_name, $overwrite)
{
$check_upload_error = $this->checkError($fileName, $error);
if($check_upload_error){
$check_uploaded_file_type = $this->checkType($fileName, $type);
$check_uploaded_file_size = $this->checkSize($fileName, $size);
if($check_uploaded_file_type && $check_uploaded_file_size){
$new_uploaded_file_name = $this->checkName($fileName, $overwrite);
$upload_result = move_uploaded_file($tmp_name, $this->_destination_upload_folder.$new_uploaded_file_name);
if($upload_result){
$messages = $new_uploaded_file_name.' uploaded successfully! <br >';
if($this->_renamed_file){
$messages .= ' and renamed successfully!';
}
$this->_error_messages[] = $messages;
} else {
$this->_error_messages[] = 'Could`nt upload '.$fileName;
}
}
}
}
public function move($overwrite = FALSE){
$file = current($this->_uploaded);
if(is_array($file['name'])){
foreach($file['name'] as $index => $filename){
$this->_renamed_file = false;
$this->processFile($filename, $file['error'][$index],
$file['size'][$index], $file['type'][$index], $file['tmp_name'][$index], $overwrite);
}
}else{
$this->processFile($file['filename'], $file['error'], $file['size'], $file['type']
, $file['tmp_name'], $overwrite);
}
}
public function getErrorMessages(){
return $this->_error_messages;
}
public function setMaxSize($new_upload_size)
{
if(!is_numeric($new_upload_size) || $new_upload_size <= 0){
throw new Exception("new maximum upload size must a number!");
}
$this->_max_upload_size = (int)$new_upload_size;
}
}
$max_upload_size = 1024 * 1024;
if(isset($_POST['upload_button'])){
$destination_upload_folder = 'destination of upload folder here....';
require_once 'Upload class filename...';
try{
$upload = new Upload($destination_upload_folder);
$upload->setMaxSize($max_upload_size);
$upload->addPermittedType('application/pdf');
$upload->move(true);
$result = $upload->getErrorMessages();
}catch(Exception $e){
echo $e->getMessage();
}
}
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
}