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

Saturday 28 September 2019

How to create/write code in text/json file and get content of file in PHP | Codeigniter

Create file and directory
public function createfileanddir() {
    $directoryname = 'directoryname';
    $filename = 1;
    $directory = APPPATH . 'uploads/cache/'.$directoryname;
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }
    $file = APPPATH . 'uploads/cache/'.$directoryname.'/'.$filename.'.json';
    if (file_exists($file)) {
        unlink($file);
    }
    if (!file_exists($file)) {
        $settings = [
            'settings'=>[],
            'socialSettingsArr'=>[],
            'pageSettings'=>[],
        ];
        $fh = fopen($file, 'w');
        fwrite($fh, json_encode($settings));
        fclose($fh);
    }
}
Get content from file and directory
public function getfiles() {
    $directoryname = 'directoryname';
    $directory = 'uploads/cache/'.$directoryname;
    $files = array_diff(scandir($directory), array('.', '..'));
    if(count($files) > 0){
        foreach ($files as $file):
            $file = $directory . '/'.$file;
            $storedata = file_get_contents($file);
            $storedata = json_decode($storedata, true);
            echo '<pre>';print_r($storedata);
        endforeach;
    }
}

Friday 2 August 2019

How to set cron job in heroku in PHP | Codeigniter

Step 1:  Install Heroku Scheduler add-ons from Heroku.


Step 2: Goto Heroku Scheduler page and add Job, set time interval and add command " php /app/index.php orderupdate crontset jaydip "
  1. php = server language
  2. /app/index.php = Path of the project root index.php
  3. orderupdate = name of controller
  4. crontset = name of function
  5. jaydip = variable name which you want to get into crontset function
Step 3: open Orderupdate.php controller

public crontset function($name){

echo $name;

}

Monday 31 December 2018

sql_mode=only_full_group_by is incompatible in PHP mysql query with GROUP BY codeigniter


#1055 - Expression #24 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'customers.first_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Add $this->db->query("SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));") line above your query.

See Example :
$this->db->query("SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));");
$this->db->select('*, customers.first_name, customers.last_name, customers.id');
$this->db->select("(SELECT count(video_id) FROM customer_videos WHERE c.customer_id = customer_videos.customer_id AND (created_at >= '$from' OR created_at <= '$todate')) as seen");
$this->db->join('customers', 'customers.id = c.customer_id', 'left');
$this->db->group_by('c.customer_id');
$this->db->from('customer_videos as c');
$query = $this->db->get();
echo "<pre/>"; print_r($query->result());exit;
return $query->result_array();

Saturday 8 October 2016

How to upload products multiple images in codeigniter Gocart in admin panel

Open : gocart/views/admin/iframe/product_image_uploader.php

<?php include('header.php');?>
<script type="text/javascript">
 
<?php if( $this->input->post('submit') ):?>
$(window).ready(function(){
        $('#iframe_uploader', window.parent.document).height($('body').height()); });
<?php endif;?>
<?php if($file_name):?>
        parent.add_product_image('<?php echo json_encode($file_name);?>');
<?php endif;?>
 
</script>
<?php if (!empty($error)): ?>
    <div class="alert alert-error">
        <a class="close" data-dismiss="alert">×</a>
        <?php echo $error; ?>
    </div>
<?php endif; ?>
<div class="row-fluid">
    <div class="col-md-12">
        <?php echo form_open_multipart($this->config->item('admin_folder') . '/products/product_image_upload', 'class="form-inline "'); ?>
        <?php echo form_upload(array('name' => 'userfile[]', 'id' => 'userfile', 'class' => 'input-file', 'multiple'=>"true" )); ?>
        <input class="btn" name="submit" type="submit" value="<?php echo lang('upload'); ?>" />
        </form>
    </div>
</div>
<?php include('footer.php');


Open : gocart/controllers/admin/products.php

Update product_image_upload() function

