I am working on a web application where the user can upload photos.
I already have a PHP code where I can upload the photos to a folder in the server directory. However, the main issue I have with my code is that it keeps the original file name of the photo from before it was uploaded and after it was uploaded. My problem with that is when there are two different photos with the same file name, I'd have conflicts when they get uploaded.
Here is my code:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once '_common.php';
$config = require_once '_config.php';
$fileName = '';
$mimeType = '';
$fileSize = 0;
if (empty($_FILES)) {
_error('No file received');
}
$pathArray = array();
foreach ($_FILES as $fileName => $fileData) {
if (!isset($fileData['error']) ||
is_array($fileData['error'])) {
die(json_encode(array(
'success' => false,
'status' => "Invalid Parameters.",
'files' => $_FILES
)));
}
switch ($fileData['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
die(json_encode(array(
'success' => false,
'status' => "No file sent.",
'files' => $_FILES)));
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
die(json_encode(array(
'success' => false,
'status' => "Exceeded filesize limit.",
'files' => $_FILES)));
default:
die(json_encode(array(
'success' => false,
'status' => "Unknown errors.",
'files' => $_FILES)));
}
// You should also check filesize here.
if ($fileData['size'] > 1000000) {
die(json_encode(array(
'success' => false,
'status' => "Exceeded File Size Limit.",
'files' => $_FILES)));
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($fileData['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',),
true)) {
die(json_encode(array(
'success' => false,
'status' => "Invalid file format.",
'files' => $_FILES)));
}
if (!move_uploaded_file(
$fileData['tmp_name'],
sprintf('./gallery/%s',
basename($fileData['name'])) )) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file.",
'files' => $_FILES)));
}
$uploaddir = '/gallery/';
$name = $fileData["tmp_name"];
$fullPath = sprintf('gallery/%s.%s',
basename($fileData['tmp_name']),
$ext
array_push($pathArray, $fullPath);
}
print_r(json_encode(array(
'success' => true,
'status' => "File is uploaded successfully.",
'filePath' => "$fullPath"
)));
?>
I've lost my touch in PHP, however, this is what I've tried:
if (!move_uploaded_file(
$fileData['tmp_name'],
sprintf('gallery/%s.%s',
sha1_file($_FILES['fileToUpload']['tmp_name'],
$ext)
)) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file.",
'files' => $_FILES)));
}
And should that go through, I changed $fullPath to fit the new destination I want:
$fullPath = sprintf('gallery/%s.%s',
sha1_file($_FILES['fileToUpload']['tmp_name'],
$ext);
However, none of those seemed to work.
My objective is to give the uploaded files a more or less unique file name, however, I can't seem to make sha1_file work.
I wonder if sha1_file can be made to work, or perhaps there's another way to change the destination file name in such a way I'll end up a unique file name (using date and time for example).
You could use microtime() or uniqid() functions to concatenate with your file name:
if (!move_uploaded_file(
$fileData['tmp_name'],
sprintf('gallery/%s.%s',
uniqid() . '_' . $_FILES['fileToUpload']['tmp_name'],
$ext)
)) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file.",
'files' => $_FILES)));
}
See uniqid documentation for more information about uniqid.
Related
I am uploading multiple images and I need to get their different file format.
But the problem is i only got the first file image format and there's an error when I do resize images because of the incorrect file format.
I am having an error The filetype you are attempting to upload is not allowed. which occur when I put the PATHINFO_EXTENSION when getting file.
Here's my code
for($i = 0; $i < $count_upload; $i++) {
$_FILES['userfile']['name'] = pathinfo($_FILES['product_image']['name'][$i], PATHINFO_EXTENSION);
$_FILES['userfile']['type'] = $_FILES['product_image']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['product_image']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['product_image']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['product_image']['size'][$i];
$file_name = $file_name;
$config = array(
'file_name' => $file_name,
'allowed_types' => 'jpg|jpeg|png',
'max_size' => 3000,
'overwrite' => TRUE,
'encrypt_name' => FALSE,
'remove_spaces' => TRUE,
'upload_path'
=> $directory
// => './assets/img/products'
);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$response = array(
'status' => false,
'environment' => ENVIRONMENT,
'message' => $error['error'],
'csrf_name' => $this->security->get_csrf_token_name(),
'csrf_hash' => $this->security->get_csrf_hash()
);
echo json_encode($response);
die();
}else {
$file_name = $this->upload->data()['file_name'];
echo $file_name;
echo '<br>';
I have an input where you can upload images, the only allowed images types are:
png, jpg, jpeg
before the image is inserted to the database it checks if the pictures are png,jpg,jpeg. But now for security reasons I need to check the mime type before or after the first check.
How do I do this? This is my code:
<?php
$iAmountOfFiles = count($_FILES['Filename']['name']);
while($iAmountOfFiles >= 1) {
$iAmountOfFiles--;
$aFileProperties = pathinfo($_FILES['Filename']['name'][$iAmountOfFiles]);
if(!in_array(strtolower($aFileProperties["extension"]), $aExtensionWhitelist)) {
echo "Bestands type niet toegestaan";
// exit;
continue;
}
$sTarget = ROOT.BACKEND."/pages/bezienswaardigheden-toevoegen/uploads/";
$sUniqueFileNameHash = hash('adler32', time().rand());
$Filename = basename($sUniqueFileNameHash."-".$_FILES['Filename']['name'][$iAmountOfFiles]);
$Filename = basename($aFileProperties["filename"]."-".$sUniqueFileNameHash.".".strtolower($aFileProperties["extension"]));
// Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'][$iAmountOfFiles], $sTarget.$Filename)) {
// here needs to come the mime check
To get MIME type, developers generally depend on $_FILES['input_name']['type']. But this is absolutely vulnerable. Because a malicious user can set one of image/jpg, image/png, image/gif etc. MIME types to a file that is not actually an image. In that case, the malicious user may get your script pass to upload other files instead of an image and execute your script for their purposes which is dangerous.
So I recommend that you not depend on the following snippet to get MIME of a file
$_FILES['input_name']['type'];
Rather I would recommend that you use this mime_content_type() function to get MIME type but with the help of other PHP's built-in functions. And that is is_uploaded_file() function. What it does is:
This is useful to help ensure that a malicious user hasn't tried to
trick the script into working on files upon which it should not be
working--for instance, /etc/passwd.
This sort of check is especially important if there is any chance that
anything done with uploaded files could reveal their contents to the
user, or even to other users on the same system.
So to make this function work properly it needs a specific argument. Check out the code below:
if (is_uploaded_file($_FILES['input_name']['tmp_name'])) {
// Do other stuff.
}
This function returns true on success, false otherwise. So if it returns true then you're ok with the file. Thanks to this function. Now mime_content_type() function comes into play. How? Look at the code below:
if (is_uploaded_file($_FILES['input_name']['tmp_name'])) {
// Notice how to grab MIME type.
$mime_type = mime_content_type($_FILES['input_name']['tmp_name']);
// If you want to allow certain files
$allowed_file_types = ['image/png', 'image/jpeg', 'application/pdf'];
if (! in_array($mime_type, $allowed_file_types)) {
// File type is NOT allowed.
}
// Set up destination of the file
$destination = '/path/to/move/your/file/';
// Now you move/upload your file
if (move_uploaded_file ($_FILES['input_name']['tmp_name'] , $destination)) {
// File moved to the destination
}
}
BTW, for novice, do not try remote URL with this function to get MIME type. The code below will not work:
mime_content_type('http://www.example.com/uploads/example.png');
But the one below would work:
mime_content_type('/source/to/your/file/etc.png');
Hope you would enjoy uploading files from now on.
you can get mime type by file content:
public static function getMimeTypeFromFileContent(string &$content): string
{
return (new finfo(FILEINFO_MIME_TYPE))->buffer($content);
}
file content you can get by $content = file_get_contents($pathToFile);
Using above simple [ you can say bigger one 🤪 ] function, you can extract or get the mime type of a file or you can say content.
But before, for using this function you might have need done some pre-configuration,
Like you have to sure that you turned or configured curl extension, filesystem releted extension and finfo extension in php.ini file.
Here, I am describing the whole process of this function in a short.
First, we are storing all the updated mime type as an array from official apache mime type url.
You can also get this mime type file in your apache conf directory
insted of using url. In this function we are using live url to get all the mime type.
But the zeroth process for this function is to validate that apache url is live or not.
After validating the url, if the url is validated [ means live ], we store all mimes from that url as an array called $mimes
If the url isn't live or exist we are manually making an array with some common extension available.
Then we validate the content as file.
Then we check the PHP pathinfo function to insure that is there any file extension or not. If there, store it.
After that we checking the $mimes array with our content extension as $mimes array index.
Finally we are returning the index value of $mimes array as content mime type through $content_mime variable.
That's it.
<?php
/**
* **get_content_mime_type
*
* #param string $content, the content or the file whose mime type you want to know.
* #return string
*/
function get_content_mime_type($content)
{
$url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';
$url_live = false;
$handle = curl_init($url);
curl_setopt_array($handle, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
));
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode == 200)
{
$url_live = true;
}
$url_live = $url_live;
curl_close($handle);
$mimes = array();
if ($url_live)
{
$mimes_file = file_get_contents($url);
preg_match_all('#^([^\s]{2,}?)\s+(.+?)$#ism', $mimes_file, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$exts = explode(" ", $match[2]);
foreach ($exts as $ext)
{
$mimes[$ext] = $match[1];
}
}
}
else
{
$mimes = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
}
$content_mime = 'unknown';
if (is_file($content))
{
if (isset(pathinfo($content) ['extension']))
{
$content_ext = pathinfo($content) ['extension'];
if (isset($mimes[$content_ext]))
{
$content_mime = $mimes[$content_ext];
}
else
{
if (is_readable($content) && is_executable($content))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$content_mime = finfo_file($finfo, $content);
if ($content_mime === null | $content_mime === "")
{
$content_mime = "application/octet-stream";
}
else
{
$content_mime = $content_mime;
}
finfo_close($finfo);
}
else
{
$content_mime = "application/octet-stream";
}
}
}
}
else
{
// return whatever you want
// $content_mime = 'unknown';
}
$content_mime = $content_mime;
return $content_mime;
}
?>
I am building an ExtJS4 web application and I have a part where I can successfully upload multiple files in a folder in my file director. I used Ivan Novakov's library to achieve this.
I created a button and in that button's handler, I had this code:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploader : 'Ext.ux.upload.uploader.FormDataUploader',
uploaderOptions : {
url : 'uploadGallery.php'
},
synchronous : true
});
var uploadDialog = Ext.create('Ext.ux.upload.Dialog', {
dialogTitle : 'My Upload Dialog',
panel : uploadPanel
});
this.mon(uploadDialog, 'uploadcomplete', function(uploadPanel, manager, items, errorCount) {
console.log('manager = ' + manager);
console.log('items = ' + items);
console.log('manager result = ' + manager.result);
console.log('manager result message = ' + manager.message);
console.log('manager status = ' + manager.status);
console.log('manager filePath = ' + manager.filePath);
}, this);
uploadDialog.show();
I have my own PHP file upload handler as such:
<?php
require_once '_common.php';
$config = require_once '_config.php'; //require __DIR__ . '/_config.php';
$fileName = '';
$mimeType = '';
$fileSize = 0;
if (empty($_FILES)) {
_error('No file received');
}
$pathArray = array();
foreach ($_FILES as $fileName => $fileData) {
if (
!isset($fileData['error']) ||
is_array($fileData['error'])
) {
die(json_encode(array(
'success' => false,
'status' => "Invalid Parameters.",
'files' => $_FILES
)));
}
// Check $_FILES['fileToUpload']['error'] value.
switch ($fileData['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
die(json_encode(array(
'success' => false,
'status' => "No file sent.",
'files' => $_FILES
)));
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
die(json_encode(array(
'success' => false,
'status' => "Exceeded filesize limit.",
'files' => $_FILES
)));
default:
die(json_encode(array(
'success' => false,
'status' => "Unknown errors.",
'files' => $_FILES
)));
}
// You should also check filesize here.
if ($fileData['size'] > 1000000) {
die(json_encode(array(
'success' => false,
'status' => "Exceeded File Size Limit.",
'files' => $_FILES
)));
}
// DO NOT TRUST $_FILES['fileToUpload']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($fileData['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
die(json_encode(array(
'success' => false,
'status' => "Invalid file format.",
'files' => $_FILES
)));
}
// You should name it uniquely.
// DO NOT USE $_FILES['fileToUpload']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$fileData['tmp_name'],
sprintf('./gallery/%s.%s',
basename($fileData['tmp_name']),
$ext
)
)) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file.",
'files' => $_FILES
)));
}
// $uploadFile = sprintf('./gallery/%s.%s',
// sha1_file($_FILES['fileToUpload']['tmp_name']);
$uploaddir = '/gallery/';
$name = $fileData["tmp_name"];
$fullPath = sprintf('gallery/%s.%s',
basename($fileData['tmp_name']),
$ext
);
array_push($pathArray, $fullPath);
// echo '{"success": true, "status": "file Uploaded successfully", "filePath" : "$filePath"}';
// _response(true, sprintf("%s", $fullPath));
// echo(json_encode(array(
// 'success' => true,
// 'status' => "File is uploaded successfully.",
// 'filePath' => "$fullPath"
// )));
}
//_log(sprintf("[multipart] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $fileSize));
// _response(true, $pathArray);
print_r(json_encode(array(
'success' => true,
'status' => "File is uploaded successfully.",
'filePath' => "$fullPath"
)));
?>
I didn't change much of his _common.php and _config.php which can be found here.
As you can see, at my PHP part, I am trying to send the filePath of the uploaded file back to the ExtJS part, I need this for a database entry process. However, I don't know how to obtain this JSON Object back in my ExtJS code as the function only has 4 arguments (uploadPanel, manager, items, errorCount) and so far I haven't had luck guessing which one would contain the JSON response.
I found a rather crude workaround to this issue. What I did was that I used the original filenames of the files uploaded as the filenames in the server's file system. This is NOT a good solution. If you need to save the filename to a database and the filename is a SQL Injection, then you'll have problems.
// You should name it uniquely.
// DO NOT USE $_FILES['fileToUpload']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
move_uploaded_file(
$fileData['tmp_name'],
sprintf('./gallery/%s',
basename($fileData['name'])
In this case $_FILES['fileToUpload']['name'] is $fileData['name'], check the start of my foreach loop.
As mentioned you shouldn't really use $_FILES['fileToUpload']['name'] without checking and validating it first.
This question will still be open for answers.
Good day. I am uploading an image file to my php server. I am successfully uploading the file to a folder. What I want to do now is as I assemble my JSON response, I want to get the new file path of the file so I would know where it is programatically.
Here is my php code so far:
<?php
header('Content-Type: text/html; charset=utf-8');
if (
!isset($_FILES['fileToUpload']['error']) ||
is_array($_FILES['fileToUpload']['error'])
) {
die(json_encode(array(
'success' => false,
'status' => "Invalid Parameters. - 1",
'files' => $_FILES
)));
}
// Check $_FILES['fileToUpload']['error'] value.
switch ($_FILES['fileToUpload']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
die(json_encode(array(
'success' => false,
'status' => "No file sent. - 2",
'files' => $_FILES
)));
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
die(json_encode(array(
'success' => false,
'status' => "Exceeded filesize limit. - 3",
'files' => $_FILES
)));
default:
die(json_encode(array(
'success' => false,
'status' => "Unknown errors. - 4",
'files' => $_FILES
)));
}
// You should also check filesize here.
if ($_FILES['fileToUpload']['size'] > 1000000) {
die(json_encode(array(
'success' => false,
'status' => "Exceeded File Size Limit. - 5",
'files' => $_FILES
)));
}
// DO NOT TRUST $_FILES['fileToUpload']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['fileToUpload']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
die(json_encode(array(
'success' => false,
'status' => "Invalid file format. - 6",
'files' => $_FILES
)));
}
// You should name it uniquely.
// DO NOT USE $_FILES['fileToUpload']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['fileToUpload']['tmp_name'],
sprintf('./gallery/%s.%s',
sha1_file($_FILES['fileToUpload']['tmp_name']),
$ext
)
)) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file. - 7",
'files' => $_FILES
)));
}
$filePathFull = sprintf('./gallery/%s.%s',
sha1_file($_FILES['fileToUpload']['tmp_name']);
$uploaddir = '/gallery/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);
die(json_encode(array(
'success' => true,
'status' => "File is uploaded successfully. - 8",
'files' => $_FILES,
'filePath' => $uploadfile
)));
?>
I am trying to get the new file path which is /gallery/ + the filename, however, I am getting an invalid JSON Object when I process it in my ExtJS part.
Can anyone help me with my problem? I also tried sprintf('./gallery/%s.%s', sha1_file($_FILES['fileToUpload']['tmp_name']); but that doesn't seem to work.
Any help is very much appreciated.
Edit:
So far this works:
$uploaddir = '/gallery/';
$uploadFile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);
die(json_encode(array(
'success' => true,
'status' => "File is uploaded successfully. - 8",
'filePath' => $uploadFile
)));
However, I don't have the file extension and I get something like: /gallery/phptnLZJm but upon checking, an image is actually uploaded but the filename is off.
I made it work. I think it sha1_file was the issue. The code is now:
if (!move_uploaded_file(
$_FILES['fileToUpload']['tmp_name'],
sprintf('./gallery/%s.%s',
basename($_FILES['fileToUpload']['tmp_name']),
$ext
)
)) {
die(json_encode(array(
'success' => false,
'status' => "Failed to move uploaded file. - 7",
'files' => $_FILES
)));
}
// $uploadFile = sprintf('./gallery/%s.%s',
// sha1_file($_FILES['fileToUpload']['tmp_name']);
$uploaddir = '/gallery/';
// $uploadFile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);
$name = $_FILES["fileToUpload"]["tmp_name"];
$fullPath = sprintf('/gallery/%s.%s',
basename($_FILES['fileToUpload']['tmp_name']),
$ext
);
die(json_encode(array(
'success' => true,
'status' => "File is uploaded successfully. - 8",
'filePath' => "$fullPath"
)));
Before, I would call sha1_file instead of basename as I am assembling my $fullPath, and I don't know why. Was it because it was moved already and now has a different name?
I'm very new on cakephp and I try to make an edit function with file replacement but it isn't working. If the file already exists I get an error message.
This is my admin_edit.ctp code:
<td>
<?php if (!empty($this->data['Stock']['filepath'])): ?>
<div class="input">
<label>Uploaded File</label>
<?php
echo $this->Form->input('filepath', array('type'=>'hidden', 'label' => false));
echo $this->Html->link(basename($this->data['Stock']['filepath']),
$this->data['Stock']['filepath']);
?>
</div>
<?php else: ?>
<?php echo $this->Form->input('filename',array('type' => 'file', 'label' => false)); ?>
<?php endif; ?>
</td>
here below stock.php validation code
public $validate = array(
'filename' => array(
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::uploadError
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload - filename error',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::mimeType
'mimeType' => array(
'rule' => array('mimeType', array('image/gif','image/png','image/jpg','image/jpeg')),
'message' => 'Invalid file, only images allowed',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// custom callback to deal with the file upload
'processUpload' => array(
'rule' => 'processUpload',
'message' => 'Something went wrong processing your file - process error',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
)
processUpload :
public function processUpload($check=array()) {
// deal with uploaded file
if (!empty($check['filename']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['filename']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['filename']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['filename']['name'], PATHINFO_EXTENSION);
// #todo check for duplicate filename
// try moving file
if (!move_uploaded_file($check['filename']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
}
}
return TRUE;
}
Error message :"Something went wrong with the file upload - filename error"
Before saving :
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['filename'] = $this->data[$this->alias]['filepath'];
foreach (array_keys($this->hasAndBelongsToMany) as $model){
if(isset($this->data[$this->name][$model])){
$this->data[$model][$model] = $this->data[$this->name][$model];
unset($this->data[$this->name][$model]);
}
}
}
return parent::beforeSave($options);
Does anyone help me to find mistake ?
Thanks