CodeIgniter(2.1.4) Sessions is not working - codeigniter

I have a problem with CI sessions.
I initialized my session library:
$autoload[‘libraries’] = array(‘database’, ‘session’) (In config/autoload.php)
This is my code:
cycle
$this->load->library(‘image_moo’);
// Upload image and return unique name
$data = array(
‘image’ => $image,
);
$this->db->insert(‘category_images’, $data);
if (!$this->session->userdata(‘uploadImages’))
{
$this->session->set_userdata(‘uploadImages’, $this->db->insert_id());
}
else
{
$session = $this->session->userdata(‘uploadImages’);
$sessionData = $session.’|’.$this->db->insert_id();
$this->session->set_userdata(“uploadImages”, $sessionData);
}
echo $this->session->userdata(‘uploadImages’); // return 256; corect result - 255|256
end of cycle
This is script for image upload with jQuery File Upload (blueimp) and i need set ids of inserted in database images to session.
Can anyone help. Thank you!

To use CI Session you also need to provide the encryption key in your application/config.php:
$config['encryption_key'] = 'xxxxxx';`

Try this
cycle
$this->load->library(‘image_moo’);
// Upload image and return unique name
$data = array(
‘image’ => $image,
);
$this->db->insert(‘category_images’, $data);
if ($this->session->userdata(‘uploadImages’)=='')// or if (!isset($this->session->userdata(‘uploadImages’)))
{
$this->session->set_userdata(‘uploadImages’, $this->db->insert_id());
}
else
{
$session = $this->session->userdata(‘uploadImages’);
$sessionData = $session.’|’.$this->db->insert_id();
$this->session->set_userdata(“uploadImages”, $sessionData);
}
echo $this->session->userdata(‘uploadImages’); // return 256; corect result - 255|256
end of cycle

Related

In Drupal, how to validate the contents of a file uploaded using webforms and *not* upload if it fails validation?

I am implementing a site that accepts archives with directory structure in a specific fashion. I want to check the directory structure in the zipfile before accepting it. I tried the following (please see comments inline):
<?php
Using Webform Validation:
// using the webform validation module and its hooks
function testsuite_ziptest_webform_validation_validators()
{
return array(
"validate_zip_file"=> array(
'name' => "testsuite: Validate Zipfile" ,
'component_types' => array(
'select',
'file',
),
'description' => t('Verifies that the contents of the zipfile adhere to the specifications of testsuite.'),
)
);
}
function testsuite_ziptest_webform_validation_validate($validator_name, $items, $components, $rule)
{
$errors = array();
if($items)
{
switch($validator_name)
{
case "validate_zip_file":
drupal_set_message(t('Validate function called'));
foreach($items as $key=>$value)
{
drupal_set_message($key);
$v = _webform_validation_flatten_array($value);
drupal_set_message($v);
}
// tried to get the $fid and access the file using the fid.
// item_6 is the key of the file field that I selected while
// enabling webform validation.
// This fails saying no such file exists when the ziparchive
// object tries to open it.
$fid = $items['item_6'];
if(!empty($fid))
{
$za = new ZipArchive();
$file = file_load($fid);
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
break;
}
}
return $errors;
}
Using hook_file_validate
// this works, but there might be other files that may
// be uploaded to the site and I only want it to trigger
// when the file is uploaded as a part of a webform, not
// for all file uploads.
function testsuite_ziptest_file_validate($file)
{
if(!empty($file->filename))
{
$za = new ZipArchive();
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
}
Using Forms API (?)
// The following two methods that uses the form api on the webform
// has the same issue as the webform validation module. I can't get
// any reference to the file.
// There is a reference through a "completed form" key but I don't know
// if this is best practice
// die statements were used for debugging
function testsuite_ziptest_form_alter(&$form, &$form_state, $form_id)
{
if($form_id == 'webform_client_form_1')
{
array_unshift($form['#validate'], 'testsuite_ziptest_form_validate');
return $form;
}
}
function testsuite_ziptest_form_validate($form, &$form_state)
{
echo '<pre>'; print_r($form_state); echo '</pre>';
die();
$fid = $form_state['values']['submitted']['attachment'];
if(!empty($fid))
{
$za = new ZipArchive();
$file = file_load($fid);
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
else
{
}
die();
return;
}
Thanks!
I think you miss a point when you've done your function. You simply forgot to send the error back.
In the Webforms validation process, you have to send back some elements in the $errors array if something gone wrong.
$errors[$key] = t('%item is not good', array('%item' => $components[$key]['name']));
Here is an example of using this method.
In the Drupal form validation process, you have to use form_set_error if something is not good, with the combo name and the error message. The validation then stop automatically and the form will not be submitted...
And in the hook_file_validate method, you also have to send back an array of errors, witch will be use by the validator to stop the submission (with form_set_error).
Its Working Example :
function yourmoduleNma_file_validate($file,$validators)
{
$errors = array();
$filename = $file->filename;
$isValid_Extention_Size = explode('.',$filename);
if(count($isValid_Extention_Size) > 2){
$errors[] = 'Extention is not valid of this file';
}
elseif($file->filesize <= 0)
{
$errors[] = 'File size should be greater than 0 Bytes and less than 5 MB';
}
return $errors;
}

codeigniter generating multiple pdfs

i'm trying to generates pdfs in loop against member id, but every time i got only the first one, i addedd code in foreach so it runs multiple times, but it gives me only one pdf.please someone help me.
public function pdf($ids){
$k = 0;
foreach ($ids as $key => $id) {
$data[$k]['academics'] = $this->Utility_model->get_all_from_table_where('member_academics', array('member_id' => $id));
$data[$k]['member_employment'] = $this->Utility_model->get_all_from_table_where('member_employment', array('member_id' => $id));
$data[$k]['member_data'] = $this->Utility_model->get_all_from_table_where('members',array('member_id' => $id));
$data[$k]['disclosure'] = $this->Utility_model->get_all_from_table('generalsettings',array('key'=>'disclosure'));
$data[$k]['enrollment_fee'] = $this->Utility_model->get_all_from_table('member_invoices',array('user_id' => $id,'paymentFor'=>'Enrollment Fee'));
$data[$k]['enrollment_fee']['payment'] = $this->Utility_model->get_all_from_table('member_payments',array('invoice_id'=>$data[$k]['enrollment_fee']['id']));
$j=0;
if (!empty($data[$k]['member_data'])) {
foreach ($data[$k]['member_data'] as $member) {
$data[$k]['member_data'][$j]['term'] = $this->Utility_model->get_all_from_table('term', array('term_id' => $member['term_id']));
$data[$k]['member_data'][$j]['degree'] = $this->Utility_model->get_all_from_table('degree', array('degree_id' => $member['degree_id']));
$data[$k]['member_data'][$j]['year'] = $this->Utility_model->get_all_from_table('year', array('year_id' => $member['year_id']));
$data[$k]['member_data'][$j]['address'] = $this->Utility_model->get_all_from_table('member_addresses', array('id' => $member['address_id']));
$j++;
}
}
$this->load->view('admin/reports_management/applications_pdf/pdf_output',$data[$k],false);
$html = $this->output->get_output();
$this->load->library('dompdf_gen');
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream($k."file".".pdf");
$k++;
}
// echo "<pre>";
// print_r($data);
// die;
}
As long as you only request the page once you cannot get the controller method to output more than one file. You could either try to instead make a multiple page PDF or you need to change how the controller is called, and call it multiple times.
See this answer for some input about making multiple page PDF: How to create several pages with dompdf

redirect uri segment after delete

I created a project , I have a question about the direct url segment ...
For example:
this my URL
http://10.88.25.131/instrumentdev/instrument/instrument/detail/CT-BSC-001
when I want delete the data and to direct to the url such as the example above
this my controllers
public function detail(){
$id = $this->uri->segment(4);
$data = array(
'detail'=>$this->mcrud->get_detail($id),
'lihat' =>$this->mcrud->lihat_komentar($id),
'isi' =>'instrument/read_views');
$this->load->view('layout/wrapper', $data);
}
function deletecom() {
$u = $this->uri->segment(4);
$this->mcrud->deletecomment($u);
redirect('???**this my problem**???');
}
Use session
$newdata = array(
'data' => $u
);
$this->session->set_userdata($newdata);
redirect('controller/method');
then in next method
$u = $this->session->userdata('data');
Use
$this->load->helper('url');/*if not already*/
redirect(base_url('controller/method/parametersIfAny'));
TRY this :
function deletecom() {
echo $this->uri->segment(4);die(); //what does this print ??
$u = $this->uri->segment(4);
$this->mcrud->deletecomment($u);
redirect(base_url('instrument/instrument/detail/'.$u));
}

How to upload multiple images in php

I am developing a module of epaper in codeigniter(PyroCMS).
I want to know how can I upload multiple images ar once.
Can anyone guide me in uploading multiple images?
I tried but I only found code for uploading single image which I have already used in news module.
In the view file give this code for image upload:
echo form_label('Multi Images','',$label_attr);
echo form_upload($multi_photo_attr);
where
$multi_photo_attr = array(
'id' => "cat_multi_images",
'class' => "multi",
'name' => "cat_multi_images[]",
'maxlength' => "25",
'multiple' => "multiple"
);
Now you need to create a folder in the root directory where your photos will be uploaded.
After that in the controller's method you need to store the path to that folder in a variable.This variable will be used to upload the images in the folder.
Next,get the names of all the images in a array something like this:
foreach($_FILES["cat_multi_images"] as $key => $value)
{
$i=0;
foreach($value as $key1 => $value1)
{
$multi_photo_array[$i][$key] = $value1;
$i++;
}
After that for every array element,i.e.,for every image run the below code to upload it:
function UploadFile($files,$path)
{
$extensions = array('jpeg','JPEG','gif','GIF','png','PNG','jpg','JPG','pdf','PDF','ZIP','zip','rar','RAR','html','HTML','TXT','txt','doc','docx','DOC','DOCX','ppt','PPT','pptx','PPTX','xlsx','XLSX','xls','XLS','exe','EXE','mp3','MP3','wav','WAV','m4r','M4R','mpeg','MPEG','mpg','MPG','mpe','MPE','mov','MOV','avi','AVI',);
$destination = $path.$files["name"];
//print_r($destination);exit;
// GET FILE PARTS
$fileParts = pathinfo($files['name']);
$file_name = $files['name'];
$file_name_only = $fileParts['filename'];
$file_name_only = preg_replace('/[^a-zA-Z0-9]/','',$file_name_only);
$file_extention = $fileParts['extension'];
$Count = 0;
$destination = $path.$file_name_only.".$file_extention";
$file_name = $file_name_only.".$file_extention";;
// THIS SHOULD KEEP CHECKING UNTIL THE FILE DOESN'T EXISTS
while( file_exists($destination))
{
$Count += 1;
$destination = $path. $file_name_only."-".$Count.".$file_extention";
$file_name = $file_name_only."-".$Count.".$file_extention";
}
$fileextension='';
$filename='';
if(!empty($files))
{
$filename=$files['name'];
$fileextension=substr($filename,strpos($filename,".")+1);
if(in_array($fileextension,$extensions))
{
$uploadstatus=move_uploaded_file($files["tmp_name"],$destination);
if($uploadstatus)
{
return $file_name;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
Just copy the above code.It should work as it is made for a general case by me!You can copy that code in your model file and call it in the controller like this :
$pr_photo_data = $this->admin_model->UploadFile($value,$targetPath_images);
$photo_list[] = $pr_photo_data;
And then store every image in the database
foreach($photo_list as $image)
{
$pro_image["cat_multi_images"] = $image;
$pro_retId = $this->admin_model->add_multipic_cat($pro_image);
}
where
function add_multipic_cat($data)
{
$retId = $this->database->query_insert("photo", $data);
return $retId;
}
Be careful.Take care and do every step accurately
check this one
https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload,---Multi-file-upload-with-CodeIgniter
Struggling To Use PyroCMS Files Library To Upload Multiple Files

Incorrect Signature in facebook stream_publish call

I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.

Resources