function product_image_upload() {
        $data['file_name'] = false;
        $data['error'] = false;
        $config['allowed_types'] = 'gif|jpg|png';
        //$config['max_size'] = $this->config->item('size_limit');
        $config['upload_path'] = 'uploads/images/full';
        $config['encrypt_name'] = true;
        $config['remove_spaces'] = true;
        $this->load->library('upload', $config);
        $files = $_FILES;
     
        $cpt = count($_FILES['userfile']['name']);
        for($i=0; $i<$cpt; $i++)
        {
            $_FILES['userfile']['name']= $files['userfile']['name'][$i];
            $_FILES['userfile']['type']= $files['userfile']['type'][$i];
            $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
            $_FILES['userfile']['error']= $files['userfile']['error'][$i];
            $_FILES['userfile']['size']= $files['userfile']['size'][$i];

            //$this->upload->initialize($this->set_upload_options());
         
            if ($this->upload->do_upload()) {
                $upload_data = $this->upload->data();
             
                $this->load->library('image_lib');
                /*
                  I find that ImageMagick is more efficient that GD2 but not everyone has it
                  if your server has ImageMagick then you can change out the line
                  $config['image_library'] = 'gd2';
                  with
                  $config['library_path'] = '/usr/bin/convert'; //make sure you use the correct path to ImageMagic
                  $config['image_library'] = 'ImageMagick';
                 */
                //this is the larger image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/full/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 600;
                $config['height'] = 500;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //small image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 235;
                $config['height'] = 235;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //cropped thumbnail
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/thumbnails/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 150;
                $config['height'] = 150;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                $data['file_name'][] = $upload_data['file_name'];
            }
        }
        if ($this->upload->display_errors() != '') {
            $data['error'] = $this->upload->display_errors();
        }
        $this->load->view($this->config->item('admin_folder') . '/iframe/product_image_uploader', $data);
    }


Open : gocart/views/admin/product_form.php

Update : add_product_image(data) function


function add_product_image(data) {
     
        var $images = $.parseJSON(data);
        $.each($images, function(i, image) {
            p = image.split('.');
            var photo = '<?php add_image("' + p[0] + '", "' + p[0] + '.' + p[1] + '", '
            ', '
            ', '
            ', base_url('
            uploads / images / thumbnails '));?>';
            $('#gc_photos').append(photo);
            $('#gc_photos').sortable('destroy');
            photos_sortable();
        });
    }

Tuesday 13 September 2016

How to Check URL is Secure or Not in amazon EC2 Server in PHP / Codeigniter SSL

You can use following code for  Check URL is Secure or Not in amazon EC2 Server


if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
      $_SERVER['HTTPS'] = 'on';
} else {
      $_SERVER['HTTPS'] = 'off';
}

Tuesday 30 August 2016

How to Get / Upload / Delete / Update file in using SFTP / FTP in PHP, Codeigniter Library

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol

Here is a small code on how to read the folder and download all files:

Controller.php

      $params = array('host' => $shopdata->ftphost, 'port' => 22);
            $this->load->library('sftpconnection', $params);
         
            $this->sftpconnection->login($shopdata->ftpuser, $shopdata->ftppass);
            //$this->sftpconnection->uploadFile("http://localhost/shopify/inventorymanagement/uploads/sku.csv", "/codetest/test.csv");
            //$result = $this->sftpconnection->scanFilesystem("/TEST/DESADV");
            $result = $this->sftpconnection->downloadFiles("$folder","/TEST/DESADV/");
            pre($result);
Create Library file : Sftpconnection.php

<?php
/*
  Sftp connection in PHP
  Created: Feb 18th, 2016
  Modified: Feb 18th, 2016
  Version: 1.0.1
  Auther : Jaydip Kanasagra
 */

//this function is just to make the code a little cleaner
class Sftpconnection {

    private $connection;
    private $sftp;

