Showing posts with label codeigniter. Show all posts
Showing posts with label codeigniter. Show all posts

Thursday, October 4, 2018

nginx returns 403 forbidden error on file upload

Leave a Comment

I have a php website, in codeigniter, which allows users to upload files. Upload works fine for most of files. But for few files nginx throws 403 Forbidden error. like

<html> <head><title>403 Forbidden</title></head> <body bgcolor="white"> <center><h1>403 Forbidden</h1></center> </body> </html> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> 

This is one of the sample .rb file that fails to upload

# Sample code from Programing Ruby, page 58 string = <<END_OF_STRING     The body of the string     is the input lines up to     one ending with the same     text that followed the '<<' END_OF_STRING 

If i remove '<<' from this file, upload works. Where is this filtration happening?

I have seen nginx error logs, nothing in there. I have seen codeigniter logs, nothing there. Infact upload request doesn't reach my Codeigniter controller, so must be blocked before reaching there by nginx?

Here is upload code in Javascript

function upload(file, params) {     var formData = new FormData();     formData.append("Filedata", file);     $.each(params, function(key, value) {        formData.append(key, value);      });      var xhr = new XMLHttpRequest();     var action = "/upload/file";      xhr.upload.onprogress = function(e){         // show progress with e.loaded, e.total     };      xhr.onerror = function(e) {          // handle error     };      xhr.open("POST", action, true);     xhr.send(formData); } 

On server side, I have simple code for now.

if( !isset($_FILES['Filedata']) || !file_exists($_FILES['Filedata']['tmp_name']) ) {     die('File not submitted.'); } else {      // Save file code is here } 

1 Answers

Answers 1

I don't have a solution, but probably related to your single quotes. Doesn't .append have it read through that file? Wouldn't it terminate on the single quote?
Essentially going:

if( !isset($_FILES['# Sample code from Programing Ruby, page 58   string = <<END_OF_STRING       The body of the string       is the input lines up to       one ending with the same       text that followed the '   
Read More

Wednesday, April 11, 2018

Curl failed: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to fcm.googleapis.com:443 in Codeigniter

Leave a Comment

i integrated Fire-base Notification CRUL Code with Codeigniter. sometimes i am getting error but not all the times.

i have integrated below code to the controller

Controller Code

$newDate=Date('m-d-Y H:i:s');  $test_str=$user->us_name. ' Clocked at '.$newDate; $res = array();  $res['data']['title'] = $user->us_name.' - Clocked In'; $res['data']['is_background'] = "TRUE"; $res['data']['message'] = $test_str; $res['data']['image'] = 'http://api.androidhive.info/images/minion.jpg'; $res['data']['payload'] = 'individual'; $res['data']['timestamp'] = date('Y-m-d G:i:s'); $res['data']['act_tab'] = 0;   $cur_id1=$this->db->query("Select token from devices")->result();  foreach($cur_id1 as $cur_id) {      $fields = array('to' => $cur_id->token,'data' => $res);     $this->notif_model->sendPushNotification($fields); } 

Model Code

function sendPushNotification($fields) {           // Set POST variables         $url = 'https://fcm.googleapis.com/fcm/send';          $headers = array(             'Authorization: key=MyServerKey',             'Content-Type: application/json'         );         // Open connection         $ch = curl_init();          // Set the url, number of POST vars, POST data         curl_setopt($ch, CURLOPT_URL, $url);         curl_setopt($ch, CURLOPT_POST, true);         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          // Disabling SSL Certificate support temporarly         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));          // Execute post         $result = curl_exec($ch);         if ($result === FALSE) {             die('Curl failed: ' . curl_error($ch));         }          // Close connection         curl_close($ch);          return $result;     } 

While Running this some times i am getting the error

Curl failed: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to fcm.googleapis.com:443

1 Answers

Answers 1

Try to add curl_setopt($ch, CURLOPT_SSLVERSION, 3);

Read More

Monday, February 19, 2018

CodeIgniter Routing - changing to handle a subdomain?

Leave a Comment

I have my site built in CodeIgniter. The url format is

domain.com/lang/id/descriptive-text  

e.g.

domain.com/en/12/article-on-codeigniter-routing 

One particular page (Tours) has all of the tour information (retrieved according to id number) to display. HOWEVER, i now have a booking system written in Ruby on Rails that i need to integrate. The way to do that is going to have to be have a subdomain called booking.domain.com and each tour page to display on that subdomain so that the in page booking system can run properly.

That means coding the Tours page in ruby and passing in the info from codeigniter. The way i know whether a page is a Tour or just other pages is that the Tour pages have id greater than 20 but less than 40.

Below is my current routing code:

$route['default_controller'] = "content"; $route['en/(:num)/(:any)'] = "content/en/$1"; $route['de/(:num)/(:any)'] = "content/de/$1"; $route['es/(:num)/(:any)'] = "content/es/$1"; $route['it/(:num)/(:any)'] = "content/it/$1"; 

My question is how would i change this to now reflect this new change?? I'm at a loss.

Thanks

3 Answers

Answers 1

if you don't have same range of id like the subdomain, you can try this

$route['default_controller'] = "content";  $route['(.+)'] = function ( $params ){                         $param = explode("/", $params);                         if(20 >= (int) $param[1] =< 40){                             return "subdomain";                         }                         else{                             return "content/" . $param[0] . "/" . $param[1];                         }                     }; 

Answers 2

Solution (without modifying the CodeIgniter)

Use .htaccess to do the redirection.

<IfModule mod_rewrite.c>  RewriteEngine on  RewriteRule    ^([^/]+)/([20][0-9]|[30][0-9]|[40]+)/([^/]+)?$    http://sub.maindomain.foo/$1/$2/$3    [L] </ifModule> 

This will redirect to the sub domain if the URL pattern matches the rule

id greater than 20 but less than 40

If your main domain and sub domain have same URL pattern,

http://maindomain.foo/en/30/article-on-codeigniter-routing

will automatically redirects to

http://sub.maindomain.foo/en/30/article-on-codeigniter-routing

Answers 3

I might be being stupid here - but isn't the solution to amend your controller and do the following?

public function content($lang,$id){     if ($id > 20 && $id < 40){         $post = base64_encode(serialize($post));         redirect('subdomain.domain.com/'.$lang.'/'.$id.'/'.$post);     } else {         // carry on processing ....     } } 

I have amended my answer based on your query about posting data. I've serialized and base64 encoded it. To unserialize it you will need https://github.com/jqr/php-serialize (I am not a ruby expert so know nothing about this) and from research I believe you would need Base64.decode64() for the base64 decoding.

Read More

Tuesday, February 6, 2018

MySQL stored procedure no insert ID returned?

Leave a Comment

I have a very simple query, not sure what I am doing wrong here.

My DB call is not receiving an insert id as I would expect it to.

Table:

enter image description here

Stored Procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT) BEGIN     INSERT INTO order_customer_product (customerID, productID, retailAmountAtPurchase, faceValue)     SELECT         in_customerID,         in_productID,         p.retail,         p.faceValue     FROM         products as p     WHERE          p.productID = in_productID; END 

PHP:

   public function addProduct($data, $userID)     {         // Do we already have a pending order for this user?         $orderID = $this->doesOrderExist($userID);          // We had no order, lets create one         if (!$orderID) {             $orderID = $this->createOrder($userID);         }          /**          * Insert the customer product.          * This relates a denomination to a customer.          */         $customerProductID = $this->addCustomerProduct($data);          // Add this customer product to the order         $this->addProductToOrder(array("customerProductID" => $customerProductID, "orderID" => $orderID));          // Return         return $customerProductID;     }      /**      * Description: Add a customer product / reward      * Page: client/add_reward      */     public function addCustomerProduct($data){         $procedure = "CALL addCustomerProduct(?,?)";         $result = $this->db->query($procedure, $data);         return $this->db->insert_id();     } 

The line with the issue is: $customerProductID = $this->addCustomerProduct($data);.

A new record is being inserted into the table and the table has a PK/AI. Data goes in fine but 0 is returned as the $customerProductID.

Will an insert from select statement not return an insert ID perhaps?

Update For @Ravi-

enter image description here

Update 2:

I created a separate method and hard coded the query and data being sent.

It adds the records fine, AI goes up, 0 is returned as the last id.

public function test(){     $procedure = "CALL addCustomerProduct(?,?)";     $result = $this->db->query($procedure, array("customerID" => 1, "productID" => 20));     echo $this->db->insert_id(); } 

Also restarted the MySQL server to make sure there wasn't anything weird going on there.

Also, updated the SP to just insert random data into the table without using a select.

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT) BEGIN     INSERT INTO order_customer_product (customerID, productID, retailAmountAtPurchase, faceValue)     VALUES(8,2,'4.55',25); END 

Update 3:

Right after the insert, I am printing out the last query that was ran as well as the result. You will notice that there is 1 affected row (the insert is happening) but the insert_id is still 0.

CALL addCustomerProduct('8','33')  CI_DB_mysqli_result Object (     [conn_id] => mysqli Object         (             [affected_rows] => 1             [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $             [client_version] => 50012             [connect_errno] => 0             [connect_error] =>              [errno] => 0             [error] =>              [error_list] => Array                 (                 )              [field_count] => 0             [host_info] => Localhost via UNIX socket             [info] =>              [insert_id] => 0             [server_info] => 5.6.35             [server_version] => 50635             [stat] => Uptime: 1637  Threads: 3  Questions: 508  Slow queries: 0  Opens: 113  Flush tables: 1  Open tables: 106  Queries per second avg: 0.310             [sqlstate] => 00000             [protocol_version] => 10             [thread_id] => 25             [warning_count] => 0         )      [result_id] => 1     [result_array] => Array         (         )      [result_object] => Array         (         )      [custom_result_object] => Array         (         )      [current_row] => 0     [num_rows] =>      [row_data] =>  ) 

Update 4:

From some of the research I have done, unless you use the mysqli method such as $this->db->insert(), it won't provide a last insert id back to you.

I am going to try and figure out Ravi's suggestion but it seems that code igniter doesn't allow the example that was shown. At least I know now that I am not crazy and its just not normal behavior unless you use the ``insert` method vs a stored procedure.

3 Answers

Answers 1

This answer may explain why your existing code doesn't work. To quote:

CodeIgniter's insert_id() will only return an ID of an insert(). Unless you are executing something like $this->db->insert('table', $data); before calling the function it will not be able to return an ID.

MySQL's LAST_INSERT_ID(); should help you here (assuming you have permission to alter the stored procedure definition). Change it to:

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(     IN in_customerID INT, in_productID INT, OUT out_customerProductID INT) BEGIN     INSERT INTO order_customer_product (         customerID, productID, retailAmountAtPurchase, faceValue)     VALUES(8,2,'4.55',25);      SELECT LAST_INSERT_ID() INTO out_customerProductID; END 

Then use something like the following to get the output parameter value:

public function addCustomerProduct($data){     $procedure = "CALL addCustomerProduct(?,?)";     $query = $this->db->query($procedure, $data);      return $query->result(); } 

If the above doesn't work, try adding a $this->db->trans_start(); and $this->db->trans_complete(); before and after the stored procedure call to ensure the transaction is committed.

Answers 2

Ideally, following line should work

$this->db->insert_id; 

But, I'm not sure why is not working, so I would suggest a workaround as following, recompile your procedure with additional parameter out_lastId, which will return last inserted id

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT, OUT out_lastId INT) 

And, after insert set the value with last inserted id.

 SET out_lastId = LAST_INSERT_ID(); 

==Updated==

$this->db->multi_query( "CALL addCustomerProduct($data, @id);SELECT @id as id" ); $db->next_result();            // flush the null RS from the call $rs=$this->db->store_result();       // get the RS containing the id echo $rs->fetch_object()->id, "\n"; $rs->free(); 

Answers 3

Why

insert_id() will only workes with Query Builder and Queries only. SP's are used to call with $this->db->query() but it won't retuns data insert_id().


How

Before the End of SP add SELECT MAX(id) FROM order_customer_product;. So this will return the last ID to your code.


Suggestion

As I see there is an Insert query to DB. If I use similar case will use normal Query Builder or/and will warp it with Codeigniter Transactions(My answer on another question).

Read More

Friday, January 5, 2018

MYSQL AND query to satisfy on same column

Leave a Comment

I have following tables

routes

id | route_name 

stops

id | stop_name 

stop_orders

id | route_id | stop_id | stop_order 

here i will store all stops name

buses

id | bus_name  1 | R.S 

here i will store all bus names

3.route_connect

id | bus_id | stop_id  1 | 1 | 1  2 | 1 | 2 

bus_timing

id | route_id | stop_id | bus_id | bus_timing | trip | trip_direction 

bus_name|stop_name

R.S |Sydney R.S | Melbourne 

1) My aim is to get all bus names when user will search between two stops.

2) For example if user search for source to destination (Sydney to Melborne) then it should return all bus names which is traveling between these two city. If there is no direct buses then i need to show connected buses between two city

I am trying write a query where i need to retrieve all buses between two stop and between two timings

i tried lots of combination of query but it failed to retrive the expected result

1) I need to retrieve all buses which travel between two city along with between two times.

2) Also if buses are not directly travel between two city then i need to show inter connected buses.

I have tried following query

SELECT  buses.bus_name,stops.stop_name FROM route_connect   LEFT JOIN buses ON buses.id=route_connect.bus_id LEFT JOIN stops ON stops.id=route_connect.stop_id WHERE route_connect.stop_id=(select id from stops where stops.stop_name='Sydney')  AND  route_connect.stop_id=(select id from stops where stops.stop_name='Melbourne') 

but this will return null .If i use OR then it will return

Can any one help me how i can fix this issue .Is my table structure is wrong ?

Note: here i am tagging both mysql and php as well as framework since i m okay with answer both query as well as code also

SELECT * FROM bus_timings  INNER JOIN buses on buses.id=bus_timings.bus_id INNER JOIN routes ON routes.id=bus_timings.route_id INNER JOIN stops ON stops.id=bus_timings.stop_id WHERE stops.stop_name in  ('Sydney', 'Melbourne') and  bus_timings.bus_time BETWEEN CAST('09:30:00' AS time) AND CAST('10:00:00' AS time)  

still buses more than two buses traveling between two city but return only one

SELECT * FROM bus_timings  INNER JOIN buses on buses.id=bus_timings.bus_id INNER JOIN routes ON routes.id=bus_timings.route_id INNER JOIN stops ON stops.id=bus_timings.stop_id WHERE stops.stop_name in  ('Sydney', 'Melbourne') HAVING COUNT(DISTINCT stops.stop_name) = 2 

still buses more than two buses traveling between two city but return only one

for more detail i have another question PHP MYSQL retrieve data based on two matching row column

Updated routes table contain

   +-----------------+     |id  | route_name |    +----+-------------    |  1 | Sydney     |    +----+------------+       |  2 | Melborne   |    +----+------------+ 

stops table contain

   +-----------------+     | id | stop_name  |    +----+-------------    |  1 | stop_1     |    +----+------------+       |  2 | stop_2     |    +----+------------+ 

stop_orders

+------+-----------+----------+-------------+     | id   |  route_id | stop_id  | stop_orders | +------+-----------+----------+-------------+ | 1    |     1     |    1     |      1      | +------+-----------+----------+-------------+ | 2    |     1     |    2     |      2      | +------+-----------+----------+-------------+ 

bus_timing

+-----+----------+---------+--------+------------+--------+----------------+ | id  | route_id | stop_id | bus_id | bus_timing | trip   | trip_direction | +-----+----------+---------+--------+------------+--------+----------------+ |  1  |   1      |   1     |  1     | 07:30:00   |   1    |     1          |     +-----+----------+---------+--------+------------+--------+----------------+     |  2  |   1      |   2     |  1     | 07:50:00   |   1    |     1          |     +-----+----------+---------+--------+------------+--------+----------------+ 

1)routes will contain different routes like sydney,melborne.

2)stops will contain same as routes

3)stop_order table contain each route as multiple stops with the order so we can know which is then next stop based on order

4)each bus has timing which will be mentioned in bus timing table with route and stop 5)one bus will travel multiple times between two city so i added trip and direction will identify which way bus is traveling i mean sydney to melborne or melborne to sydney

Updated

enter image description here

Image explanation

1)In image city refers to routes table

2)green color shows multiple stops in city

3)city 1 and city 2 will connect in city 3 so if a person wants to go city-1 to city-2 then he need to use interconnected buses between city-1 to city-3 and city-3 to city-2

Updated Table structure

CREATE TABLE `buses` (   `id` int(11) NOT NULL,   `bus_name` varchar(255) DEFAULT NULL,   `bus_number` varchar(255) DEFAULT NULL,   `bus_image` varchar(255) DEFAULT NULL,   `bus_stop_start` int(11) DEFAULT NULL,   `bus_stop_end` int(11) DEFAULT NULL,   `route_id` varchar(255) DEFAULT NULL,   `created_at` datetime NOT NULL,   `updated_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `buses` --  INSERT INTO `buses` (`id`, `bus_name`, `bus_number`, `bus_image`, `bus_stop_start`, `bus_stop_end`, `route_id`, `created_at`, `updated_at`) VALUES (1, 'A.K', NULL, NULL, NULL, NULL, '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (2, 'B.K', NULL, NULL, NULL, NULL, '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'); (3, 'J.K', NULL, NULL, NULL, NULL, '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'); (4, 'M.K', NULL, NULL, NULL, NULL, '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'); (5, 'N.K', NULL, NULL, NULL, NULL, '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00');  CREATE TABLE `bus_timings` (   `id` int(11) NOT NULL,   `route_id` int(11) NOT NULL,   `bus_id` int(11) NOT NULL,   `stop_id` int(11) NOT NULL,   `bus_time` varchar(255) NOT NULL,   `bus_direction` varchar(255) NOT NULL,   `trip` varchar(255) NOT NULL,   `created_at` datetime NOT NULL,   `updated_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `bus_timings` --  INSERT INTO `bus_timings` (`id`, `route_id`, `bus_id`, `stop_id`, `bus_time`, `bus_direction`, `trip`, `created_at`, `updated_at`) VALUES (8, 1, 1, 4, '08:26:00', '1', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (9, 1, 1, 5, '08:45:00', '1', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (21, 1, 1, 18, '10:45:00', '1', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (22, 1, 1, 1, '10:50:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (23, 1, 1, 27, '10:55:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (24, 1, 1, 2, '11:05:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (25, 1, 1, 20, '11:15:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (26, 1, 1, 3, '11:20:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (27, 1, 1, 6, '11:25:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (28, 1, 1, 19, '11:35:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (29, 1, 1, 4, '11:45:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (30, 1, 1, 5, '11:55:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (31, 1, 1, 21, '11:58:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (32, 1, 1, 7, '12:05:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (33, 1, 1, 22, '12:15:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (34, 1, 1, 23, '12:20:00', '2', '1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),  CREATE TABLE `routes` (   `id` int(11) NOT NULL,   `route_name` varchar(255) DEFAULT NULL,   `seo_url` varchar(255) NOT NULL,   `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,   `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `routes` --  INSERT INTO `routes` (`id`, `route_name`, `seo_url`, `created_at`, `updated_at`) VALUES (1, 'Sydney', 'sydney', '2017-12-26 08:46:16', '2017-12-26 08:46:16'), (2, 'Melbourne', 'melbourne', '2017-12-26 08:46:16', '2017-12-26 08:46:16'), (3, 'Perth', 'perth', '2017-12-26 08:46:16', '2017-12-26 08:46:16');   CREATE TABLE `route_connect` (   `id` int(11) NOT NULL,   `stop_id` int(11) DEFAULT NULL,   `bus_id` int(11) DEFAULT NULL,   `created_at` datetime NOT NULL,   `updated_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `route_connect` --  INSERT INTO `route_connect` (`id`, `stop_id`, `bus_id`, `created_at`, `updated_at`) VALUES (1, 2, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (2, 8, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (3, 14, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (4, 18, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (5, 14, 4, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (6, 18, 4, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),   -- --------------------------------------------------------  -- -- Table structure for table `stops` --  CREATE TABLE `stops` (   `id` int(11) NOT NULL,   `stop_name` varchar(255) DEFAULT NULL,   `created_at` datetime NOT NULL,   `updated_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `stops` --  INSERT INTO `stops` (`id`, `stop_name`, `created_at`, `updated_at`) VALUES (1, 'stop_1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (2, 'stop_2', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (3, 'stop_3', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (4, 'stop_4', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (5, 'stop_5', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (6, 'stop_6', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (7, 'stop_7', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (8, 'stop_8', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (9, 'stop_9', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (10, 'stop_10', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (11, 'stop_20', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (12, 'stop_21', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (13, 'stop_22', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (14, 'stop_23', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (15, 'stop_25', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (16, 'stop_37', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (17, 'stop_n1', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),   -- --------------------------------------------------------  -- -- Table structure for table `stop_orders` --  CREATE TABLE `stop_orders` (   `id` int(11) NOT NULL,   `route_id` int(11) DEFAULT NULL,   `stop_id` int(11) DEFAULT NULL,   `stop_orders` int(11) DEFAULT NULL,   `created_at` datetime NOT NULL,   `updated_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for table `stop_orders` --  INSERT INTO `stop_orders` (`id`, `route_id`, `stop_id`, `stop_orders`, `created_at`, `updated_at`) VALUES (1, 1, 1, 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (2, 1, 27, 2, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (3, 1, 2, 3, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (4, 1, 20, 4, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (5, 1, 3, 5, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (6, 1, 6, 6, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (7, 1, 19, 7, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (8, 1, 4, 8, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), 

Update-2 Gordon Linoff answer at one works fine.and that query not giving result when user select large time difference like 1 to 9 .This is because same bus will travel multiple times so group by will kill here if i remove group by then only one record will come even i tried many combination of group by

Updated

My project aim is to store all buses ,lines,stops and bus timing along with trip and direction. 1.There are many routes and each routes have multiple stops and few bus stops may belong to multiple routes (For example city 1 and city 2 route buses will travel in city 3 routes as per image provided)

2.in bus timing table i will store buses time along with route(line),stops trip and direction(Here trip and direction used because of one buse will travel between source to destination multiple times a day)

Output expecting

1.when user search between source to destination along with the time then application should return all buses travel between source and destination (if user select long time for example

2 clock to 12 clock )then it should return all buses here there are chances same buses result twice or more than that because every bus will travel more than twice

1 Answers

Answers 1

Because stop_id cannot be two different values in the same row.

Aggregation is one way to do what you want:

SELECT b.bus_name FROM buses b JOIN      route_connect rc      ON rc.busid = b.id JOIN      stops s      ON s.id = rc.stop_id GROUP BY b.bus_name HAVING SUM( s.stop_name = 'Sydney' ) > 0 AND        SUM( s.stop_name = 'Melbourne' ) > 0; 

This returns buses that have stops with the name of both cities.

Given that buses can have lots of stops, it might be more efficient to do:

SELECT b.bus_name FROM buses b JOIN      route_connect rc      ON rc.busid = b.id JOIN      stops s      ON s.id = rc.stop_id WHERE s.stop_name in ('Sydney', 'Melbourne') GROUP BY b.bus_name HAVING COUNT(DISTINCT s.stop_name) = 2; 
Read More

Sunday, December 31, 2017

Does not login into account at first time in Codeigniter 3 framework

Leave a Comment

I have a website and login system. In localhost everything is perfect. However, in the server (HOSTGATOR), when people want to log in their account, they type login password and hit "Login" button, it refreshes the page but does not log in. They should enter 2-3 times and then systems logs in. Where can be the problem?

public function __construct() {     parent::__construct();     $this->load->helper(array('form','url', 'security'));     $this->load->library(array('session', 'form_validation', 'email'));     $this->load->database();     $this->load->model('User_model'); }   public function login(){             $data['title'] = 'Sign In';          $validator = array('success' => false, 'messages' => array());          $validate_data = array(             array(                 'field' => 'usernameforlog',                 'label' => lang('controller-username-label'),                 'rules' => 'trim|required|alpha_dash'             ),             array(                 'field' => 'passwordforlog',                 'label' => lang('controller-password-label'),                 'rules' => 'trim|required|md5'             )         );          $this->form_validation->set_rules($validate_data);         $this->form_validation->set_message('required', lang("form_validation_required"));           $this->form_validation->set_message('alpha_dash', lang("form_validation_alpha_dash"));         $this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');                if ($this->form_validation->run() === FALSE)             {                  // fails                 $validator['success'] = false;                 foreach ($_POST as $key => $value) {                     $validator['messages'][$key] = form_error($key);                 }                  log_message('error', 'validation errors' );              }else {                  // Get username                 $username = mb_strtolower($this->input->post('usernameforlog'), 'UTF-8');                 // Get and encrypt the password                 $password = $this->input->post('passwordforlog');                 // Login user                  $user_id = $this->user_model->login($username, $password);                 if($user_id){                     // Create session                      $user_data = array(                      'id' => $user_id,                      'instructors_slug' => $username,                      'logged_in' => true                      );                      $this->session->set_userdata($user_data);                     $validator['success'] = true;                     $validator['messages'] = array();                 } else {                      $validator['success'] = false;                     $validator['messages'] = '<div class="alert alert-danger text-center">'.lang('controller-user-email-error3').'</div>';                 }                    }              echo json_encode($validator);         } 

Here is the ajax file:

$(document).ready(function() {     $("#loginform").unbind('submit').bind('submit', function() {         var form = $(this);          $.ajax({             url: form.attr('action'),             type: form.attr('method'),             data: form.serialize(),             dataType: 'json',             success:function(response) {             console.log(response);                               if(response.success) {                     //redirect main page                     location.reload();                 }                 else {                     $("#loginmsg").html(response.messages);                      $.each(response.messages, function(index, value) {                         var element = $("#"+index);                          $(element)                         .closest('.form-group')                         .removeClass('has-error')                         .removeClass('has-success')                         .addClass(value.length > 0 ? 'has-error' : 'has-success')                         .find('.text-danger').remove();                          $(element).after(value);                      });                 }             } // /success         });  // /ajax          return false;     }); }); 

1 Answers

Answers 1

because location.reload() will reload your login() page, in here you need to add method for checking if user has logged_in ?

public function login() {      $logged_in = $this->session->userdata('logged_in');      if($logged_in)     {         // example redirect to dashboard         redirect('dashboard', 'refresh');     }       // rest of code } 

instead just echo json_encode($validator); better set also your content header as application/json

return $this->output->set_content_type('application/json')->set_output(json_encode($this->response)); 
Read More

Friday, November 3, 2017

Wordpress and CI rewrite rule in htaccess

Leave a Comment

I have installed WordPress in example.com. I have also installed CodeIgniter in ci folder here example.com/ci/, ci is the folder name , register is the controller name and working URL of CI is example.com/ci/register .

Now I have one WordPress URL example.com/hotel, hotel is the page that I have created in WordPress admin, it works fine.

I want to run my CI path like example.com/hotel/ci/register, I think we can do it with some rewrite rule so that my URL would look like example.com/hotel/ci/register. I have added given htaccess for wordpress that redirecting me here example.com/hotel/ci/register. It is showing me 404 error of CI. It means now I am in CI. Now I did following things in routes.php file.

$route['default_controller'] = 'register'; $route['404_override'] = 'register'; 

Now this URL example.com/hotel/ci/register is working, but this is not right way, next time there will be more controllers then it will not work.

Note: I can not create hotel folder because hotel is a page in the WordPress. If I create hotel folder then WordPress URL example.com/hotel/ will not work. It will redirect WordPress page to the hotel folder. So I have to do it without creating hotel folder.

I need to find another good solution.Any advise or guidance would be greatly appreciated?

Following is my reWrite rule in wordpress htaccess:

# BEGIN WordPress    <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^/?hotel/ci/register(/.*)?$ /ci/$1 [L]     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule> # END WordPress 

And following is my CI htaccess:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L,QSA]  </IfModule> 

1 Answers

Answers 1

I think you are on the right path, try this:

# BEGIN WordPress    <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^/hotel/ci(/.*)?$ /ci/$1 [L]  # remove the register part                                                # so that it would be handled by CI                                               # also remove the "?" in front of hotel     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule> # END WordPress 

keep your CI htaccess as it is:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L,QSA]  </IfModule> 

the last part is match your CI config.php to your new url model

$config['base_url'] = "http://example.com/hotel/ci/"; 
Read More

Friday, October 27, 2017

Sessions not working in localhost but work in live server (Codeigniter)

Leave a Comment

I have been facing this issue since yesterday and yet I could not resolve this. Issue is sessions are not working in local environment but when for a testing purpose I put the same files on a live server, they work all okay.

Here if my config.php file:

$config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE;  $config['cookie_prefix']    = ''; $config['cookie_domain']    = ''; $config['cookie_path']      = '/'; $config['cookie_secure']    = FALSE; $config['cookie_httponly']  = FALSE; 

Here is how I save the data in one of my model files

$this->session->set_userdata('user',$result); //$result works fine, it produces right result 

In my view, I tried to access this by:

$this->session->userdata['user']['name']; //name here is an element in result array 

I get this error:

Severity: Notice

Message: Undefined index: user

Filename: home/home.php

Line Number: 2

To my surprise, this same code runs without any error on server.

Also, to be able to know the data being saved by Codeigniter sessions, I tried database method.

I changed the code to below in config.php file

$config['sess_driver'] = 'database'; $config['sess_cookie_name'] = 'ci_sessions'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; 

Instead of inserting one row of data, it inserts four. Please see below screenshot from the database (last four rows).

Database Screenshot

Can anybody point to the error? Any help will be appreciated.

5 Answers

Answers 1

Your question has a few parts, I'll answer each in turn.

Regarding retrieving values from the session

userdata() is a method. The way you are accessing it treats it as an array:

$this->session->userdata['user']['name']; // Bad 

As the docs describe, you should pass the key of the value you want to retrieve as a parameter to the userdata method:

$user = $this->session->userdata('user'); // Now you can echo $user['name']; 

Even simpler is to use the newer syntax:

$user = $this->session->user; // Now you can echo $user['name']; 

Regarding the 4 session records in the database

Check the timestamp fields. They show 3 different times, meaning those are 3 separate events on the site. The first occurs at 1501911275, then 6 seconds later there are another 2 records, and then 139 seconds later the last record. Those represent 3 separate requests to the site - probably you were visiting different pages, or testing and reloading.

As to why there are multiple records, that's because the session ID is periodically regenerated. Exactly how often that happens depends on your configuration see the sess_time_to_update config option. How often they are destroyed also depends on your config (see sess_regenerate_destroy in the same section of the docs) - but normally older session records stick around for a while and are cleaned up later by garbage collection. So while you have only 1 "current" session record, old records can persist for a while.

Regarding your sess_save_path

From the wording of your question I think you want to use the files session driver, and only tried the database driver for testing. If that's correct, there is a problem in your files session configuration which you should fix.

According to the docs:

only absolute paths are supported for $config['sess_save_path'].

The comments in config/config.php also say:

WARNING: Only absolute paths are supported!

Your configuration specifies that session data should be saved in ci_sessions, which is not an absolute path:

$config['sess_save_path'] = 'ci_sessions'; // Bad 

I am not sure how will be interpreted, but my guess is the directory won't exist, and the web server will not have permissions to create it. I can't imagine why it works on your live server.

Change the path to an absolute path, and make sure your web server can write to it. Again from the docs

mkdir /<path to your application directory>/sessions/ chmod 0700 /<path to your application directory>/sessions/ chown www-data /<path to your application directory>/sessions/ 

(change www-data to the user your web server is running as). And then:

$config['sess_save_path'] = '/<path to your application directory>/sessions/'; 

Answers 2

If you read the Codeigniter Class Reference setuserdata expects the second argument to be a value, that in case first argument is a key, hence the error.

with the Codeigniter way, you won't be able to achieve what you want as it uses:

set like this:

$result=array('name'=>'john doe');

$this->session->set_userdata($result); or $this->session->set_userdata('name','john doe');

get like this:

echo $this->session->userdata(['name']);

on the other hand using vanilla php $_SESSION you can achieve it like so:

set: $_SESSION['user']=$result;

get: echo $_SESSION['user']['name'];

see about $_SESSION at php manual

note:

To my surprise, this same code runs without any error on server.

this is due to your ENVIRONMENT setting, as you have error_reporting limited at the production (live) server. This is set in your root index.php.

change define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); to: define('ENVIRONMENT', 'production'); and you won't see the error on your localhost as well.

update:

Actually $this->session->set_userdata('name', $name); works, but the function userdata() only accepts one argument and expects it to be a string

if you look into session library (/system/libraries/Session/Session.php), you'll find it near row 747:

/**  * Userdata (fetch)  *  * Legacy CI_Session compatibility method  *  * @param   string  $key    Session data key  * @return  mixed   Session data value or NULL if not found  */ public function userdata($key = NULL) {     if (isset($key))     {         return isset($_SESSION[$key]) ? $_SESSION[$key] : NULL;     }     elseif (empty($_SESSION))     {         return array();     }      $userdata = array();     $_exclude = array_merge(         array('__ci_vars'),         $this->get_flash_keys(),         $this->get_temp_keys()     );      foreach (array_keys($_SESSION) as $key)     {         if ( ! in_array($key, $_exclude, TRUE))         {             $userdata[$key] = $_SESSION[$key];         }     }      return $userdata; } 

Answers 3

Follow these

In config.php

Set $config['sess_save_path'] = NULL; 

As you said $this->session->set_userdata('user',$result); //$result works fine, it produces above $result shoulb be like this

$result = array(     'user'  => 'Ab',     .....     'logged_in' => TRUE ); 

How To Access session key

echo $this->session->userdata('user'); 

or

$user = $this->session->userdata('user'); echo $user; 

Answers 4

Seems the issue was with PHP version 7.1 as CI 3.1.6 was not supporting that PHP version.

I'm not sure whether this is the correct explanation but when I switched back to PHP version 5.6, everything started working absolutely fine.

Answers 5

I think issue with access of session data with incorrect syntax.you can use below syntax for set session data and get session data.

Example for set session data

$session_data = array('name' => "kiran"); $this->session->set_userdata('user', $session_data); 

Example for get stored session data

$this->session->userdata('user')['name']; 
Read More

Sunday, September 24, 2017

how to check array in where condition in codeigniter?

Leave a Comment

in code igniter a group of student details check in fore-each loop ,the student get by the bases of student admission number

my admission numbers are in $ad_no=$this->input->post('adn_no'); :-

array(5) { [0]=> string(5) "11784" [1]=> string(5) "11837" [2]=> string(5) "11775" [3]=> string(5) "11937" [4]=> string(5) "12061" }

i try to select these admission numbers student, but the result show only first student result .

my code:

foreach($ad_no as $key => $id) {         $this - > db - > where_in('ad_no', $id);         $query = $this - > db - > get('duration');         $r = $query - > result_array();         $dur = $r[0]['tot_hr'];         $start = explode(':', $dur);         $end = explode(':', $tm);         $total_hours = $start[0] - $end[0];         $total_hours1 = $start[1] - $end[1];         $mins = abs($total_hours1);         $dur = $total_hours.":".$mins;         $durs[$key] =             array(                 'ad_no' => $ad_no[$key],                 'tot_hr' => $dur             );     }     $reslt = $this - > Daily_temp_model - > duration($durs); 

1 Answers

Answers 1

using array push in foreach loop

$result=[]; foreach($ad_no as $key => $id) {     $this->db->where_in('ad_no', $id);     $query = $this-> db-> get('duration');     $r = $query-> result_array();     array_push($result, $r);     $dur = $r[0]['tot_hr'];     $start = explode(':', $dur);     $end = explode(':', $tm);     $total_hours = $start[0] - $end[0];     $total_hours1 = $start[1] - $end[1];     $mins = abs($total_hours1);     $dur = $total_hours.":".$mins;     $durs[$key] =         array(             'ad_no' => $ad_no[$key],             'tot_hr' => $dur         ); } $reslt = $this->Daily_temp_model->duration($durs); 
Read More

Wednesday, August 2, 2017

How to preview and delete images in Krajee bootstrap?

Leave a Comment

Here is the setting of the initialize the file input. I have successfully done upload file but i want to edit than i cant preview images in the container of krajee bootstrap input. Please if anyone know give the full code to delete and preview.

 $("#userfiles").fileinput({               'dropZoneEnabled': true,               'maxFileCount': totalcount,               'showUpload': false,               'browseLabel': "Click Here or Drag & Drop Images Here",               'browseIcon': "<i class=\"glyphicon glyphicon-picture\"></i> ",               'validateInitialCount': true,               'allowedFileExtensions': ["jpg", "png", "gif", "jpeg"],               'showCaption': true,               'showPreview': true,               'showRemove': true  });    //This is the ajax for get images from database   $.ajax({ type: "POST", url: site_url+'posting/getpicdata', data: {pid: url}, dataType: "json", success: function(response)     {       //console.log(response);       //var result = JSON.parse(response);      $.each(response, function(k, v) {       //display the key and value pair       //console.log(v.url);       image_html = v.imgname;     appendHTML +='<div data-template="image" data-fileindex="0" id="'+v.imgname+'" class="file-preview-frame krajee-default  file-preview-initial file-sortable kv-preview-thumb">';         appendHTML +='<div class="kv-file-content">';         appendHTML +='<img style="width:auto;height:160px;"" alt="'+v.imgname+'" title="'+v.imgname+'" class="kv-preview-data file-preview-image" src="'+v.url+'">';         appendHTML +='</div>';         appendHTML +='<div class="file-thumbnail-footer">';         appendHTML +='<div title="'+v.imgname+'" class="file-footer-caption">'+v.imgname+' <br></div>';         appendHTML +='<div class="file-thumb-progress hide">';         appendHTML +='<div class="progress">';         appendHTML +='<div style="width:0%;" aria-valuemax="100" aria-valuemin="0" aria-valuenow="0" role="progressbar" class="progress-bar progress-bar-success progress-bar-striped active">0%</div>';         appendHTML +='</div>';         appendHTML +='</div>';         appendHTML +='<div class="file-actions">';         appendHTML +='<div class="file-footer-buttons">';         appendHTML +='<button title="Remove file" data-id="'+v.imgname+'" class="kv-file-remove btn btn-xs btn-default" type="button"><i class="glyphicon glyphicon-trash text-danger"></i></button>';         appendHTML +='</div>';         appendHTML +='<div title="Not uploaded yet" class="file-upload-indicator"><i class="glyphicon glyphicon-hand-down text-warning"></i></div>';         appendHTML +='<div class="clearfix"></div>';         appendHTML +='</div>';         appendHTML +='</div>';         appendHTML +='</div>';     }); 

2 Answers

Answers 1

Your question is not clear But I'm suppose that what you are looking how to preview the images in krajee plugin

<script>  $("#input-pd").fileinput({      uploadUrl: "/file-upload-batch/1",      uploadAsync: false,      minFileCount: 2,      maxFileCount: 5,      overwriteInitial: false,      initialPreview: [          // IMAGE DATA          "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Desert.jpg",          // IMAGE DATA          "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Lighthouse.jpg",          // VIDEO DATA          "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/small.mp4",          // PDF DATA          'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/pdf-sample.pdf',          // TEXT DATA          "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut mauris ut libero fermentum feugiat eu et dui. Mauris condimentum rhoncus enim, sed semper neque vestibulum id. Nulla semper, turpis ut consequat imperdiet, enim turpis aliquet orci, eget venenatis elit sapien non ante. Aliquam neque ipsum, rhoncus id ipsum et, volutpat tincidunt augue. Maecenas dolor libero, gravida nec est at, commodo tempor massa. Sed id feugiat massa. Pellentesque at est eu ante aliquam viverra ac sed est.",          // HTML DATA          '<div class="text-center">' +           '<h3>Lorem Ipsum</h3>' +           '<p><em>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</em></p>' +           '<h5><small>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</small></h5>' +           '<hr>' +           '</div>' +           '<div class="text-justify">' +           '<p>' +           'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed convallis convallis dolor sed dignissim. Phasellus euismod mauris vel dolor maximus, sed fermentum mauris lobortis. Aliquam luctus, diam in luctus egestas, magna lacus luctus libero, scelerisque mattis ante dolor ac nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse varius orci ultricies massa euismod, at semper turpis fermentum. Quisque vitae augue vel lectus viverra facilisis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla lacinia molestie diam, et volutpat nunc bibendum a. Cras a est sed augue commodo accumsan quis vitae nisi.' +           '</p>' +           '<p>' +           'Nunc sit amet metus et dui aliquet feugiat. Praesent lobortis, ipsum et elementum dignissim, urna libero fringilla justo, at tincidunt nisi mi sed mi. Integer vel est porttitor, tempor tortor non, lobortis felis. Curabitur porttitor nisi et volutpat iaculis. Fusce nec feugiat lectus, vitae ullamcorper lorem. Ut ultrices nunc imperdiet placerat malesuada. Proin commodo erat in egestas maximus.' +           '</p>'      ],      initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup      initialPreviewFileType: 'image', // image is the default and can be overridden in config below      initialPreviewConfig: [          {caption: "Desert.jpg", size: 827000, width: "120px", url: "/file-upload-batch/2", key: 1},          {caption: "Lighthouse.jpg", size: 549000, width: "120px", url: "/file-upload-batch/2", key: 2},           {type: "video", size: 375000, filetype: "video/mp4", caption: "KrajeeSample.mp4", url: "/file-upload-batch/2", key: 3},           {type: "pdf", size: 8000, caption: "About.pdf", url: "/file-upload-batch/2", key: 4},          {type: "text", size: 1430, caption: "LoremIpsum.txt", url: "/file-upload-batch/2", key: 5},           {type: "html", size: 3550, caption: "LoremIpsum.html", url: "/file-upload-batch/2", key: 6}      ],      purifyHtml: true, // this by default purifies HTML data for preview      uploadExtraData: {          img_key: "1000",          img_keywords: "happy, places",      }  }).on('filesorted', function(e, params) {      console.log('File sorted params', params);  }).on('fileuploaded', function(e, params) {      console.log('File uploaded params', params);  });  </script>
<!-- PREVIEW DATA -->  <!-- load the JS files in the right order -->  <!-- sortable plugin for sorting/rearranging initial preview -->  <script src="/path/to/js/plugins/sortable.min.js"></script>  <!-- purify plugin for safe rendering HTML content in preview -->  <script src="/path/to/js/plugins/purify.min.js"></script>  <script src="/path/to/js/fileinput.js"></script>     <label class="control-label">Select File</label>  <input id="input-pd" name="input-pd[]" type="file" multiple class="file-loading">

You must install this plugin through composer and add the links in header of your html file then it will work fine see the documentation

Answers 2

It's not totally clear what you are looking for, but I think it's something like this...

 <!-- PREVIEW DATA --> <!-- load the JS files in the right order --> <!-- sortable plugin for sorting/rearranging initial preview --> <script src="/path/to/js/plugins/sortable.min.js"></script> <!-- purify plugin for safe rendering HTML content in preview --> <script src="/path/to/js/plugins/purify.min.js"></script> <script src="/path/to/js/fileinput.js"></script>  <script> $("#userfiles").fileinput({           'dropZoneEnabled': true,           'maxFileCount': totalcount,           'showUpload': false,           'browseLabel': "Click Here or Drag & Drop Images Here",           'browseIcon': "<i class=\"glyphicon glyphicon-picture\"></i> ",           'validateInitialCount': true,           'allowedFileExtensions': ["jpg", "png", "gif", "jpeg"],           'showCaption': true,           'showPreview': true,           'showRemove': true,     uploadUrl: "/file-upload-batch/1",     uploadAsync: false,     minFileCount: 2,     maxFileCount: 5,     overwriteInitial: false,     initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup     initialPreviewFileType: 'image' // image is the default and can be overridden in initialPreviewConfig. see the docs (http://plugins.krajee.com/file-preview-management-demo) }).on('filesorted', function(e, params) {     console.log('File sorted params', params); }).on('fileuploaded', function(e, params) {     console.log('File uploaded params', params); }); </script> 
Read More

Tuesday, June 27, 2017

How to iterate over array in ionize-cms with codeigniter?

Leave a Comment

I'm using Ionize cms for the back end of my site and i want to create my own Tags - for passing data from my own tables. I've followed This tutorial to create custom tags, and by that - passing data to views, but i keep getting error :

Tag missing: demo, scope: .

Here is my view :

<ul>     <ion:demo:details>          <li><ion:detail field="user_name" /></li>     </ion:demo:details> </ul> 

And here are the changes I've added to TagManager.php

 public static $tag_definitions = array     (     // <ion:demo:authors /> calls the method “tag_details”     "demo:details" =>      "tag_details",     "demo:details:detail" =>    "tag_detail",     ); 

I've also tried to create a simple codeigniter controller and pass the data with view() and to do something like :

<ul>    <?php foreach($details as $detail): ?>      <li>      <?php echo $detail['name'] ?>      </li>     <?php endforeach ;?> </ul> 

But i'm getting undefined error of $details...

1 Answers

Answers 1

Got it... changed the tags and now it's good.

<?php   class TagManager_Data extends TagManager  { /**  * Tags declaration  * To be available, each tag must be declared in this static array.  *  * @var array  *  */ public static $tag_definitions = array (     // <ion:demo:authors /> calls the method “tag_authors”     "authors" =>      "tag_authors",     "authors:author" =>    "tag_author",      );      /**      * Base module tag    * The index function of this class refers to the <ion:#module_name /> tag    * In other words, this function makes the <ion:#module_name /> tag    * available as main module parent tag for all other tags defined  * in this class.  *  * @usage  <ion:demo >  *      ...  *    </ion:demo>  *     */    public static function index(FTL_Binding $tag)    {     $str = $tag->expand();      return $str;     }     /**  * Loops through authors  *  * @param FTL_Binding $tag  * @return string  *  * @usage  <ion:demo:authors >  *        ...  *    </ion:demo:authors>  *  */    public static function tag_authors(FTL_Binding $tag) {     // Returned string     $str = '';      // Model load     //self::load_model('demo_author_model', 'author_model');      // Authors array     $authors = [["name"=>'josh',"foo"=>'josh'],     ["name"=>'joshjosh',"foo"=>'josh'],["name"=>'josh',"foo"=>'josh']];      foreach($authors as $author)     {         // Set the local tag var "author"         $tag->set('author', $author);          // Tag expand : Process of the children tags         $str .= $tag->expand();     }      return $str;    }    /**  * Author tag  *  * @param    FTL_Binding    Tag object  * @return    String      Tag attribute or ''  *  * @usage    <ion:demo:authors>  *        <ion:author field="name" />  *       </ion:demo:authors>  *  */ public static function tag_author(FTL_Binding $tag) {     // Returns the field value or NULL if the attribute is not set     $field = $tag->getAttribute('field');      if ( ! is_null($field))     {         $author = $tag->get('author');          if ( ! empty($author[$field]))         {             return self::output_value($tag, $author[$field]);         }          // Here we have the choice :         // - Ether return nothing if the field attribute isn't set or          doesn't exist         // - Ether silently return ''         return self::show_tag_error(             $tag,             'The attribute <b>"field"</b> is not set'         );         // return '';     }     }   } 
Read More

Monday, April 17, 2017

Codeigniter - getting 404 Not Found error

Leave a Comment

We have two hosting packages at godaddy. Our live website is working fine using following .htaccess file. Website is accessible without using index.php in url.

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L]  

We used same htaccess file and same code on other hosting that is also by godaddy. We just wanted to make production and development instances seperate. But on other hosting with same code and htaccess file, website shows 404 page not found error but website works fine with index.php in url.

We have same php version on both server. Just wants to know what could be the issue?

9 Answers

Answers 1

I also faced the similar problem when I move my 100% working code to dedicated Debian server. After 3 hours of research, i found out why htaccess file is not working.You need to allow overriding of htaccess in Apache Configuration.

Here are the steps.

Step 1:

Add this in htaccess file

<IfModule mod_rewrite.c>     RewriteEngine on     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule ^(.*)$ index.php/$1 [L,QSA] </IfModule> 

Step 2:

Remove index.php in codeigniter config

$config['index_page'] = ''; 

Step 3:

Allow overriding htaccess in Apache Configuration (Command)

sudo nano /etc/apache2/apache2.conf 

and edit the file & change to

AllowOverride All 

for www folder

Step 4:

Restart Apache (Command)

sudo /etc/init.d/apache2 restart 

Before you make any changes in apache2.conf file make sure to make a backup copy of that file. If you are using Debian server you can avoid sudo command. I believe you know how to connect to your server using ssh client software like putty. Comment below if this method does not work for you.

Answers 2

I have limited knowledge in server networking but this should give you a few ideas.

First ,you must know what is .htacess file is. you can check it here link

.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

Basically .htaccess is giving you permission to edit the configuration of Apache Web Server. You will gain permission using .htacess if mod_rewrite is enabled in Apache. I will not write what that 4 basic line in .htaccess can do in codeigniter because you can find it in google. this link can give you some nice basic info.

Now the main issue is .htaccess is not working in your other hosting. This is possible because a few reason :

  1. For some reason, mod_rewrite is disabled in your Apache Web Server. If your hosting is VPS or DS it's possible you are didn't configuring it yet. Someone already ask how to enable mod_rewrite, you can go to this link. If you are using Shared Hosting, ask your hosting to enable mod.rewrite in your host. You can check if mod.rewrite enabled or not in your hosting following this link. Or you can simply check with <?php phpinfo(); ?> and check in "Loaded Modules" for mod_rewrite exist or not. Example in this image.
  2. You are not using Apache as Web Server. There are others Web Server as NGINX and lighttpd. You should ask your server administrator what Web Server are you use currently. I dont have any experience using NGINX and lighttpd so i cannot give you any help in that. But as far as i know .htaccess code is different in APACHE, NGINX, and lighttpd. You can try to convert .htaccess apache code to nginx code in here or here. For converting .htaccess to lighttpd unfortunately, i cannot find any online converter but there are official guide here and here
  3. Well for the complete tips sake i will write this. It's possible you are not configuring codeigniter to not use index.php. In config file, empty configuration for index_page. and give Base_url your domain name. $config['base_url'] = "yourdomainname.com"; $config['index_page'] = '';

I hope this clear your confussion why your .htaccess didnt work.

Answers 3

You can use this. This works for me in godaddy hosting.

RewriteEngine On  RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) index.php?/$1 

Answers 4

Try to lowercase all your controllers. This fix the problem for me.

Answers 5

try this one.. it's works for me..

DirectoryIndex index.php RewriteEngine on RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA] 

Answers 6

in index.php you echo "test" and run .then you can check whether it is called or not. in config file enable error log . Make your /application/logs folder writable. In /application/config/config.php set. $config['log_threshold'] = 4;

check the log /application/logs folder

Answers 7

I have faced the similar problem when I move on godaddy server.And It's work for me.

Add this code into your .htaccess file.

<IfModule mod_rewrite.c>     RewriteEngine On     RewriteCond %{REQUEST_FILENAME} !-f    RewriteCond %{REQUEST_FILENAME} !-d     # Rewrite all other URLs to index.php/URL    RewriteRule ^(.*)$ index.php?url=$1 [PT,L]   </IfModule> <IfModule !mod_rewrite.c>        ErrorDocument 404 index.php </IfModule> 

In config file:

$config['base_url'] = 'domain.com'; $config['index.php'] = ''; 

And Set AllowOverride to All in your httpd.conf

set the correct permission on the /cache folder, rather than just making the folder writable you need to make it reclusively writable.

I hope it will work for you.

Answers 8

Follow this

  • Create a new .htaccess file in your public_html/Project root
  • Paste the following code

    RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|resources|robots\.txt|static) [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/?$1 [L,QSA] 

  • Optional

If you can ssh into the server using command ssh username@ip_address on a command line either Linux terminal or Putty

The username is the one given to you by GoDaddy or you can use root

The ip_address would be the Public IP to your host you can find it in your hosting panel

Run the command sudo a2dissite 000-default

The command disables the default apache config that handles request

Goodluck!

Answers 9

As you mentioned here, on localhost your code is working fine but when you moved it over live server it causes 404 error. There might be few cases you need to check:

Step 1: Check mod_rewrite is enabled or not in your Apache configuration

Step 2: Remove index.php in codeigniter config as @geordy suggested

You can check it by

<?php echo 'Test'; die; ?> 

in your root index.php. It ensures your all requests should go through this files else Codeigniter framework would not work properly.

Read More

Wednesday, February 1, 2017

Securing API calls from cross domain using RESTful service

Leave a Comment

I have a booking site from where I provide a few lines of code to the user where I add API key in a div along with the code. The users are required to add these codes in their website. Then I load the view from my site over their site using ajax calls. My concern is: How can I make these calls secure using public and private API Key with restful web services using codeIgniter?

My code provided to user looks like

    <link rel="stylesheet" type="text/css" href="http://localhost/bookingpoints_com/apiTesting/styles/first.css" />     <script src="http://localhost/bookingpoints_com/contents/scripts/jquery.js" ></script>     <script src="http://localhost/bookingpoints_com/contents/scripts/apiused.js" ></script>     <script src="http://localhost/bookingpoints_com/apiTesting/scripts/common.js" ></script>              <div id="api-data-reserve" name="Njc4ZDI5ZDZiN2RlYzIxMzM1N2U3ZWRkOGEwYjhlNThhZmZiNDNjNXRlc3QgY29kZTE=" data="Njc4ZDI5ZDZiN2RlYzIxMzM1N2U3ZWRkOGEwYjhlNThhZmZiNDNjNW1HVnZ3YVhMRVc=" sitekey="Njc4ZDI5ZDZiN2RlYzIxMzM1N2U3ZWRkOGEwYjhlNThhZmZiNDNjNQ=="></div> 

By these lines of code I make an ajax call to my site and render the view on users site. How could I make it work like google's client and secret key structure with authentication using restful services using pure API architecture?

4 Answers

Answers 1

Ajax requests can be emulated by creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { //Request identified as ajax request }, However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

But this is not enough, you have to secure your Ajax call using server side scripting(e.g. PHP). For example, if your AJAX passes the key to the PHP file, write code in the PHP file to make sure that is the correct key.

Answers 2

Facebook, Google and other large companies uses iframe for these kind of services.
Take example of facebook it gives you on script to put in code which when runs will create an iframe for particular view.

Also you can not make cross-site ajax calls. Only iframe which is loaded from your site can securely load the page.

Now with the keys, you can always provide public key in script. The iframe href will point to you website with $_SERVER['http_referer'] where you can make sure the api key is authorized. Don't use private key unless you are not going to post any private confidential data.

Answers 3

I wrote an article awhile back on securing REST APIs, specifically those consumed by a browser. I recommend taking a look https://www.moesif.com/blog/technical/restful-apis/Authorization-on-RESTful-APIs/

Auth0, an authentication provider has quite a few resources also, I have no affiliation other than used them before and like their product.

Many APIs are secured through JWTs which are nice since they allow you to authenticate an API call without centralized auth servers. They are based on public/private crypto algorithms where the two keys are mathematically related. The keys are generated in a trusted environment such as your server, but anyone can verify that they come from who they say they did. You can design other authentication token schemes.

Depending on what you need, the keys will be accessible by any client, so you can design a specific permissions model to ensure the key has the rights of least privilege (i.e. they shouldn't have admin rights, etc)

Answers 4

Google is restricting the API key to specific URLs, so it can't just be copied.

Any item you use will be public, therefore it's useless to create private and public keys.

I don't know any existing frameworks, probably you have to build it from scratch. You have to implement a tool where users can register, create client ids and assign URLs to their client id. Then on each request you have to check if the referer is allowed for the given client id.

Read More

Tuesday, April 26, 2016

Phil Sturgeon's REST server, Codeigniter3, error messages no return on PUT

Leave a Comment

I am using Phil Sturgeon's REST server, CI3 and POSTMAN for debugging. I send a PUT with below info, however, I am not receiving the error messages expected.

Here is my form_validation.php:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');  $config = array(   'student_put' => array(     array('field' => 'email_address', 'label' => 'email_address', 'rules' => 'trim|required|valid_email'),     array('field' => 'password', 'label' => 'password', 'rules' => 'trim|required|min_length[8]|max_length[16]'),     array('field' => 'first_name', 'label' => 'first_name', 'rules' => 'trim|required|max_length[50]'),     array('field' => 'last_name', 'label' => 'last_name', 'rules' => 'trim|required|max_length[50]'),     array('field' => 'phone_number', 'label' => 'phone_number', 'rules' => 'trim|required|alpha_dash'),   ) );  ?> 

Here is my method in my controller Api.php:

function student_put(){     $this->form_validation->set_data($this->put());     // these are the rules set in config/form_validation.php     if ($this->form_validation->run('student_put') != FALSE) {         die('good data');     } else {          $this->response(              array(                 'status'=> 'failure',                  'message'=> $this->form_validation->get_errors_as_array(),                 ),              REST_Controller::HTTP_BAD_REQUEST           );     } } 

This is in my libraries folder as MY_Form_validation.php:

<?php  class MY_Form_validation extends CI_Form_validation {    function __construct($rules = array()) {       parent::__construct($rules);       $this->ci =& get_instance();   }    public function get_errors_as_array() {       return $this->_error_array;   }    public function get_config_rules() {       return $this->_config_rules;   }    public function get_field_names($form) {       $field_names = array();       $rules = $this->get_config_rules();       $rules = $rules[$form];       foreach ($rules as $index=> $info) {           $field_names[] = $info['field'];       }       return $field_names;   } } 

When I put following in POSTMAN:

X-API-KEY          123456 first_name         test email_address      abc 

This is the result I get:

{   "status": "failure",   "message": [] } 

But I should be getting the validation errors.

As debugging steps, I have confirmed: - no auth errors - the form_validation.php is being read - if I change:

'message'=> $this->form_validation->get_errors_as_array(), 

to

'message'=> 'test', 

the postman returns:

{ "status": "failure", "message": "test" } 

Any help very much appreciated.

1 Answers

Answers 1

you must read this link,

http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814

if you use apikey, you must set

    $config['rest_auth'] = 'basic'     $config['rest_enable_keys'] = TRUE; 

also make a table in database for storing api key

CREATE TABLE `keys` (     `id` INT(11) NOT NULL AUTO_INCREMENT,     `user_id` INT(11) NOT NULL,     `key` VARCHAR(40) NOT NULL,     `level` INT(2) NOT NULL,     `ignore_limits` TINYINT(1) NOT NULL DEFAULT '0',     `is_private_key` TINYINT(1)  NOT NULL DEFAULT '0',     `ip_addresses` TEXT NULL DEFAULT NULL,     `date_created` INT(11) NOT NULL,     PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

insert into that database minimum 1 row, the important column only key, it is the apikey

the apikey must contains 40 digits alphanumeric for security reasons

and again, you must read documentation, and the rest.php in application/config

    $config['rest_valid_logins'] = ['admin' => '1234']; 

that login is set by default, so you must insert that login in your header of client request, etc

    http_user           'admin'     http_pass           '1234'     X-API-KEY           '123456'     first_name          test     email_address       abc 

if that header not work, try this

    http_user           'admin'     http_pass           '1234'     api_name            'X-API-KEY'     api_key             '123456'     first_name          test     email_address       abc 

if you have try request like this before with your

    $config['rest_auth'] = FALSE 

actually you not yet securing your api webservice

Read More

Sunday, April 10, 2016

PHP+fork(): How to run a fork in a PHP code

Leave a Comment

I am running my code on CodeIgniter - Ubuntu Server.

I have been researching for async ways to run functions. I use CodeIgniter.

This is my function:

<?php         // Registers a new keyword for prod to the DB.      public function add_keyword() {          $keyword_p = $this->input->post('key_word');          $prod      = $this->input->post('prod_name');         $prod      = $this->kas_model->search_prod_name($prod);         $prod      = $prod[0]->prod_id;          $country   = $this->input->post('key_country');          $keyword = explode(", ", $keyword_p);         var_dump($keyword);          $keyword_count = count($keyword);         echo "the keyword count: $keyword_count";          // problematic part that needs forking         for ($i=0; $i < $keyword_count ; $i++) {               // get new vars from $keyword_count             // run API functions to get new data_arrays             // inserts new data for each $keyword_count to the DB           }          // Redirect to main page.          redirect('banana/kas');       } 

The "foreach" uses variables with slow APIs, and updates the database.

I saw some tutorials using fork but haven't quite understood the syntax part of it. Most of the things I found were just exmplanations of how it works (2 processes: parent-child ect') but non-gave a good explanation of how applying this on the code.

Can someone explain how I work with the fork() syntax?

Continue PHP execution after sending HTTP response

http://www.onlinetechtutorials.com/2014/06/how-to-run-php-code-asynchronously.html

http://php.net/manual/en/function.pcntl-fork.php (more general)

From the server side: https://www.youtube.com/watch?v=xVSPv-9x3gk

EDIT:

Did I get it right?

<?php     // Registers a new keyword for prod to the DB.  public function add_keyword() {      $keyword_p = $this->input->post('key_word');      $prod      = $this->input->post('prod_name');     $prod      = $this->kas_model->search_prod_name($prod);     $prod      = $prod[0]->prod_id;      $country   = $this->input->post('key_country');      $keyword = explode(", ", $keyword_p);     var_dump($keyword);      $keyword_count = count($keyword);     echo "the keyword count: $keyword_count";      for ($i=0; $i < $keyword_count ; $i++) {          // create your next fork         $pid = pcntl_fork();          if(!$pid){             //*** get new vars from $keyword_count             //*** run API functions to get new data_arrays             //*** inserts new data for each $keyword_count to the DB              print "In child $i\n";             exit($i);             // end child         }     }      // we are the parent (main), check child's (optional)     while(pcntl_waitpid(0, $status) != -1){         $status = pcntl_wexitstatus($status);          echo "Child $status completed\n";     }      // your other main code: Redirect to main page.      redirect('banana/kas');   } ?> 

This won't cause any problem with using this inside a loop? will it know to stack each process?

3 Answers

Answers 1

You must mention what's the operating system that you are using, because pcntl extensions are not available on Windows platform
Also you must be aware that activating process control on Linux/Unix within a web server can give you unexpected results, so only CLI/CGI mode is recommended to use PCNTL
Please read carefully this PCNTL Introduction

Now, your code seems to be correct and well implemented, but you must compile your PHP with this option --enable-pcntl to enable pcntl functions like int pcntl_fork(void) otherwise you will get

Fatal error: Call to undefined function pcntl_fork()

For me, the best solution to run functions/methods in asynchronous way is to use pthreads, if you are interested by this advice i can edit my response by adding examples and how to install it on Windows or Linux platforms

Read this article to know how to compile PHP

Answers 2

You have one fork after your pcntl_fork(), check $pid and then you can use it. Repeat for more forks.

<?php     for($i = 1; $i <= 3; ++$i){         // create your next fork         $pid = pcntl_fork();          if(!$pid){             // begin child, your execution code             sleep(1);             print "In child $i\n";             exit($i);             // end child         }     }      // we are the parent (main), check child's (optional)     while(pcntl_waitpid(0, $status) != -1){         $status = pcntl_wexitstatus($status);         echo "Child $status completed\n";     }     // your other main code ?> 

For async http requests you can use multicurl: http://php.net/manual/en/function.curl-multi-init.php

Answers 3

As far as I am aware of, you can achieve this in two ways...

Use:

  • Pthreads
  • Amphp
  • Pthreads is a parallel processing library, while amp is a pure asynchronous framework...

    So, the way for using pthreads would be to first download/enable the pthreads extension and add extension=/path/to/pthread.so in the php.ini file...

    And then create a class, which extends the Thread Class and override the method run, and put everything inside it, which you want to do parallely.

    So for your specific purpose the the class could be something like this:

    <?php class Inserter extends Thread {     public $db_con = null;     public $data;      public function __construct($db_connection, $data) {         $this->db_con = $db_connection;         $this->data = data;     }      private function run() {         // use your logic to insert the data...     } } 

    To use that, just instantiate the class, and put the the DB connection variable, and the data to be processed in the ctor. And call the start method of the object. Like:

    $inserter = new Inserter($dbConn, $data); $inserter->start(); 

    Where $dbConn stores the DB connection and $data stores the necessary data.

    And that's it...

    Read More

    Sunday, March 27, 2016

    codeigniter form POST Empty in Controller from View

    Leave a Comment

    I'm working with Codeigniter. I have created an HTML form which post data to the Controller.

    This Form was working perfectly but it suddenly stopped posting data.

    HTML:

    <form name="frm_search" id="frm_search" method="post" action="http://ip/free/index.php/taskdetails/tabOne/1/ShibNo/asc/"> <input  id="order1" name="order1" value="26" type="text" > <input  id="item1" name="item1" value="" type="text" > </form> 
    1. I tried to check the data post in Browser and it shows the data that I input in the input box.

    enter image description here

    1. In My index.php I placed the following code to see if it is posted:
    echo "CONTENT_TYPE: " . $_SERVER['CONTENT_TYPE'] . ""; $data = file_get_contents('php://input'); echo "DATA: <pre>"; var_dump($data); var_dump($_POST); echo "</pre>";  exit;  

    RESULT:

    CONTENT_TYPE: application/x-www-form-urlencoded

    string 'order1=26&item1='

    array (size=23)
    'order1' => string '26' (length=2)
    'item1' => string '' (length=0)

    But when I print $_POST in controller I get the following:

    Array (     [order1] =>      [item1] => ) 
    1. My .htaccess code as follows:

      RewriteEngine on  RewriteCond $1 !^(index\\.php|resources|robots\\.txt)  RewriteCond %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d  RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

    Can someone tell me what's the issue? I'm not able to find out why is it when the data passes to controller it becomes null. The application was running successfully for more than a year but I got this issue suddenly.

    Thank you in advance. Kindly let me know if you need any more to help me.

    Note: I figured out Once page loaded, If i edit the name of the input time to some other name then the data is post successfully.

    i.e: instead of order1, If I change the name my editing using inspect element in chrome to "neworder" Then if I submit, the data submits with value to controller. Dont know why?

    Update: I found some this strange. In the set-cookie of the browser. Its like a full page of junk.

    each time when the page is called i start a new session but i wont kill the existing session. Is that a problem?

    Even If i destory the old session and start new one i get eh set-cookies in browser. It has to me one.. but in my case i get more then 6 set cookies in the browser.

    1 Answers

    Answers 1

    It could be a .htaccess issue with RewriteRule, according to this CI github post issue https://github.com/bcit-ci/CodeIgniter/issues/242:

    if Apache server is used then mod rewrite should be enabled, otherwise redirection will be proper but with empty $_POST.

    &

    if you don't have a trailing slash on your URL the server will send a 301 redirect which will interfere with POST data.

    Your problem could be with

    RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

    Try changing to:

    RewriteRule ^(.*)$ index.php/$1 [PT,L] 

    (from: not able get post form submit values in codeigniter) or try to set:

    sudo a2enmod rewrite 

    Hope it helps!

    Read More