File upload does not work on cakePHP 2.x - cakephp

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;
}

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
}

Backup an entire website and database using PHP

I've been at this for a bit now and this is the closest I've gotten to backing up an entire site and database with PHP. The issue is I can't figure out why I continue to receive errors on lines 145 and 154.
Error:Notice: Undefined variable: arr_zip in C:\xampp\htdocs\wordpress\backup.php on line 145
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\backup.php on line 145
Notice: Undefined variable: delete_zip in C:\xampp\htdocs\wordpress\backup.php on line 154
<?php
ini_set ("max_execution_time", 0);
$dir = "site-backup-stark";
if(!(file_exists($dir)))
{
mkdir($dir, 0777);
}
$host = "localhost"; //host name
$username = "wordpress_user"; //username
$password = "pasword99"; // your password
$dbname = "wordpress_db"; // database name
$zip = new ZipArchive();
backup_tables($host, $username, $password, $dbname);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$con = mysql_connect($host,$user,$pass);
mysql_select_db($name,$con);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = "";
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "nn".$row2[1].";nn";
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#n#","n",$row[$j]);
if (isset($row[$j]))
{
$return.= '"'.$row[$j].'"' ;
}
else
{
$return.= '""';
}
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");n";
}
$return.="nnn";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
if (glob("*.sql") != false)
{
$filecount = count(glob("*.sql"));
$arr_file = glob("*.sql");
for($j=0;$j<$filecount;$j++)
{
$res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
if ($res === TRUE)
{
$zip->addFile($arr_file[$j]);
$zip->close();
unlink($arr_file[$j]);
}
}
}
//get the current folder name-start
$path = dirname($_SERVER['PHP_SELF']);
$position = strrpos($path,'/') + 1;
$folder_name = substr($path,$position);
//get the current folder name-end
$zipname = date('Y/m/d');
$str = "stark-".$zipname.".zip";
$str = str_replace("/", "-", $str);
// open archive
if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE)
{
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../$folder_name/"));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value)
{
if( strstr(realpath($key), "stark") == FALSE)
{
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
if(glob("*.sql.zip") != false)
{
$filecount = count(glob("*.sql.zip"));
$arr_file = glob("*.sql.zip");
for($j=0;$j<$filecount;$j++)
{
unlink($arr_file[$j]);
}
}
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
{
if (strstr($value, "stark"))
{
$delete_zip[] = $value;
copy("$value", "$dir/$value");
}
}
for ($i=0; $i < count($delete_zip); $i++) //error here
{
unlink($delete_zip[$i]);
}
?>
In this block of code:
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
If your call to glob("*.zip") returns a 'falsey' value your variable $arr_zip won't be initialised and you'll get an error in the foreach that follows it. Check for false explicitly with
if(glob("*.zip") !== false)
If this continues to fail you need to investigate why glob() is failing. I don't have a suggestion for that.
Later, you haven't initialised $delete_zip at all, somewhere you need
$delete_zip = array();

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));
}
}
}

Drupal 7.14: Preprocess search block form gives me a blank form to render in $search_form

I've started working on a theme from scratch, I've tried to replace the title of the textfield but when imploding the search variable into search_form, the result is blank. Any error that I could be missing?
`function mytheme_preprocess_search_block_form(&$form) {
$form['search'] = array();
$hidden = array();
// Provide variables named after form keys so themers can print each element independently.
foreach (element_children($form['form']) as $key) {
echo $key;
$type = $form['form'][$key]['#type'];
echo '__'.$type.'<br />';
if ($type == 'hidden' || $type == 'token') {
$hidden[] = drupal_render($form['form'][$key]);
}
else {
if($key == 'search_block_form')
{
$form['form'][$key]['#title'] = t('');
//$form['search'][$key] = drupal_render($form['form'][$key]);
}
else
{
$form['search'][$key] = drupal_render($form['form'][$key]);
}
}
}
// Hidden form elements have no value to themers. No need for separation.
$form['search']['hidden'] = implode($hidden);
// Collect all form elements to make it easier to print the whole form.
$form['search_form'] = implode($form['search']);
var_dump($form);
exit;
}`
Refer to http://drupal.org/node/1092122:
<?php
/**
* Implements hook_theme().
*/
function MYMODULE_theme($existing, $type, $theme, $path) {
return array(
'article_node_form' => array(
'render element' => 'form',
'template' => 'article-node-form',
// this will set to module/theme path by default:
'path' => drupal_get_path('module', 'MYMODULE'),
),
);
}
?>
<?php
/**
* Preprocessor for theme('article_node_form').
*/
function template_preprocess_article_node_form(&$variables) {
// nodeformcols is an alternative for this solution.
if (!module_exists('nodeformcols')) {
$variables['sidebar'] = array(); // Put taxonomy fields in sidebar.
$variables['sidebar'][] = $variables['form']['field_tags'];
hide($variables['form']['field_tags']);
// Extract the form buttons, and put them in independent variable.
$variables['buttons'] = $variables['form']['actions'];
hide($variables['form']['actions']);
}
}
?>
article-node-form.tpl.php
<?php echo drupal_render_children($form)?>

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