    public function __construct($config) {
        $host = $config['host'];
        $port = $config['port'];
        $this->connection = @ssh2_connect($host, $port);
        if (!$this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password) {
        if (!@ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
            "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (!$this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (!$stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }

    public function receiveFile($remote_file, $local_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (!$stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents($local_file, $contents);
        @fclose($stream);
    }
 
    public function downloadFiles($local_dir, $remote_dir) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_dir";
        $downloadedfiles = $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
     
        foreach ($files as $file)
        {
            $currentdir = $this->getCurrentdirfiles('uploads/ftpfiles/TEST/JAYDIP/');
            if(in_array($file, $currentdir)){
                continue;
            }
         
            echo "Copying file: $file<br>";
            if (!$remote = @fopen("ssh2.sftp://{$sftp}{$remote_dir}{$file}", 'r'))
            {
                echo "Unable to open remote file: $file\n";
                continue;
            }

            if (!$local = @fopen($local_dir . $file, 'w'))
            {
                echo "Unable to create local file: $file\n";
                continue;
            }

            $read = 0;
            $filesize = filesize("ssh2.sftp://{$sftp}/{$remote_dir}{$file}");
            while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
            {
                $read += strlen($buffer);
                if (fwrite($local, $buffer) === FALSE)
                {
                    echo "Unable to write to local file: $file\n";
                    break;
                }
            }
            $downloadedfiles[] = $file;
            fclose($local);
            fclose($remote);
        }

        return $downloadedfiles;
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
 
    function getCurrentdirfiles($dir){
        //$dir = "ftpfiles/TEST/JAYDIP/";
        $listfiles = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $listfiles[] = $file;
                }
            }
        }
        closedir($handle);
        return $listfiles;
    }

}

?>

Monday 6 June 2016

https%3A%2F%2F Forbidden You don't have permission to access in PHP, Codeigniter, .net

It seems like my shared host provider is detecting the presence of "http://www" or "http%3A%2F%2Fwww" in any get request and serving up a 403 page.
I also get an 'in addition' error...

"Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request."
This only happens with this string. If I change it to something else the get is successfully submitted and the target page successfully returned.
If it helps I'm writing a QR code getter, so the ability to submit urls is quite important.
Also, strangely I can submit a url as long as it doesn't have 'www' in it. I can also submit 'www' as long as it isn't preceded by 'http://' (or the encoded version)
edit: Just to confirm this wasn't a specific problem with the page I was writing, I went to another page on my website that uses get request and manually inserted the string. This also generates the 403 error.

Answers

Request to remove this strange security feature or "ModSecurity" of your account from your provider (Hosting Provider).
Don't send urls with http://www in URL. For example replace https%3A%2F%2F to https:// before sending data PHP.

Wednesday 1 June 2016

Codeigniter Query in mysql With JOIN, GroupBy, Select Into Select, IFNULL, SUM, IF Condition

Codeigniter Query

function getitemsofseller($sellers){
       
        //For get total funds of the seller and set flag on item
        $i=0;
        $banne = 0;
        $results = array();
        foreach ($sellers as $seller):
           
            $this->db->select('*');
       
            /*Get homepage banner fee*/
            $this->db->select("SUM(IF(home_page_banner = 1 , (((paid_price+shipping_price)*quantity)*".MAIN_BANNER_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) )) as mainbannerfee");
           
            /*Get feature banner fee*/
            $this->db->select("SUM(IF(featured_product = 1, IF(is_buytribe = 1, (((paid_price+shipping_price)*quantity)*".FEATURE_BT_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".FEATURE_BIN_FEE.")/100) ) , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) )) as featurefee");
           
            /*Get nominal fee*/
            $this->db->select("SUM(IF(((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) > 0.50 ,((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) , (1/2))) as nominalfee", false);
           
            /*Get Total payment which is payed to seller ((paid_price+shipping_price)*quantity)-mainbannerfee-featurefee-nominalfee*/
            $this->db->select("(SUM((((paid_price+shipping_price)*quantity)"
                    . "-(IF(home_page_banner = 1 , (((paid_price+shipping_price)*quantity)*".MAIN_BANNER_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))"
                    . "-(IF(featured_product = 1, IF(is_buytribe = 1, (((paid_price+shipping_price)*quantity)*".FEATURE_BT_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".FEATURE_BIN_FEE.")/100) ) , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))"
                    . "-(IF(((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) > 0.50 ,((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) , (1/2)))))) as sellerpaid", false);
           
            /*Get return product payment (SUM(((paid_price+shipping_price)*quantity)+home_page_banner+featurebanner+nominalfee) */
            $this->db->select("IFNULL((SELECT SUM(((paid_price+shipping_price)*quantity)+(IF(home_page_banner = 1, (((paid_price+shipping_price)*quantity)*".MAIN_BANNER_FEE.")/100, ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))+(IF(featured_product = 1, IF(is_buytribe = 1, (((paid_price+shipping_price)*quantity)*".FEATURE_BT_FEE.")/100, ((((paid_price+shipping_price)*quantity)*".FEATURE_BIN_FEE.")/100) ), ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))) FROM (".prefix('order_items')." as btoi) WHERE `seller_id` = oi.seller_id AND btoi.lisiting_id = oi.lisiting_id AND `dispute_raised` = '0' AND `ispaidtoseller` = '0' AND `is_paid` = '3' AND `item_status` = 'Completed' GROUP BY `lisiting_id`),0) as refunds", false);
           
            /*Get return product payment (((paid_price+shipping_price)*quantity)-mainbannerfee-featurefee-nominalfee)-returned ((SUM(((paid_price+shipping_price)*quantity)+home_page_banner+featurebanner+nominalfee)) */
            $this->db->select("(SUM((((paid_price+shipping_price)*quantity)"
                    . "-(IF(home_page_banner = 1 , (((paid_price+shipping_price)*quantity)*".MAIN_BANNER_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))"
                    . "-(IF(featured_product = 1, IF(is_buytribe = 1, (((paid_price+shipping_price)*quantity)*".FEATURE_BT_FEE.")/100 , ((((paid_price+shipping_price)*quantity)*".FEATURE_BIN_FEE.")/100) ) , ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))"
                    . "-(IF(((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) > 0.50 ,((((paid_price+shipping_price)*quantity)*IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0))/100) , (1/2)))))"
                    . "-IFNULL((SELECT SUM(((paid_price+shipping_price)*quantity)+(IF(home_page_banner = 1, (((paid_price+shipping_price)*quantity)*".MAIN_BANNER_FEE.")/100, ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))+(IF(featured_product = 1, IF(is_buytribe = 1, (((paid_price+shipping_price)*quantity)*".FEATURE_BT_FEE.")/100, ((((paid_price+shipping_price)*quantity)*".FEATURE_BIN_FEE.")/100) ), ((((paid_price+shipping_price)*quantity)*".$banne.")/100) ))) FROM (".prefix('order_items')." as btjoi) WHERE `seller_id` = oi.seller_id AND btjoi.lisiting_id = oi.lisiting_id AND `dispute_raised` = '0' AND `ispaidtoseller` = '0' AND `is_paid` = '3' AND `item_status` = 'Completed' GROUP BY `lisiting_id`),0)) as sellerpaidafterfee", false);
           
           
            /*Get Return Qty (if is_paid = 3)*/
            $this->db->select("IFNULL((SELECT SUM(quantity) FROM ".prefix('order_items').' WHERE dispute_raised = 0 && item_status = "Completed" && ispaidtoseller = 0 && is_paid = 3 && `lisiting_id` = oi.lisiting_id LIMIT 1),0) as returnqty', false);
           
            /*Gross Revenue SUM((paid_price+shipping_price)*quantity)*/
            $this->db->select("SUM((paid_price+shipping_price)*quantity) as grossrevenue", false);
           
            /*Get nominal fee in percentage(%) */
            $this->db->select("IFNULL((SELECT `c`.commission FROM ".prefix('category_products')." JOIN ".prefix('categories')." as c ON `c`.`id` = ".prefix('category_products').".`category_id` && c.parent_id = 0 WHERE `product_id` = oi.product_id), 0) as nominalfeeper", false);
           
            /* Get total shipping charge */
            $this->db->select("SUM(shipping_price) as totalshipping", false);
           
            /* Get total product price without fee*/
            $this->db->select("SUM(paid_price)*quantity as totalproductprice", false);
           
            /* Get total quantity without calculate returned*/
            $this->db->select("SUM(quantity) as unitsold");
           
            /* Get total quantity without calculate returned*/
            $this->db->select(MAIN_BANNER_FEE." as mainbannerfeestatic", false);
           
            $this->db->select("IF(is_buytribe = 1 , ".FEATURE_BT_FEE." , ((1*".FEATURE_BIN_FEE.")) ) as featurefeestatic", false);
           
            $this->db->from("order_items as oi");
            $this->db->group_by('lisiting_id');
            $this->db->where('seller_id', $seller->seller_id);
            $this->db->where('dispute_raised', '0');
            $this->db->where('ispaidtoseller', '0');
            $this->db->where('item_status', 'Completed');
           
            $query = $this->db->get();
           
            //echo $this->db->last_query();exit;
            if($query->num_rows() > 0){
                $results[$i] = $query->result();
            }
            $i++;
        endforeach;
       
        return $results;
    }

