I have set form validation in my project. My all form validation is working but I can not display file input validation error message. The file is upload properly, it doesn't show any error when I upload an invalid file. I try a lot of ways but anythings are not working.
I give here only file uploading related code.
My controller
$config = [
'upload_path'=>'./uploads/image/',
'allowed_types'=>'jpg|png',
'max_size' => '400',
'overwrite' => FALSE
];
$this->load->library('upload', $config);
if(!($this->form_validation->run() && $this->upload->do_upload()))
{
$view = array('error' => $this->upload->display_errors());
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}
MY model
public function add_books()
{
$data = $this->upload->data();
$image_path = base_url("uploads/image/".$data['raw_name'].$data['file_ext']);
$data = array(
'book_name' => $this->input->post('book_name'),
'description' => $this->input->post('description'),
'author' => $this->input->post('author'),
'publisher' => $this->input->post('publisher'),
'price' => $this->input->post('price'),
'quantity' => $this->input->post('quantity'),
'categoryId' => $this->input->post('categoryId'),
'book_image' => $image_path,
'userId' => $this->session->userdata('id'),
'status' => $this->input->post('status')
);
$insert_book = $this->db->insert('books', $data);
return $insert_book;
}
My view
<div class="form-group row">
<label for="book_image" class="col-sm-2 col-form-label">Book image</label>
<div class="col-sm-6">
<?= form_upload(['name'=>'userfile', 'class'=>'form-control'])?>
<div class="text-secondary">* Upload PNG, JPG format. Image should not be more than 400KB</div>
</div>
<div class="col-sm-4">
<div class="text-danger form-error"><?= form_error('userfile')?></div>
</div>
</div>
How it can be fixed?
I think you should separate $this->form_validation->run() and $this->upload->do_upload()
$view = array();
if($this->form_validation->run() == true){
if(!$this->upload->do_upload('userfile')){
$view['error'] = $this->upload->display_errors();
}
}else{
$view['error'] = validation_errors();
}
if(array_key_exists('error', $view)){
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}else{
//Insert the record
}
Related
Goodnight (or good morning),
I trying to upload multiple files at the same time. I am following the cookbook instructions to build the solution. I always got first file (not and array of files).
Here is my view code...
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Upload $upload
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Uploads'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="uploads form content">
<?= $this->Form->create($upload, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Upload') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('document_type_id', ['options' => $documentTypes]);
echo $this->Form->control('period_id', ['options' => $periods]);
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('documents', ['type' => 'file', 'label' => __('Choose PDF Files'), 'accept' => 'application/pdf', 'multiple' => 'multiple']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
And here is my controller code...
public function add()
{
$upload = $this->Uploads->newEmptyEntity();
if ($this->request->is('post')) {
$upload = $this->Uploads->patchEntity($upload, $this->request->getData());
if ($this->Uploads->save($upload)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$documents = $this->request->getData('documents');
$this->loadModel('Dockets');
$dockets = $this->Dockets->findByDocketStateId(1);
$documents_ok = 0;
$documents_nok = 0;
$dockets_without_document = 0;
foreach($documents as $documents_key => $document_to_save)
{
foreach($dockets as $dockets_key => $docket)
{
$contents = file_get_contents($document_to_save);
$pattern = str_replace('-', '', $pattern);
$pattern = str_replace('', '', $pattern);
$pattern = preg_quote($docket->cuit, '/');
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$documentsTable = $this->getTableLocator()->get('Documents');
$document = $documentsTable->newEmptyEntity();
$document->upload_id = $upload->id;
$document->document_type_id = $upload->document_type_id;
$document->period_id = $upload->period_id;
$document->docket_id = $docket->id;
$document->user_id = $this->getRequest()->getAttribute('identity')['id'];
if ($documentsTable->save($document)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$fileobject = $this->request->getData('document');
$destination = $this->Parameters->findByName('document_directory')->first()->toArray()['value'] . 'document_' . $document->id . '.pdf';
// Existing files with the same name will be replaced.
$fileobject->moveTo($destination);
}
$this->Flash->error(__('The document could not be saved. Please, try again.'));
$documents_ok = $documents_ok + 1;
unset($dockets[$dockets_key]);
unset($documents[$documents_key]);
break;
}
}
}
if(!empty($documents)){
//print_r($documents);
$documents_nok = count($documents);
unset($documents);
}
if(!empty($dockets)){
$dockets_without_document = count($dockets);
unset($dockets);
}
$message = __('There were processed ') . $documents_ok . __(' documents succesfully. ') . $documents_nok . __(' documents did not math with a docket. And ') . $dockets_without_document . __(' active dockets ddid not not have a document.');
$this->Flash->success(__('The upload has been saved. ') . $message);
return $this->redirect(['action' => 'view', $upload->id]);
}
$this->Flash->error(__('The upload could not be saved. Please, try again.'));
}
$documentTypes = $this->Uploads->DocumentTypes->find('list', ['keyField' => 'id',
'valueField' => 'document_type',
'limit' => 200]);
$periods = $this->Uploads->Periods->find('list', ['keyField' => 'id',
'valueField' => 'period',
'limit' => 200]);
$users = $this->Uploads->Users->find('list', ['keyField' => 'id',
'valueField' => 'full_name',
'conditions' => ['id' => $this->getRequest()->getAttribute('identity')['id']],
'limit' => 200]);
$this->set(compact('upload', 'documentTypes', 'periods', 'users'));
}
Can you help me to understand what I doing wrong?
Thanks,
Gonzalo
When using PHP, multi-file form inputs must have a name with [] appended, otherwise PHP isn't able to parse out multiple entries, they will all have the same name, and PHP will simply use the last occurrence of that name.
echo $this->Form->control('documents', [
'type' => 'file',
'label' => __('Choose PDF Files'),
'accept' => 'application/pdf',
'multiple' => 'multiple',
'name' => 'documents[]',
]);
Furthermore the following line:
$fileobject = $this->request->getData('document');
should probably be more like this, as there a) is no document field and b) even if there were, you most likely wouldn't want to process the same file over and over again:
$fileobject = $documents[$documents_key];
Also make sure that you have proper validation in place for the uploaded files, even if you don't seem to use the user provided file information, you should still make sure that you've received valid data!
I am creating a form and trying to upload multiple image .All thing right with single image . when I am trying to upload multiple image,Then I receive only one image in output .
Here is my View file.
<div class="from-control-div">
<?php echo $this->Form->create('Post', array('type' => 'file','id'=>'unitform','class'=>'form-horizontal','role'=>'form','url' => array('controller' => 'posts', 'action' => 'savepost')));?>
<div class="from-div-bottom">
<div class="form-group">
<label class="col-sm-4 control-label">File Upload</label>
<div class="col-sm-6" id="more-files">
<?php echo $this->Form->input('files.',array('type'=>'file','label' => false,'placeholder' => 'Upload images','id'=>"inputFile",'multiple','onchange'=>'readURL(this)'));?>
<!--<div id="fileList"></div>-->
</div>
<a class="col-sm-2 pull-right" style="font-weight:bold;" id="add-more"><i class="fa fa-plus"></i> Add More</a>
</div>
</div>
</form>
After this here is my controller.If I print print_r($data); then output is single array. No multiple array receive .Any help for me
Array ( [0] => Array ( [name] => download.jpg [type] => image/jpeg [tmp_name] => /tmp/phpX3Oy32 [error] => 0 [size] => 12988 ) )
public function savepost() {
if (count($this->request->data) > 0) {
$fileNames = '';
if (isset($this->request->data['Post']['files']) && count($this->request->data['Post']['files']) > 0) {
$data=$this->request->data['Post']['files'];
print_r($data);
$fileNames = array();
foreach ($this->request->data['Post']['files'] as $filedata) {
if(isset($filedata["name"]) && ($filedata["name"] !='')){
$upload_dir = FILE_UPLOAD_PATH;
$original = explode('.', $filedata["name"]);
$extension = array_pop($original);
$newname = time() . '.' . $extension;
if (file_exists($upload_dir . $newname)) {
unlink($upload_dir . $newname);
}
if (move_uploaded_file($filedata["tmp_name"], $upload_dir . $newname)) {
$fileNames[] = $newname;
print_r($fileNames);
}
}
}
}
}
}
public function savepost() {
if(isset($this->request->data['multifiles'])){
$file_name_all="";
for($i=0; $i<count($this->request->data['multifiles']); $i++){
if(!empty($this->request->data['multifiles'][$i]['name'])){
$file = $this->request->data['multifiles'][$i];
$file['name'] = time() . '-' . str_replace(' ', '_', $file['name']);
$uploadPath = WWW_ROOT . 'img/ ';
$fileName = $file['name'];
$uploadFile = $uploadPath.$fileName;
$file_name_all.= $file['name'].",";
if($file['name']){
move_uploaded_file($file['tmp_name'], $uploadFile);
}
}
}
}
}
in my code it is working.
I am using 3.4 cakephp version but file uploaded successfully but i want the url to be updated in request entity. I can have one entity updated but not all like:
$post->url = WWW_ROOT.'uploads/filename';
Html form :
<?= $this->Form->create(null, ['class' => 'form-horizontal', 'id' => 'postSubmit', 'type' => 'file', 'autocomplete' => 'off'])?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">Ad Category:</label>
<div class="col-sm-8">
<?= $this->Form->select('category_id', $categories, ['class' => 'form-control required categorySelected', 'empty' => 'Select Category'])?>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-4 control-label">Photos(5 max):</label>
<div class="col-sm-8">
<?= $this->Form->input('images.', [ 'type' => 'file', 'id' => 'image', 'multiple' => 'multiple', 'accept' => 'image/jpg, image/jpeg', 'label' => false])?>
<p class="help-block">Good photos quick response</p>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-4">
<?= $this->Form->button('Post Now', ['class' => 'btn custom_btn btn-sm', 'type' => 'submit', 'label' => false])?>
</div>
</div>
</form>
Controller Action :
$post = $this->Posts->newEntity();
$post = $this->Posts->patchEntity($post, $this->request->getData());
if($this->request->getData()['images']) {
$dir = new Folder(WWW_ROOT.'uploads', true, 0755);
$files = $this->request->getData()['images'];
foreach ($files as $key => $file) {
if($file['error'] == 0) {
$info = pathinfo($file["name"]);
$newfilename = $info["filename"].'_'.time() . '.'. $info["extension"];
if(move_uploaded_file($file["tmp_name"], WWW_ROOT.'uploads/' . $newfilename)) {
$post->url = WWW_ROOT.'uploads/' . $newfilename;
}
}
}
}
if ($this->Posts->save($post)) {
$this->Flash->success('Post has been submitted successfully. Please wait
for approval');
}
I recommend you to implement the CakePHP3-Proffer described bellow:
Uploading multiple related images
This example will show you how to upload many images which are related to your current table class. An example setup might be that you have a Users table class and a UserImages table class. The example below is just baked code.
Tables
The relationships are setup as follows. Be sure to attach the behavior to the table class which is receiving the uploads.
// src/Model/Table/UsersTable.php
$this->hasMany('UserImages', ['foreignKey' => 'user_id'])
// src/Model/Table/UserImagesTable.php
$this->addBehavior('Proffer.Proffer', [
'image' => [
'dir' => 'image_dir',
'thumbnailSizes' => [
'square' => ['w' => 100, 'h' => 100],
'large' => ['w' => 250, 'h' => 250]
]
]
]);
$this->belongsTo('Users', ['foreignKey' => 'user_id', 'joinType' => 'INNER']);
Entities
Your entity must allow the associated field in it's $_accessible array. So in our example we need to check that the 'user_images' => true is included in our User entity.
Controller
No changes need to be made to standard controller code as Cake will automatically save any first level associated data by default. As our Users table is directly associated with our UserImages table, we don't need to change anything.
If you were working with a related models data, you would need to specify the associations to populate when merging the entity data using the 'associated' key.
Templates
You will need to include the related fields in your templates using the correct field names, so that your request data is formatted correctly.
// Don't forget that you need to include ['type' => 'file'] in your ->create() call
<fieldset>
<legend>User images</legend>
<?php
echo $this->Form->input('user_images.0.image', ['type' => 'file']);
echo $this->Form->input('user_images.1.image', ['type' => 'file']);
echo $this->Form->input('user_images.2.image', ['type' => 'file']);
?>
</fieldset>
How you deal with the display of existing images, deletion of existing images, and adding of new upload fields is up to you, and outside the scope of this example.
I am currently learning on WordPress plugin development and I am trying to build a short code for my plugin
my plugin is basically a custom post type called property which have 3 meta data boxs in it
price location and date of construction
and one taxonomy called property type which be setted at the backend with rent or sale
all of this works and if you put them in wordpress they will work
But my shortcode file does work properly the loop on the WP_Query should return all the post which I have made but instead its returning only the first element found in the WP_Query
Can anyone guide me or fix where I have mistaken please
thanks all
now my short code file name is: properties_post_type_shortcode.php
My plugin file name is: properties_post_type.php
code for properties_post_type_shortcode.php
<?php
add_shortcode('land_properties',function(){
$loop = new WP_Query(
array(
'post_type' => 'property_post',
'orderby' => 'title'
)
);
if ($loop->have_posts()){
$output = '<ul class="land_properties_list">';
$i=0;
while( $loop->have_posts() ){
$loop->the_post();
$meta=get_post_meta(get_the_id(),'' );
$output= '
<li>
<a href="' .get_permalink() . '">
' . get_the_title() . ' | '.
$meta['property_price'][0]. " " .
$meta['property_location'][0]. " " .
$meta['property_date'][0]. " " .
'
</a>
<div>' . get_the_excerpt() . '</div>
</li>
';
}
}
else {
$output="No lands added";
}
// $loop->wp_reset_postdata();
return $output;
});
code for properties_post_type.php
<?php
/*
* Plugin Name: properties_post_type
* Plugin URI: Have not be set yet
* Description: this plugin allow you to create custom post type property which you can be modified and edited
* Version: 1.0
* Author: Muhab Alwan
* Author URI: https://www.facebook.com/HaaaB
* License: A "Slug" license name e.g. GPL2
*/
class PROP_POST_TYPE{
//default contructor
public function __construct()
{
$this->register_post_type();
$this->taxonomies();
$this->metaboxes();
}
public function register_post_type()
{
$args= array(
'labels' => array(
'name'=> 'Properties',
'singular_value' => 'Property',
'add_new' => 'Add New Property',
'add_new_item' => 'Add New Property',
'edit_items' => 'Edit_Items',
'new_item' => ' Add New Items',
'view_item'=> 'View Item',
'search_items' => 'Search Items',
'not_found' => 'No Property Found',
'not_found_in_trash' => 'No Property Found In Trash'),
'query_var' =>'properties',
'rewrite' => array(
'slug' => 'property/'),
'public' => true,
'menu_position' => 80, // set postion in the backend menu
'menu_icon' => admin_url(). 'images/media-button-other.gif', // define an image for the prop
'supports' => array(
'title',
//'editor',
'excerpt',
//'custom-fields' when we need user to build their own meta box Not required in project
) // specify what wordpress types are custom post type support
);
register_post_type('property_post', $args );
}
public function taxonomies()
{
$taxonomies = array();
$taxonomies['property_type'] = array(
'hierarchical' => true,
'query_var' => 'movie_genere',
'rewrite' => array('slug' => 'prop/type'
),
'labels' => array(
'name'=> 'Properties Type',
'singular_value' => 'Property Type',
'add_new' => 'Add New Property Type',
'add_new_item' => 'Add New Property Type',
'edit_items' => 'Edit Properties Type',
'new_item' => ' Add New Properties Type',
'view_item'=> 'View Property Type',
'search_items' => 'Search Properties Type',
'popular_items' => 'Popular Properties Type',
'separate_items_with_comments' => 'Separate Property Type With Comments',
'add_or_remove_items' => 'Add Or Remove Properties Type',
'choose_from_most_used' => 'Choose From Most Used Properties Type'
)
);
$this-> register_all_taxonomies($taxonomies); // register all taxonomies build in this plugin
}
public function register_all_taxonomies($taxonomies)
{
// foreach is for registering many taxonomy
foreach ($taxonomies as $name=> $arr)
{
//register ( what the taxonomies name, array of the object type that we register ex post or page
register_taxonomy($name,array('property_post'),$arr );
}
}
public function metaboxes()
{
// FIRST PRICE META BOX
add_action('add_meta_boxes', function(){
//css id, title, cb func, page, priority level, call back func argum
add_meta_box('property_price','Property Price', 'property_price','property_post');
add_meta_box('property_location','Property Location', 'property_location','property_post');
add_meta_box('property_date','Date Of Construction', 'property_date','property_post');
});
//PRICE PROP
function property_price($post){
$price_length = get_post_meta($post->ID,'property_price', true);
?>
<p>
<label for="property_price"> :</label>
<input type="number" pattern="[0-9]+" size="50" class="widfat" name="property_price" id="property_price" value="<?php echo esc_attr($price_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_price']))
{
update_post_meta(
$id,'property_price',
strip_tags($_POST['property_price'])
);
}
});
// LOCATIO PROP
function property_location($post){
$location_length = get_post_meta($post->ID,'property_location', true);
?>
<p>
<label for="property_location"> :</label>
<input type="text" class="widfat" name="property_location" id="property_location" value="<?php echo esc_attr($location_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_location']))
{
update_post_meta(
$id,'property_location',
strip_tags($_POST['property_location'])
);
}
});
function property_date($post){
$dof_length = get_post_meta($post->ID,'property_date', true);
?>
<p>
<label for="property_date"> :</label>
<input type="date" class="widfat" name="property_date" id="property_date" value="<?php echo esc_attr($dof_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_date']))
{
update_post_meta(
$id,'property_date',
strip_tags($_POST['property_date'])
);
}
});
//third date of construction metaboxes
}
}
// initialization essential to build a cust post
add_action('init', function(){
new PROP_POST_TYPE();
include dirname(__FILE__). '/properties_post_type_shortcode.php';
});
To query all posts, add the following to the args of WP_Query:
'posts_per_page' => -1
Your code:
$loop = new WP_Query( array(
'post_type' => 'property_post',
'orderby' => 'title',
'posts_per_page' => -1
) );
I'm trying to upload multiple images from a textbox to MYSQL database using PHP.
But somehow it only inserts the last item from the array in the database.
I tried uploading using one image, and that worked.
What am I doing wrong?
form.php:
<form action="addpicture.php?id=<?php echo $prodID; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="image[]" multiple/>
<input type="submit" value="upload" name="image" class="btn btn-primary" />
</form>
Addpicture.php:
<?php
session_start();
include '../includes/config.php';
$prodID = $_GET['id'];
foreach(array_keys($_FILES['image']['error']) as $key){
$temp_name = $_FILES['image']['tmp_name'][$key];
$t_name = file_get_contents($temp_name);
$t_name = mysql_real_escape_string($t_name);
$insert = mysql_query("INSERT INTO tblpictures(prodID, foto) VALUES ('$prodID','$t_name')") or die(mysql_error());
header('location: form.php?prodID=' . $prodID);
exit();
}
?>
EDIT: SOLVED
HTML 5 multi file upload with PHP
You're using the PHP array-based naming for file uploads. PHP's treatment of that in the $_FILES array is BEYOND moronic.
Single files show up as
$_FILES = array(
'fieldname' => array('error' => ..., 'name' => '...', etc....)
);
As soon as you go into array mode, you get a completely DIFFERENT structure:
$_FILES = array(
'fieldname' => array (
'error' => array(
0 => 'error code of first file'
1 => 'error code of second file'
etc...
)
'name' => array(
0 => 'first filename',
1 => 'second filename',
etc...
)
)
)
You need to loop on:
foreach(array_keys($_FILES['image']['error']) as $key) {
$name = $_FILES['image']['name'][$key];
$temp_name = $_FILES['image']['tmp_name'][$key];
}