PHP uploading files using <input> multiple Attribute - php

I'm currently having several <input type="file" fields for uploading images. I want to convert the input fields to one single field using the html multiple attribute.
My working code with multiple input fields:
<input type="file" name="popup_images_1">
<input type="file" name="popup_images_2">
<input type="file" name="popup_images_3">...
for ($i = 1; $i <= 3; $i++) {
if (is_uploaded_file($_FILES['popup_images_' . $i]['tmp_name'])) {
$products_image = new upload('popup_images_' . $i);
$products_image->set_destination(DIR_FS_CATALOG_IMAGES);
if ($products_image->parse() && $products_image->save()) {
$products_image_name = $products_image->filename;
// do database stuff
}
}
}
My new code, which is not working, with a single input field:
<input type="file" name="popup_images[]" multiple="multiple">
$num_files = count($HTTP_POST_FILES['popup_images']['tmp_name']);
for ($i = 1; $i <= $num_files; $i++) {
if (is_uploaded_file($HTTP_POST_FILES['popup_images']['tmp_name'][$i])) {
$products_image = new upload('popup_images' . $i);
$products_image->set_destination(DIR_FS_CATALOG_IMAGES);
if ($products_image->parse() && $products_image->save()) {
$products_image_name = $products_image->filename;
// do database stuff
}
}
}
Things seems to go wrong at the line where new upload('popup_images' . $i) is set. Any ideas?
This is the upload class:
class upload {
var $file, $filename, $destination, $permissions, $extensions, $tmp_filename, $message_location;
function upload($file = '', $destination = '', $permissions = '777', $extensions = '') {
$this->set_file($file);
$this->set_destination($destination);
$this->set_permissions($permissions);
$this->set_extensions($extensions);
$this->set_output_messages('direct');
if (tep_not_null($this->file) && tep_not_null($this->destination)) {
$this->set_output_messages('session');
if ( ($this->parse() == true) && ($this->save() == true) ) {
return true;
} else {
return false;
}
}
}
function parse() {
global $HTTP_POST_FILES, $messageStack;
$file = array();
if (isset($_FILES[$this->file])) {
$file = array('name' => $_FILES[$this->file]['name'],
'type' => $_FILES[$this->file]['type'],
'size' => $_FILES[$this->file]['size'],
'tmp_name' => $_FILES[$this->file]['tmp_name']);
} elseif (isset($HTTP_POST_FILES[$this->file])) {
$file = array('name' => $HTTP_POST_FILES[$this->file]['name'],
'type' => $HTTP_POST_FILES[$this->file]['type'],
'size' => $HTTP_POST_FILES[$this->file]['size'],
'tmp_name' => $HTTP_POST_FILES[$this->file]['tmp_name']);
}
if ( tep_not_null($file['tmp_name']) && ($file['tmp_name'] != 'none') && is_uploaded_file($file['tmp_name']) ) {
if (sizeof($this->extensions) > 0) {
if (!in_array(strtolower(substr($file['name'], strrpos($file['name'], '.')+1)), $this->extensions)) {
if ($this->message_location == 'direct') {
$messageStack->add(ERROR_FILETYPE_NOT_ALLOWED, 'error');
} else {
$messageStack->add_session(ERROR_FILETYPE_NOT_ALLOWED, 'error');
}
return false;
}
}
$this->set_file($file);
$this->set_filename($file['name']);
$this->set_tmp_filename($file['tmp_name']);
return $this->check_destination();
} else {
if ($this->message_location == 'direct') {
$messageStack->add(WARNING_NO_FILE_UPLOADED, 'warning');
} else {
$messageStack->add_session(WARNING_NO_FILE_UPLOADED, 'warning');
}
return false;
}
}
function save() {
global $messageStack;
if (substr($this->destination, -1) != '/') $this->destination .= '/';
if (move_uploaded_file($this->file['tmp_name'], $this->destination . $this->filename)) {
chmod($this->destination . $this->filename, $this->permissions);
if ($this->message_location == 'direct') {
$messageStack->add(SUCCESS_FILE_SAVED_SUCCESSFULLY, 'success');
} else {
$messageStack->add_session(SUCCESS_FILE_SAVED_SUCCESSFULLY, 'success');
}
return true;
} else {
if ($this->message_location == 'direct') {
$messageStack->add(ERROR_FILE_NOT_SAVED, 'error');
} else {
$messageStack->add_session(ERROR_FILE_NOT_SAVED, 'error');
}
return false;
}
}

Related

How to write this into php code? Alt of the Image

How to write this into code please?
if the alt of the image is "your alt here" then its 1.
Here is the code that i made.
public function getSiteAdvisor($domain)
{
try
{
$callback_url = "https://www.mcafee.com/threat-intelligence/site/default.aspx?url=" . $domain;
$curl_response = $this->curl->get($callback_url);
if ($curl_response->headers['Status-Code'] == "200") {
libxml_use_internal_errors(TRUE);
$this->dom_doc->loadHTML($curl_response);
libxml_use_internal_errors(FALSE);
$xpath = new DOMXPath($this->dom_doc);
$tmp = $xpath->query('/html/body//div[#class="threeFourth"]//img/#alt')->item(0);
I don't know how to code the 'alt' of the image.
I add some code but not sure if this is correct.
if ($tmp->hasAttribute('src')) {
$tmp = $tmp->getAttribute('src');
if (stripos($tmp, "Minimal") !== false) {
$siteadvisor_rating = 1;
} elseif (stripos($tmp, "Moderate") !== false) {
$siteadvisor_rating = 2;
} elseif (stripos($tmp, "High") !== false) {
$siteadvisor_rating = 3;
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;
}
$response = array(
'status' => 'success',
'data' => array(
'siteadvisor' => (int)$siteadvisor_rating
)
);
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
Thanks
I found an answer by using this:
if ($tmp->hasAttribute('src')) {
$tmp = $tmp->getAttribute('alt');
if (stripos($tmp, "Minimal") !== false) {
$siteadvisor_rating = 1;
} elseif (stripos($tmp, "Moderate") !== false) {
$siteadvisor_rating = 2;
} elseif (stripos($tmp, "High") !== false) {
$siteadvisor_rating = 3;
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;

Limitting file upload on a User php

Im new to php please help me, I have a website and people can upload files like pdf, doc,xls and I want to limit the number of file upload. the user after login can see the upload page and upload his files but i want that the user can only upload files 3 times a day if he submitted 3 times in a day then it should not allow the user to upload more files it should give a message that you can not post more that 3 projects per day.
My files are: form.php and Uploadfile.php
<?php
use foundationphp\UploadFile;
session_start();
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2000000;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
// $upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploads</title>
<link href="styles/form.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Uploading Files</h1>
<?php if ($result || $error) { ?>
<ul class="result">
<?php
if ($error) {
echo "<li>{$error['message']}</li>";
}
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";
}
}?>
</ul>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<label for="filename">Select File:</label>
<input type="file" name="filename[]" id="filename" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>">
</p>
<ul>
<li>Up to <?php echo $_SESSION['maxfiles'];?> files can be uploaded simultaneously.</li>
<li>Each file should be no more than <?php echo UploadFile::convertFromBytes($max);?>.</li>
<li>Combined total should not exceed <?php echo $_SESSION ['displaymax'];?>.</li>
</ul>
<p>
<input type="submit" name="upload" value="Upload File">
</p>
</form>
<script src="js/checkmultiple.js"></script>
</body>
</html>
And uploadfile.php
<?php
namespace foundationphp;
class UploadFile
{
protected $destination;
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Thanks/Regards,
Sam
You can use SQL to store the amount of files uploaded by each user. Then you can check in php if a user can upload another file or not with SQL queries.
EDIT:
Let's elaborate a little.
There can be 2 ways for achieving this:
a) server-side.
As you say, you have a login form. I suppose you have a database with usernames and passwords, right? So, you can add an 'uploads' table in your database with the timestamp of each upload and the username of the uploader.
Then, each time your PHP class is called, you can make a query to your database to see the amount of files the uploader has uploaded within the last 24 hours. If the number is <3 then your PHP class will allow him to upload another one. Else, your PHP class will echo the message you want.
b) client-side.
Each time a user uploads a file, the info about his uploads is stored in his localStorage. So, this info will be checked on 'upload' button click event and either he will be allowed to upload or not.
However, as I said, the info is stored in HIS localStorage, so, this method is bypassable by the user. I wouldn't recommend it.
Improve your upload function and add destination inside UploadFile class for better re-usability and security:
class UploadFile
{
protected $destination = __DIR__ . '/uploaded/';
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$fi = new FilesystemIterator($this->destination, FilesystemIterator::SKIP_DOTS);
$totalFiles = iterator_count($fi);
if ($totalFiles <= 3){
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
} else {
die('You can not post more that 3 projects per day!'); //Improve this to a thrown or stuff;
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
I think you have a user table in you DB. just add a new attribute upload_day_count...
At every upload you check if the number is at 3 if not then you allow the upload and icrement the attribute value for this user. Day +1 at 00h01min you run a cron Job to reset all values for all users.

Combining PHP classes, not populating array

I've got 3 different classes (class Thumbnail in Thumbnail.php, class Upload in Upload.php and class ThumbnailUpload in ThumbnailUpload.php) all in the same namespace (PhotoProject). Currently, it will load an image, create a thumbnail and store both in selected directory, but it will not store the information requested into a database. If you look in the code snippet of blog_insert.php, once it gets to calling $loader->collectFilenames to be assigned to $names, nothing is ever stored in $names[]. I've did a var_dump, and $names is always empty. Any suggestions? Below are the code snippets.
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
...
public function collectFilenames() {
return $this->collectednames;
}
blog_insert.php
<?php
use PhotoProject\ThumbnailUpload;
require_once '../includes/connection.php';
$conn = dbConnect();
if (isset($_POST['insert'])) {
$OK = false;
$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
$imageOK = false;
require_once '../PhotoProject/ThumbnailUpload.php';
$loader = new ThumbnailUpload('path to store images');
$loader->setThumbDestination('path to store thumbnail');
$loader->upload();
$names = $loader->collectFilenames();
// $names will be an empty array if the upload failed
if ($names) {
$sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';
Class Thumbnail
<?php
namespace PhotoProject;
class Thumbnail {
protected $original;
protected $originalwidth;
protected $originalheight;
protected $basename;
protected $thumbwidth;
protected $thumbheight;
protected $maxSize = 350;
protected $canProcess = false;
protected $imageType;
protected $destination;
protected $suffix = '_thb';
protected $messages = [];
public function __construct($image) {
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
} else {
$details = null;
$this->messages[] = "Cannot open $image.";
}
// if getimagesize() returns an array, it looks like an image
if (is_array($details)) {
$this->original = $image;
$this->originalwidth = $details[0];
$this->originalheight = $details[1];
$this->basename = pathinfo($image, PATHINFO_FILENAME);
// check the MIME type
$this->checkType($details['mime']);
} else {
$this->messages[] = "$image doesn't appear to be an image.";
}
}
public function setDestination($destination) {
if (is_dir($destination) && is_writable($destination)) {
// get last character
$last = substr($destination, -1);
// add a trailing slash if missing
if ($last == '/' || $last == '\\') {
$this->destination = $destination;
} else {
$this->destination = $destination . DIRECTORY_SEPARATOR;
}
} else {
$this->messages[] = "Cannot write to $destination.";
}
}
public function setMaxSize($size) {
if (is_numeric($size) && $size > 0) {
$this->maxSize = abs($size);
} else {
$this->messages[] = 'The value for setMaxSize() must be a positive number.';
$this->canProcess = false;
}
}
public function setSuffix($suffix) {
if (preg_match('/^\w+$/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function create() {
if ($this->canProcess && $this->originalwidth != 0) {
$this->calculateSize($this->originalwidth, $this->originalheight);
$this->createThumbnail();
} elseif ($this->originalwidth == 0) {
$this->messages[] = 'Cannot determine size of ' . $this->original;
}
}
public function getMessages() {
return $this->messages;
}
protected function checkType($mime) {
$mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($mime, $mimetypes)) {
$this->canProcess = true;
// extract the characters after 'image/'
$this->imageType = substr($mime, 6);
}
}
protected function calculateSize($width, $height) {
if ($width <= $this->maxSize && $height <= $this->maxSize) {
$ratio = 1;
} elseif ($width > $height) {
$ratio = $this->maxSize/$width;
} else {
$ratio = $this->maxSize/$height;
}
$this->thumbwidth = round($width * $ratio);
$this->thumbheight = round($height * $ratio);
}
protected function createImageResource() {
if ($this->imageType == 'jpeg') {
return imagecreatefromjpeg($this->original);
} elseif ($this->imageType == 'png') {
return imagecreatefrompng($this->original);
} elseif ($this->imageType == 'gif') {
return imagecreatefromgif($this->original);
}
}
protected function createThumbnail() {
$resource = $this->createImageResource();
$thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
$this->thumbheight, $this->originalwidth, $this->originalheight);
$newname = $this->basename . $this->suffix;
if ($this->imageType == 'jpeg') {
$newname .= '.jpg';
$success = imagejpeg($thumb, $this->destination . $newname, 100);
} elseif ($this->imageType == 'png') {
$newname .= '.png';
$success = imagepng($thumb, $this->destination . $newname, 0);
} elseif ($this->imageType == 'gif') {
$newname .= '.gif';
$success = imagegif($thumb, $this->destination . $newname);
}
if ($success) {
$this->messages[] = "$newname created successfully.";
} else {
$this->messages[] = "Couldn't create a thumbnail for " .
basename($this->original);
}
imagedestroy($resource);
imagedestroy($thumb);
}
}
Class ThumbnailUpload
<?php
namespace PhotoProject;
use PhotoProject\Upload;
require_once 'Upload.php';
require_once 'Thumbnail.php';
class ThumbnailUpload extends Upload {
protected $thumbDestination;
protected $deleteOriginal;
protected $suffix = '_thb';
public function __construct($path, $deleteOriginal = false) {
parent::__construct($path);
$this->thumbDestination = $path;
$this->deleteOriginal = $deleteOriginal;
}
/*
** Setter method for the thumbnail destination
*/
public function setThumbDestination($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->thumbDestination = $path;
}
public function setThumbSuffix($suffix) {
if (preg_match('/\w+/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function allowAllTypes() {
$this->typeCheckingOn = true;
}
protected function createThumbnail($image) {
$thumb = new Thumbnail($image);
$thumb->setDestination($this->thumbDestination);
$thumb->setSuffix($this->suffix);
$thumb->create();
$messages = $thumb->getMessages();
$this->messages = array_merge($this->messages, $messages);
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add a message only if the original image is not deleted
if (!$this->deleteOriginal) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
}
// create a thumbnail from the uploaded image
$this->createThumbnail($this->destination . $filename);
// delete the uploaded image if required
if ($this->deleteOriginal) {
unlink($this->destination . $filename);
}
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Class Upload
<?php
namespace PhotoProject;
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $renameDuplicates;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->destination = $path;
}
public function setMaxSize($num) {
if (is_numeric($num) && $num > 0) {
$this->max = (int) $num;
}
}
public function allowAllTypes() {
$this->typeCheckingOn = false;
if (!$suffix) {
$this->suffix = ''; // empty string
}
}
public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
// deal with multiple uploads
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages() {
return $this->messages;
}
public function collectFilenames() {
return $this->collectednames;
}
public function getMaxSize() {
return number_format($this->max/1024, 1) . ' KB';
}
protected function checkFile($file) {
$accept = true;
if ($file['error'] != 0) {
$this->getErrorMessage($file);
// stop checking if no file submitted
if ($file['error'] == 4) {
return false;
} else {
$accept = false;
}
}
if (!$this->checkSize($file)) {
$accept = false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
$accept = false;
}
}
if ($accept) {
$this->checkName($file);
}
return $accept;
return true;
}
protected function checkName($file) {
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$extension = pathinfo($nospaces, PATHINFO_EXTENSION);
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
// rename file
$basename = pathinfo($name, PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
do {
$this->newName = $basename . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
} while (in_array($this->newName, $existing));
}
}
}
protected function getErrorMessage($file) {
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
$this->getMaxSize() . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially
uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' .
$file['name'];
break;
}
}
protected function checkSize($file) {
if ($file['error'] == 1 || $file['error'] == 2 ) {
return false;
} elseif ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is an empty file.';
return false;
} elseif ($file['size'] > $this->max) {
$this->messages[] = $file['name'] . ' exceeds the maximum size
for a file (' . $this->getMaxSize() . ').';
return false;
} else {
return true;
}
}
protected function checkType($file) {
if (in_array($file['type'], $this->permitted)) {
return true;
} else {
if (!empty($file['type'])) {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add the amended filename to the array of uploaded files
$this->filenames[] = $filename;
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}

Multiple uploads to multiple folders - PHP

I am attempting to upload multiple files into multiple folders. Unfortunately, with little success.
Any help would be greatly appreciated
I have two form fields:
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input name="menu" type="file" class="input_event noBorder" title="Upload Menu" />
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input name="img" type="file" class="input_event noBorder" title="Upload Img" />
I would like to use one for uploading images, and the other to upload pdf's and/or word docs.
I would also like for these two files to be saved into their corresponding folders (/imgs and /docs).
Some things i have tried
have tried to have two of these, each pointing to the correct path
have tried multiple classes to handle each file
have added array brackets to the input name field (ex: name="menu[]")
I imagine i need to change somethings in the class itself; however i am learning php and this class is cobbled together from 3 books, dozens of Google searches, and a few posts i found here on stack.
Exactly what i need to change is still far beyond me.
Relevant portion of on-page PHP code:
$max = 400000;
if (isset($_POST['submit'])) { //MAIN IF STATEMENT
$destination = './uploads/menus_up/';
try {
$upload = new Upload_File($destination);
$upload->move();
$result = $upload->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
Upload class:
class Upload_File {
protected $_uploaded = array();
protected $_destination;
protected $_max = 400000;
protected $_messages = array();
protected $_permitted = array('image/gif',
'image/jpeg',
'image/pjpeg',
'image/png');
protected $_renamed = false;
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function getMaxSize() {
return number_format($this->_max/1024, 1) . 'kB';
}
public function setMaxSize($num) {
if (!is_numeric($num)) {
throw new Exception("Maximum size must be a number.");
}
$this->_max = (int) $num;
}
public function move($overwrite = false) {
$field = current($this->_uploaded);
if (is_array($field['name'])) {
foreach ($field['name'] as $number => $filename) {
// process multiple upload
$this->_renamed = false;
$this->processFile($filename, $field['error'][$number], $field['size'][$number], $field['type'][$number], $field['tmp_name'][$number], $overwrite);
}
} else {
$this->processFile($field['name'], $field['error'], $field['size'], $field['type'], $field['tmp_name'], $overwrite);
}
}
public function getMessages() {
return $this->_messages;
}
protected function checkError($filename, $error) {
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
return true;
case 3:
$this->_messages[] = "Error uploading $filename. Please try again.";
return false;
case 4:
$this->_messages[] = 'No file selected.';
return false;
default:
$this->_messages[] = "System error uploading $filename. Contact webmaster.";
return false;
}
}
protected function checkSize($filename, $size) {
if ($size == 0) {
return false;
} elseif ($size > $this->_max) {
$this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
return false;
} else {
return true;
}
}
protected function checkType($filename, $type) {
if (empty($type)) {
return false;
} elseif (!in_array($type, $this->_permitted)) {
$this->_messages[] = "$filename is not a permitted type of file.";
return false;
} else {
return true;
}
}
public function addPermittedTypes($types) {
$types = (array) $types;
$this->isValidMime($types);
$this->_permitted = array_merge($this->_permitted, $types);
}
protected function isValidMime($types) {
$alsoValid = array('image/tiff',
'application/pdf',
'application/msword');
$valid = array_merge($this->_permitted, $alsoValid);
foreach ($types as $type) {
if (!in_array($type, $valid)) {
throw new Exception("$type is not a permitted MIME type");
}
}
}
protected function checkName($name, $overwrite) {
$nospaces = str_replace(' ', '_', $name);
if ($nospaces != $name) {
$this->_renamed = true;
}
if (!$overwrite) {
$existing = scandir($this->_destination);
if (in_array($nospaces, $existing)) {
$dot = strrpos($nospaces, '.');
if ($dot) {
$base = substr($nospaces, 0, $dot);
$extension = substr($nospaces, $dot);
} else {
$base = $nospaces;
$extension = '';
}
$i = 1;
do {
$nospaces = $base . '_' . $i++ . $extension;
} while (in_array($nospaces, $existing));
$this->_renamed = true;
}
}
return $nospaces;
}
protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
$OK = $this->checkError($filename, $error);
if ($OK) {
$sizeOK = $this->checkSize($filename, $size);
$typeOK = $this->checkType($filename, $type);
if ($sizeOK && $typeOK) {
$name = $this->checkName($filename, $overwrite);
$success = move_uploaded_file($tmp_name, $this->_destination . $name);
if ($success) {
$message = "$filename uploaded successfully";
if ($this->_renamed) {
$message .= " and renamed $name";
}
$this->_messages[] = $message;
} else {
$this->_messages[] = "Could not upload $filename";
}
}
}
}
}//END CLASS....Upload_Menu
Striped down class
protected $_uploaded = array();
protected $_destination;
protected $_max = 400000;
protected $_messages = array();
protected $_permitted = array('image/gif',
'image/jpeg',
'image/pjpeg',
'image/png');
protected $_renamed = false;
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function move() {
$field = current($this->_uploaded);
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
if ($success) {
$this->_messages[] = $field['name'] . ' uploaded successfully';
} else {
$this->_messages[] = 'Could not upload ' . $field['name'];
}
}
public function getMessages() {
return $this->_messages;
}
I would take a slightly different approach: Send a specific file to the constructor when you create your object like:
$upload = new Upload_File($_FILES['menu'], $destination);
Then you have all the information you need in your class and you don't have to access global variables from within your class.
You can then loop over your $_FILES array to add every file or put that in a different class.
It would require some rewriting in the class but it would make it more flexible and it would meet your needs.
SOLVED
So...for anyone who may come across this in the future, here is a less than elegant, but ultimately effective solution.
pathinfo($string, PATHINFO_EXTENSION) FTW!
I add a sorting mechanism to my processFile method and Wallah!
protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
$OK = $this->checkError($filename, $error);
if ($OK) {
$sizeOK = $this->checkSize($filename, $size);
$typeOK = $this->checkType($filename, $type);
if ($sizeOK && $typeOK) {
$name = $this->checkName($filename, $overwrite);
/************************ADDED HERE************************************/
if (pathinfo($filename, PATHINFO_EXTENSION) == 'pdf' || 'doc' || 'docx'){
$this->_destination = './uploads/menus_up/';
if (pathinfo($filename, PATHINFO_EXTENSION) == 'png' || 'jpeg' || 'gif'){
$this->_destination = './uploads/eventBG_up/';
/**********************************************************************/
$success = move_uploaded_file($tmp_name, $this->_destination . $name);
if ($success) {
$message = "$filename uploaded successfully";
if ($this->_renamed) {
$message .= " and renamed $name";
}
$this->_messages[] = $message;
} else {
$this->_messages[] = "Could not upload $filename";
}
}
}
}
}
}

how to validate multiple file upload field in php?

I'm trying to upload several files with their names in different field.
example--- there are 3 form fields for inserting names and 3 fields for uploading files in there respective order.
this is image attached, fr what i'm trying to achieve --
http://imgur.com/pGAlsjF
Now what i want is, when a user enters name in "document name" label in first field and selects a file to upload in "document file" label first field, then data gets inserted. else shows an error.
user should enter file name select file in there respective order, else it should show error.
it should error when a user enters name in first field and selects a file in second field then it should display error.
this is being done opencart admin section.
currently this is the simple code for simple validation --
foreach ($this->request->post['document_description'] as $language_id => $value) {
if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 64)) {
$this->error['name'][$language_id] = $this->language->get('error_name');
}
}
One thing is common between file name field and form upload field is "language id".
code for documents.php are ---
protected function getForm() {
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['entry_name'] = $this->language->get('entry_name');
$this->data['entry_filename'] = $this->language->get('entry_filename');
$this->data['entry_mask'] = $this->language->get('entry_mask');
$this->data['entry_remaining'] = $this->language->get('entry_remaining');
$this->data['entry_update'] = $this->language->get('entry_update');
$this->data['button_save'] = $this->language->get('button_save');
$this->data['button_cancel'] = $this->language->get('button_cancel');
$this->data['button_upload'] = $this->language->get('button_upload');
if (isset($this->error['warning'])) {
$this->data['error_warning'] = $this->error['warning'];
} else {
$this->data['error_warning'] = '';
}
if (isset($this->error['name'])) {
$this->data['error_name'] = $this->error['name'];
} else {
$this->data['error_name'] = array();
}
if (isset($this->error['filename'])) {
$this->data['error_filename'] = $this->error['filename'];
} else {
$this->data['error_filename'] = '';
}
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('catalog/documents', 'token=' . $this->session->data['token'] . $url, 'SSL'),
'separator' => ' :: '
);
if (!isset($this->request->get['document_id'])) {
$this->data['action'] = $this->url->link('catalog/documents/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
} else {
$this->data['action'] = $this->url->link('catalog/documents/update', 'token=' . $this->session->data['token'] . '&document_id=' . $this->request->get['document_id'] . $url, 'SSL');
}
$this->data['cancel'] = $this->url->link('catalog/documents', 'token=' . $this->session->data['token'] . $url, 'SSL');
$this->load->model('localisation/language');
$this->data['languages'] = $this->model_localisation_language->getLanguages();
if (isset($this->request->get['document_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
$document_info = $this->model_catalog_documents->getDocument($this->request->get['document_id']);
}
$this->data['token'] = $this->session->data['token'];
if (isset($this->request->get['document_id'])) {
$this->data['document_id'] = $this->request->get['document_id'];
} else {
$this->data['document_id'] = 0;
}
if (isset($this->request->post['document_description'])) {
$this->data['document_description'] = $this->request->post['document_description'];
} elseif (isset($this->request->get['document_id'])) {
$this->data['document_description'] = $this->model_catalog_documents->getDocumentDescriptions($this->request->get['document_id']);
} else {
$this->data['document_description'] = array();
}
if (isset($this->request->post['filename'])) {
$this->data['filename'] = $this->request->post['filename'];
} elseif (!empty($document_info)) {
$this->data['filename'] = $document_info['filename'];
} else {
$this->data['filename'] = '';
}
if (isset($this->request->post['mask'])) {
$this->data['mask'] = $this->request->post['mask'];
} elseif (!empty($document_info)) {
$this->data['mask'] = $document_info['mask'];
} else {
$this->data['mask'] = '';
}
if (isset($this->request->post['remaining'])) {
$this->data['remaining'] = $this->request->post['remaining'];
} elseif (!empty($document_info)) {
$this->data['remaining'] = $document_info['remaining'];
} else {
$this->data['remaining'] = 1;
}
if (isset($this->request->post['update'])) {
$this->data['update'] = $this->request->post['update'];
} else {
$this->data['update'] = false;
}
$this->template = 'catalog/documents_form.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
protected function validateForm() {
if (!$this->user->hasPermission('modify', 'catalog/documents')) {
$this->error['warning'] = $this->language->get('error_permission');
}
print_r($this->request->post['document_description']); echo "<br>";
print_r($this->request->files['document_files']); echo "<br>";
foreach ($this->request->files['document_files'] as $files => $value)
{
print_r($files.'==>'.print_r($value)); echo "<br>";
}die;
foreach ($this->request->post['document_description'] as $language_id => $value) {
foreach ($this->request->files['document_files'] as $selected => $filename)
{
if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 64))
{
$this->error['name'][$language_id] = $this->language->get('error_name');
}
if (empty($filename))
{
$this->error['name'][$language_id] = $this->language->get('error_name');
}
}
}
if (!$this->error) {
return true;
} else {
return false;
}
}
public function upload() {
$this->language->load('sale/order');
$json = array();
if (!$this->user->hasPermission('modify', 'catalog/documents')) {
$json['error'] = $this->language->get('error_permission');
}
if (!isset($json['error'])) {
if (!empty($this->request->files['file']['name'])) {
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array();
$filetypes = explode("\n", $this->config->get('config_file_extension_allowed'));
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array();
$filetypes = explode("\n", $this->config->get('config_file_mime_allowed'));
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!isset($json['error'])) {
if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$ext = md5(mt_rand());
$json['filename'] = $filename . '.' . $ext;
$json['mask'] = $filename;
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
}
$json['success'] = $this->language->get('text_upload');
}
$this->response->setOutput(json_encode($json));
}
Place the document name fields next to the document file field and hide it at first. Then display the document name fields when file is selected (jQuery - Detecting if a file has been selected in the file input).
In admin/controller/catalog/product.php, there is a function: validateForm where all validations are done. Within that function a foreach is used for language based validations:
foreach ($this->request->post['product_description'] as $language_id => $value) {
...........
//add your validation code here like:
if (trim($value['download_name']) == '' && $value['download_file'] == '' ) {
$this->error['downloadfile'][$language_id] = $this->language->get('error_ownloadfile');
}
...........
}// end of foreach

Categories