Wednesday 4 May 2016

Convert PHP, Magento, Joomla, Codeigniter, Cake PHP, Wordpress XML to JSON, XML to Array, JSON to Array

Convert PHP, Magento, Joomla, Codeigniter, Cake PHP, Wordpress XML to JSON, XML to Array, JSON to Array is very difficult task for some people. But, in PHP, believe me it’s very easy. One line of code each! Don’t believe? Just check out the code below and test it yourself!


$xml = simplexml_load_string($xmldata);
$json = json_encode($xml);
$array = json_decode($json,true);

Monday 18 April 2016

How to get user ip in PHP/Codeigniter

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone's private RFC1918 address may not do you any good if you're say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There's no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There's only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

For Codeigniter


$this->input->ip_address();

For PHP

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
echo $ip;

Saturday 9 April 2016

How to get last week' date range in PHP, Codeigniter, CakePHP

$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last sunday midnight",$previous_week);
$end_week = strtotime("next saturday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
echo $start_week.' '.$end_week ;

Monday 28 March 2016

How to get Controller, Action/Function/Method, URL informations in CodeIgniter PHP

You could use the URI Class:
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
You can also use this in-built functions of codeigniter.
$this->router->fetch_class();
$this->router->fetch_method(); 

Friday 26 June 2015

CodeIgniter Remove index.php from URL

change in .htaccess file and try it

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

Pagination in CodeIgniter

Controller:
------------------------
public function index() {
        $count = $this->dcategory->Count_drugcategories();
        $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
        $this->load->library('pagination');
        $config['base_url'] = base_url('drug_categories');
        $config['use_page_numbers'] = TRUE;
        $config['total_rows'] = $count;
        $config['per_page'] = 10;
        $config["uri_segment"] = 2;
        $this->pagination->initialize($config);
        $limit = $config['per_page'];
        $start = ($page  == 0) ? 0 : ($page * $config['per_page']) - $config['per_page'];
        $data['query'] = $this->dcategory->Getlist_drugcategories($start,$limit);      
        $seo['title'] = 'Drug Categories List | ekimed';
        $data['links'] = $this->pagination->create_links();
        $this->load->view('layout/header',$seo);
        $this->load->view('drug_categories/listdrugcategories',$data);
        $this->load->view('layout/footer');
    }

Model:
----------------------
function Getlist_drugcategories($limit=0,$start=0){
        $this->db->select('*');
        if($limit>0 && $start>=0) {
            $this->db->limit($limit,$start);
        } else {
            $this->db->limit(10);
        }
        $query = $this->db->get($this->drugs_category);
        if($query->num_rows() > 0){
            return $query->result();
        } 
        return FALSE;
    }

Views:
-----------
<?php echo $links; ?>

Inserting multiple rows mysql in codeigniter

if your php version>=5.4 it should work.
You may try this

if ($_POST) { $row_ids=$this->input->post('id'); $desc=$this->input->post('desc'); $spaces=$this->input->post('space'); $prices=$this->input->post('price'); $totals=$this->input->post('total'); $data = array(); for ($i = 0; $i < count($this->input->post('id')); $i++) { $data[$i] = array( 'row_id' => $row_ids[$i], 'desc' => $desc[$i], 'space' => $spaces[$i], 'price' => $prices[$i], 'total' => $totals[$i], 'code' => time() ); } $this->Home_model->create($data); }

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 
 
After
 
$_config[0] =& $config;return $_config[0];  

How to called codeigniter helper function using JQuery AJAX?

You need to make a request via controller, then call that function through that controller, something like:
 
 
$("#id").change(function()
{       
 $.ajax({
     type: "POST",
     url: base_url + "controller_name/your_function", 
     data: {val: $("#your_val").val(),currency_id: $("#your_cur").val()},
     dataType: "JSON",  
     cache:false,
     success: 
          function(data){
            $("#your_elem").val(data.price);
      }
});
 
 
Then on your controller:

public function yourfunction()
{
   $data = $this->input->post();
   $price = format_price($data['val'],$data['currency_id']);
   echo json_encode(array('price' => $price));
}

PHP - CodeIgniter - Invalid argument supplied for foreach()

<?php if(is_array($result)): ?>
<?php foreach($result as $row):?>  
<h3><? echo $row->title; ?></h3>  
<p><? echo $row->text; ?></p>  
<?php endforeach;?>  
<?php endif; ?>