check extension in cakephp 3 - cakephp

I want to upload only jpg, jpeg and png type images. That's why I want to check extension of uploading images. All files which extension is updated like .exe file is updated as .jpg or .png file then it allow to upload but I want to prevent it and upload only original images.
How can I do it in Cakephp 3
My Controller is
if(h($this->request->data['image']['name']) != '')
{
$ext = substr(strtolower(strrchr($this->request->data['image']['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
if (in_array($ext, $arr_ext))
{
$extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
if($extension=='jpg' || $extension=='jpeg' || $extension=='png')
{
if ($this->request->data['image']['size'] < '26214400')
{
$randno = rand(0,100);
$filenameArr = explode('.' , h($this->request->data['image']['name']));
$namefile = $filenameArr[0].$randno;
$extfile = $filenameArr[1];
$filename = WWW_ROOT .'uploads/users/'.$namefile.'.'.$extfile;
move_uploaded_file($this->request->data['image']['tmp_name'], $filename);
$upload = $namefile.'.'.$extfile;
$newData['image'] = $upload;
}
}
else
{
$this->Flash->error(__('Please upload only jpg or jpeg or png type image '));
return $this->redirect(['action' => 'edit', $id]);
}
}
else
{
$this->Flash->error(__('Please only upload images (jpeg, png, jpg).'));
return $this->redirect(['action' => 'edit', $id]);
}
}
But It's only executing else condition even when i put correct extension.

Related

My photo gallery I upload multiple image with encrypted name, But I want to save these encrypted name in database

My codeigniter photo gallery upload multiple image in single click. Image upload with encrypted name but name save in database original image name.I want to save in database those encrypted name.
My controller code is:
public function file_upload2(){
if($this->session->userdata('is_loged_in')){
$config = array();
$config['image_library'] = 'gd2';
$config['upload_path'] = './photo/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPG';
$config['max_size'] = 0;
$config['maintain_ratio'] = FALSE;
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$this->form_validation->set_rules('category', 'Category', 'required|trim');
if ($this->form_validation->run() == TRUE){
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++){
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$category = $this->input->post('category');
$fileName = implode(',',$images);
$this->Upload_model->upload_image($fileName,$category);
if($this->upload->do_upload()){
$this->success();
} else {
$this->index();
}
} else {
$this->index();
}
} else {
redirect('admin');
}
}
My Model:
public function upload_image($fileName,$category){
if($fileName!='' ){
$filename1 = explode(',',$fileName);
foreach($filename1 as $file){
$file_data = array(
'name' => $file,
'datetime'=> date('Y-m-d h:i:s'),
'category'=> $category
);
$this->db->insert('photo', $file_data);
}
}
}
When you uploading, use the codeigniter's upload data, since php $_FILES array doesn't know anything about the encrypted name:
if ($this->upload->do_upload()) {
$data = $this->upload->data();
echo $data['file_name']; // Here is the encrypted filename
}

File upload does not work on cakePHP 2.x

I am trying to upload the user pictures, but with the following example nothing is getting saved into the database and no errors are given. I know that the validation has to be done and it will once I get the files to be stored.
Here are the snippets from the view file:
<?php
echo $this->Form->create('User', array('enctype' => 'multipart/form-data'));
echo $this->form->input('upload', array('type' => 'file'));
echo $this->Form->end('Submit');
?>
The controller:
public function add() {
if ($this->request->is('post')) {
if(!empty($this->data['User']['upload']['name'])){
$file = $this->data['User']['upload'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/users/' . $file['name']);
$this->data['User']['image'] = $file['name'];
}
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The employee has been saved');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The employee could not be saved. Please, try again.');
}
}
}
change your view like this
<?php echo $this->Form->file('Document.submittedfile'); ?>
and your controller like this
public function fileupload() {
if ($this->request->is('post') || $this->request->is('put')) {
//die();
$file = $this->request->data['Document']['submittedfile'];
//$this->pdfadd1->save($this->request->data);
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/cakephp3/cakephp1/cakephp/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for the submission'));
return $this->redirect(array('controller' => 'users','action' => 'index'));
}
}
dnt forget to create a folder in webroot or in any other place(for uploaded files)
Check the following link :
http://www.jamesfairhurst.co.uk/posts/view/uploading_files_and_images_with_cakephp
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}

CakePHP 1.3 and Uploadifive/Uploadify - Change Upload Filename to a random string

I have somehow implemented UPLOADIFIVE in my CakePHP application. Everything seems to work great including uploading multiple files and inserting the correct information in the Database.
Based on the following code, I would like to UPLOAD AND SAVE EVERY FILE WITH A RANDOM NAME TAKING INTO ACCOUNT THE CURRENT DATE OR SOMETHING SIMILAR.
How could I accomplish this?
In my Photos Controller I have the following function:
// This function is called at every file upload. It uploads the file onto the server
// and save the corresponding image name, etc, to the database table `photos`.
function upload() {
$uploadDir = '/img/uploads/photos/';
if (!empty($_FILES)) {
debug($_FILES);
$tempFile = $_FILES['Filedata']['tmp_name'][0];
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$targetFile = $uploadDir . $_FILES['Filedata']['name'][0];
// Validate the file type
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions
$fileParts = pathinfo($_FILES['Filedata']['name'][0]);
// Validate the filetype
if (in_array($fileParts['extension'], $fileTypes)) {
// Save the file
move_uploaded_file($tempFile,$targetFile);
$_POST['image'] = $_FILES['Filedata']['name'][0];
$this->Photo->create();
if ($this->Photo->save($_POST)) {
$this->Session->setFlash($targetFile, 'default', array('class' => 'alert_success'));
$this->redirect(array('action' => 'index'));
}
} else {
// The file type wasn't allowed
//echo 'Invalid file type.';
$this->Session->setFlash(__('The photo could not be saved. Please, try again.', true));
}
}
}
In my View file - admin_add.ctp I have added the following function
$('#file_upload').uploadifive({
'auto' : false,
'uploadScript' : '/photos/upload',
'buttonText' : 'BROWSE FILES',
'method' : 'post',
'onAddQueueItem' : function(file) {
this.data('uploadifive').settings.formData = { 'photocategory_id' : $('#PhotoPhotocategoryId').val() };
}
});
<input type="file" name="file_upload" id="file_upload" />
function upload() {
$uploadDir = '/img/uploads/photos/';
if (!empty($_FILES)) {
debug($_FILES);
// $tempFile = $_FILES['Filedata']['tmp_name'][0];
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$targetFile = $uploadDir . $_FILES['Filedata']['name'][0];
// Validate the file type
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions
$fileParts = pathinfo($_FILES['Filedata']['name'][0]);
// Validate the filetype
if (in_array($fileParts['extension'], $fileTypes)) {
// Save the file
$tempFile = time()."_".basename($_FILES['Filedata']['name'][0]);
$_POST['image'] = $tempFile;
move_uploaded_file($tempFile,$targetFile);
$this->Photo->create();
if ($this->Photo->save($_POST)) {
$this->Session->setFlash($targetFile, 'default', array('class' => 'alert_success'));
$this->redirect(array('action' => 'index'));
}
} else {
// The file type wasn't allowed
//echo 'Invalid file type.';
$this->Session->setFlash(__('The photo could not be saved. Please, try again.', true));
}
}
}
Chetanspeed thanks so much for quickly helping out with this. Based on his solution I was able to make it work. Below is the code that worked for me which is slightly different than Chetanspeed
function upload() {
$uploadDir = '/img/uploads/photos/';
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'][0]; // Temp file should not be changed since it contains the physical location of the file /tmp/file.jpg
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$randomString = time(); // Save this random string to a variable
$targetFile = $uploadDir . $randomString."_".basename($_FILES['Filedata']['name'][0]); //randomString is added to target...
// Validate the file type
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions
$fileParts = pathinfo($_FILES['Filedata']['name'][0]);
// Validate the filetype
if (in_array($fileParts['extension'], $fileTypes)) {
//image name posted to database containing the randomString generated from time...thanks Chetanspeed
$_POST['image'] = $randomString."_".basename($_FILES['Filedata']['name'][0]);
move_uploaded_file($tempFile,$targetFile);
$this->Photo->create();
if ($this->Photo->save($_POST)) {
$this->Session->setFlash($targetFile, 'default', array('class' => 'alert_success'));
$this->redirect(array('action' => 'index'));
}
} else {
// The file type wasn't allowed
//echo 'Invalid file type.';
$this->Session->setFlash(__('The photo could not be saved. Please, try again.', true));
}
}
}

codeigniter file upload - optional?

I'm sure this is simple but I can't see how to make uploading a file with CI optional.
If you leave the file input box empty, the error "You didn't choose an upload file" appears.
The reason I want it to be optional is that my form edits a directory type listing, and I don't need to upload the image each time I edit the listing.
Is there a way to remove the "required" error handling on the file class
Use the following:
<?php if ( $_FILES AND $_FILES['field_name']['name'] )
{
// Upload the file
}
codeigniter file upload optionally ...works perfect..... :)
---------- controller ---------
function file()
{
$this->load->view('includes/template', $data);
}
function valid_file()
{
$this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');
if ($this->form_validation->run()==FALSE)
{
$this->file();
}
else
{
$config['upload_path'] = './documents/';
$config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile',FALSE))
{
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if($_FILES['userfile']['error'] != 4)
{
return false;
}
}
else
{
return true;
}
}
i just use this lines which makes it optionally,
if($_FILES['userfile']['error'] != 4)
{
return false;
}
$_FILES['userfile']['error'] != 4 is for file required to upload.
you can u make it unneccessory by using $_FILES['userfile']['error'] != 4 , then it will pass this error for file required and
works great with other types of errors if any by using return false ,
hope it works for u ....
Use this code in the controller before calling do_upload()
if (is_uploaded_file($_FILES['field_name']['tmp_name'])) {
// your code here
}
Use This Code :-
$config['upload_path'] = 'assets/img/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
// Upload the file
if ($this->upload->do_upload('Image')){
$dataimage = $this->upload->data();
$data = array(
'image' => $dataimage['file_name'],
'UserName' => $this->input->post('UserName'),
'Password' => $this->input->post('Password'),
'xid' => $this->input->post('xid')
);
}
else{
/*$out['msg'] = show_err_msg($this->upload->display_errors());
echo json_encode($out);
exit();*/
$data = array(
'image' => NULL,
'UserName' => $this->input->post('UserName'),
'Password' => $this->input->post('Password'),
'xid' => $this->input->post('xid')
);
}

file upload cakephp

when uploading an image to the server using cakephp
$this->Model->Behaviors->attach('ImageUpload', Configure::read('photo.files'));
photo uploaded successfully, and the database fields also
but shows following error instead of returning to index page.
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 104]
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 107]
Warning (2): Cannot modify header information - headers already sent by (output started at E:\umoorthy_105act10\projects\dev1base\core\cake\basics.php:111) [CORE\cake\libs\controller\controller.php, line 614]
wat to do?
Cake has already wrote where to look for a problem
Configure::read('photo.files')
do following to check if everything is ok
pr(Configure::read('photo.files'))
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative echo "<pre>"; print_r($formdata); exit;
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}

Resources