Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14348 articles
Browse latest View live

CodeIgniter with PostgreSQL and PgBouncer in Transaction mode

$
0
0
Previously we used PostgreSQL 9 with PgBouncer in session mode, and with that was able to easily create a new record and get the last ID with db->insert_id('table', 'pk_column').

But the use of the Session mode of PgBouncer proved to be extremely problematic for us, with several operations per second, the Pool easily reached the capacity of connections, so we switched to PostgreSQL 12 with PgBouncer in Transaction mode.

One problem that has begun to occur with this mode is that using operations that require being in the same session does not work, not allowing to use CURRVAL, which is used by insert_id(), 

Example of Insert created by CodeIgniter 3:
Code:
INSERT INTO "table" ("column") VALUES ('ABC');
SELECT pg_get_serial_sequence('table', 'tableid') AS seq;
SELECT CURRVAL('public.table_tableid_seq') AS ins_id;

This code will trigger the error:
Quote:currval has not yet been defined this session

Is there any configuration that must be done in CodeIgniter to work with PgBouncer in transaction mode?

Files management module

$
0
0
Hi all! I thought I posted about this one when I released the initial version, but I can't find the thread so maybe I forgot to? Either way, if you've never heard of Tatter\Files then you're in luck: it's better than ever!

Tatter\Files: File Uploads and Management
https://github.com/tattersoftware/codeigniter4-files

"Files" is a self-contained file management suite, with its own routes, model, controller, and view. Install via Composer, update your database, and voila! instant file management.
But it's better! The whole thing is modular and very configurable/extendable. Don't want just anyone to upload? No problem, adjust permissions for every CRUD action and route. Want to embed files in en existing page? No problem, requests respond to AJAX or you may load the view directly. See the README for all the things you could possibly configure.

A significant motivating factor for this version was to take advantage of the underlying packages and their powerful improvements: Tatter\Handlers, Tatter\Exports, and Tatter\Thumbnails. All these modules have been refactored to eliminate extra steps (like unnecessary migrations), apply full static analysis and unit tests, and fix a slew of bugs.

"Files" is better than ever, but there are bound to be bugs and missing features. I welcome your feedback here, or on the GitHub repo.

Quick Start:

1. Install with Composer: > composer require tatter/files
2. Migrate the database: > php spark migrate -all
3. Seed the database: > php spark dbConfusedeed "Tatter\Files\Database\Seeds\FileSeeder"
4. Start managing files: https://example.com/files

By default Files configures the "/files/" route and is set up in a loose dropbox mode where anyone can upload files and view existing versions. Permissions can be applied directly to the model with a simple chmod-style "mode" (e.g. 755), via controller filters, or with a whole authentication suite (like Myth:Auth).
The MVC portion of the module uses its Config file to adjust behavior, which you can copy into App and change as needed. Controllers/Files.php contains a number of helper methods that make it easy to extend, so your own "app/Controllers/Widgets.php" can extend "Tatter\Files\Controllers\Files" to make easy lists of widget files.

Some screenshots.

[Image: 96811765-ff82c500-13e9-11eb-9f1d-c9461ef1a438.png]

[Image: 96811782-00b3f200-13ea-11eb-9f39-df56362e1d2b.png]

[Image: 96811800-01e51f00-13ea-11eb-8a2d-f06ae5dff469.png]

Override page cache functionality

$
0
0
Hi,

I would like to use the page cache with 
Code:
$this->cachePage(600);

However, it should never use the cache is the user is logged in on site. I can check this with 
Code:
if ($session->logged_in)

But it the page is already cached, it won't run any logic. So I don't know how to do a check before the cache is fetched. My first thought was to override the function cache in Common.php, but I don't think that would be enough?

Now I'm trying to override system/Cache/Handlers/FileHandler.php in get() and getItem(). It doesn't seem to work though. I followed the this guide: https://codeigniter.com/user_guide/exten...asses.html

Could be that the cache is not automatically run and I cannot override it this way.

Would it be possible to write my own cache handler?

I also tried emptying the cache on all requests when logged in, but it affects all users of course, and if multiple visitors are on site at the same times it get's messy.

Any ideas for me, on how to do conditional caching? It's ok if it does cache the page as long as the cached page is not returned when logged in.

Thanks Smile

Codeigniter 4 routing not working on live server

$
0
0
hi,
i am developing a website.its working fine on local.But when i uploaded it to windows server,only default controller working.getting 
"Not Found
The requested document was not found on this server."

document root is httpdocs/public.
here is the htaccess  on public.
Code:
# Disable directory browsing
Options All -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    # RewriteBase /

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]
        

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
      

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
    ServerSignature Off
# Disable server signature end
and htacces on httpdocs
Code:
<IfModule mod_rewrite.c>
DirectoryIndex /public/index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|assets|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./public/index.php/$1 [L,QSA]
</IfModule>
and here is the route
Code:
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
$routes->match(['get', 'post'], '/Login', 'Home::login');

configuration files as array?

$
0
0
I am passing some environment settings to a view template but how do I pass it as an Array to avoid below error?

TypeError
Argument 2 passed to view() must be of the type array, object given





PHP Code:
<?php namespace Config;

use 
CodeIgniter\Config\BaseConfig;

class 
TestConfig extends BaseConfig
{
    /*
    |--------------------------------------------------------------------------
    | CAPTCHA
    |--------------------------------------------------------------------------
    |
     */
    public $captcha 1


PHP Code:
// Access config class with namespace
$config config'Config\\TestConfig' );

echo 
view('login'$config); 

Can anyone help me with this one.

$
0
0
http://sqlfiddle.com/#!9/a9ec7e/4/0

Code:
SELECT
        p.*
    FROM
        (
          -- For every product_id, find maximum created_at time
          SELECT
              product_id, max(created_at) AS created_at
          FROM
              purchases
          GROUP BY
              product_id
         ) AS mx
         -- JOIN to the whole table
         JOIN purchases p ON
              mx.product_id = p.product_id AND mx.created_at = p.created_at
    ORDER BY
         product_id ;

Thats exactly what i need for my project.
But i can't / dont know how to do this query in codeigniter.

Im using CodeIgniter 3.

[Việt Nam] - Codeigniter 4 Forum

About Library

$
0
0
class Donaturlib {


   function 
is_admin()
    {            
        
$ci     =&get_instance();
            
$cek $ci->donaturlib->security();    
                        if(
$cek != null)
                        {
                                       foreach (
$cek as $key) {
                                       
$username =  $key->username;
                                       }
                                       
$hasil $ci->donaturlib->getPeople($username);
                                       foreach (
$hasil as $levelnya ) {
                                           
$lv $levelnya->level;
                                       }
                                       if (
$lv != 1) {
                                           return 
false;
                                       }
                                       else
                                       {
                                           return 
true;
                                       }
                        }else{
        
$msg="<div class='alert alert-danger alert-dismissible' role='alert'>
  <button type='button' class='close' data-dismiss='alert'>
  <span aria-hidden='true'>&times;</span><span class='sr-only'>Close</span></button>
  <strong>Harap login terlebih dahulu
</div>"
;
        
$ci->session->set_flashdata('donatur',$msg);
        
redirect('welcome','refresh');
                        }

   }
    function 
getPeople($username)
    {
            
$ci     =&get_instance();
            
$query  =   $ci->db->query("select level from user where username ='$username'");
            return 
$query->result();
    }
    function 
checkexist($namadonasi,$tabel1)
    {
            
$ci         =   &get_instance();
            
$fieldpilih    ='*'
            
$hasil         $ci->modeldonatur->pilihdata($tabel1,$namadonasi,$fieldpilih);    
            if(
$hasil!=null)
            {
                return 
true;
            }
            else
            {
                return 
false;
            }
    }
    function 
security()
        {
            
$ci     =&get_instance();
            
$vCuser     $ci->input->cookie('dnt_user');
            
$vCsesi     $ci->input->cookie('dnt_sesi');
            
$tbl='logindata';
            
$fieldpilih='*'
            
$fieldkondisi=array('username'=>$vCuser,'sesi'=>$vCsesi);             
            
$hasil      $ci->modeldonatur->pilihdata($tbl,$fieldkondisi,$fieldpilih);
            
            if(
$hasil!=null)
            {
            
//simpan ke cookie
            
$vCookie1['name']   = 'ik_inv_ck_user';
            
$vCookie1['value']  = $vCuser;
            
$vCookie1['expire'] = '600';
            
$ci->input->set_cookie($vCookie1);
            
            
//simpan ke cookie token/sesi   
            
$vCookie2['name']   = 'ik_inv_ck_sesi';
            
$vCookie2['value']   = $vCsesi;
            
$vCookie2['expire']  = '600';
            
$ci->input->set_cookie($vCookie2);
            }
            
            return 
$hasil;
        }

 } 

retrieve parameters from url and build dynamic queries

$
0
0
Hi everyone, I'm new with codeigniter. I have this problem. I have a western table with data and a view that shows everything. Procedural php code use when I wanted to generate an art director page I put the link followed by? :

director? id_regista = $ id_regista

then I went to the landing page and filled in the select with the recovery in GET. But here on codeigniter it doesn't work! I've tried several model-like things:

SOLUTION A:

Details VIEW:

                  echo "<h5><a href='index.php/western/regista/$id_regista/'>.$row->regia</a></h5>";

Details MODEL:

function regista()

  {

    $id_regista= $this->uri->segment(3);
    $query  = $this->db->select('*')
      ->from('western')
      ->where('id_regista', '$id_regista') // Condition
      ->get();
    return $query->result();
  }


___________________________________________________________________________________________________________

OR SOLUTION B

VIEW:    echo "<h5><a href='index.php/western/regista?id_regista=$id_regista'>.$row->regia</a></h5>";

Model:

  function regista1()

  {

    echo $this->input->get('$id_regista');

    $query = $this->db->query("SELECT * FROM western where 'id_regista' = '$id_regista'");

    if ($query->num_rows() == 0) {

      show_error('empty db!');
    } else {

      return $query->result();
    }
  }

but both solutions do not dynamically generate the corresponding director for me starting from the home director link.

How do I retrieve the parameter and fill the query to build the page since

    $id_regista = $_GET['id_regista'];

put in model don't work?

For either solution A or B use in the Western controller

    function regista()
        {
 

                $this->load->model('western_model');
                $data['result'] = $this->western_model->regista();
                $this->load->view('regista_view', $data);
        }


and I also bothered to insert in the index

$this->load->helper('url');

thanks in advance on some helpful tips to solve, I have tried everything but I can't solve the parameter capture problem either using GET or segment
.png   Schermata 23-10-2020 10.35.10.png (Size: 332.67 KB / Downloads: 0)

json_encode issue

$
0
0
I am trying to build a json representation of an array. My array is 

$request = array();
$request["registration.applicationId"] = $applicationID;
$requestJ = json_encode($request);  //convert the array into json


when I run this $requestJ becomes $requestJ = {"registration.applicationId":"32688330-1630-4e0d-a4de-8ae45c3ca527"}

but the documentation for the package I am using shows this as valid

Code:
{
  "registration": {
    "applicationId": "10000000-0000-0002-0000-000000000001",
Notice how the package's demo has a registration section while mine has registration.applicationId? How do I get json_encode to create a json like the sample? 

404 on routes in sub folder

$
0
0
I inherited a codeigniter website, and upgraded codeigniter. Figured out the controller files have to start with capital letters, and I got most of the routes and views working again. Except for the Admin portion of the site. The routes for this portion is not in the routes.php file, but in a different file. And the controllers is in a sub directory called admin, which I renamed to Admin. So even though there is for example an entry:

PHP Code:
$route['admin'] = 'admin/admin/index' 

When I go to /admin I get 404, and logs show:
Code:
404 Page Not Found: Admin/admin

I've even tried putting eg
PHP Code:
$route['admin/login'] = "admin/admin/login"
in the routes.php file, but I still see in the logs
Code:
404 Page Not Found: Admin/admin
even though:

Code:
$ grep admin config/routes.php
route['admin/login'] = "admin/admin/login";
$ grep login controllers/Admin/Admin.php
    public function login()
How can I troubleshoot these 404 errors in order to properly load the routes in the sub folder?

MySQL UNION statement and Query Builder?

$
0
0
Is there any way to write a MySQL UNION statement with Query Builder?  I have reviewed the documentation and cannot find the answer.

assets folder not found after remove public from url

$
0
0
I add/create new .htaccess and add to my root folder for remove public from url:

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

this solution work for me and remove public from url but when I add assets(css/js) in my header, codeigniter not found my assets folder ie:

Code:
<link rel="stylesheet" href="<?php echo base_url('assets/vendor/bootstrap/css/bootstrap.css'); ?>">

output is:

Code:
http://ci.local/assets/vendor/bootstrap/css/bootstrap.css">

This address not work(not found), how do can I fix this problem?

Pre format rules ignored - CI4 Validation

$
0
0
Hi Team,

If I apply any rule to CI4 Validation that returns string instead of boolean, that rule is skipped. No effect on data output / formatting.

Like this.

PHP Code:
$validation->setRules([
    'username' => 'trim|required',
    'password' => 'required|min_length[10]'
]); 

PHP Code:
$request->getPostGet('username'); // Username is not trimmed. 

This used to be working fine in CI3. How can I attain the same in CI4?

displaying an image in a template

$
0
0
I have a view file that is being loaded with this:

$this->output->set_template('default3');

inside default3 I have this bit of code.

<?php
if ($_GET['typo']=="PHARMA"){
      echo '<script type="text/JavaScript">
      <img src="<?php echo base_url(); ?>assets/themes/default/images/new_blue_logo_sub240x240.png" style="float:left;margin-top:5px;z-index:5" alt="logo"/>
      </script>;
    }


if ($_GET['typo']=="SOFTWARE"){         <<this line is causing the error
      echo '<script type="text/JavaScript">
      <img src="<?php echo base_url(); ?>assets/themes/default/images/output-onlinepngtools (8).png" style="float:left;margin-top:5px;z-index:5" alt="logo"/>
      </script>;
    };
?>


I am trying to get either one of those two images to appear. But the second $_GET causes an error: 
Message: syntax error, unexpected 'typo' (T_STRING), expecting ',' or ';'
Why is this?

Very little error in online documentation

$
0
0
In this page, https://codeigniter.com/user_guide/datab...sults.html





At method "getRowArray()" section, the documentation says :



Quote:Identical to the above row() method, except it returns an array.


But the method "row()" not exists in CI4. No?



So, it's a very little change from "row()" to "getRow()". Shy

Why choose CodeIgniter

$
0
0
Hi,
I just got acquainted with CodeIgniter. I see in documetation that "CodeIgniter is right for you if you need exceptional performance".
I can't understand about that.  Who has experience please help me.
Thanks.

Simple CMS

$
0
0
I was thinking of perhaps some kind of simple CMS for small businesses to make a website with pages like homepage, map, menu prices, contact etc... but perhaps this is a bit complex just to showcase the framework. Another idea would be a simple forum, but perhaps someone would have a better idea for a simple project.
I've had a course module and then practical training experience working with the Microsoft's ASP.NET MVC with C#. That was ok, but I'm a Linux guy and have coded (badly) with php as a hobby for some years. I would much rather further my knowledge of php and MVC design architecture which I really liked using with ASP.NET. My front end skills are also up to scratch.

Report page with multiple Parts/Sections

$
0
0
Hi guys ,

I'm lost at this so I want an opinion if it's doable  :

I was asked to see if I can create an online version of a report we now do in excel. The report is quite big
around 50 pages  more or less . It has 10 Main Parts , each part may have up to 20  Sub Parts and
each subpart  contains questions the user fills in by selecting check boxes , one is yes no
and one is 3 different choices (H. M L as High,Medium, Low) and two additional check-boxes.
I'm thinking that the best was to have a single page with all the Main Parts in place and have
a (button ?) to open each additional Sub Part and it's relevant questions with a save/add function.
The thing is I haven't seen any real life example on how (or if it is possible) to do such a workflow
with codeigniter. I have seen similar work with two tables with Datatables plugin  and ajax with php
for example but nothing that uses plain codigniter framework, most examples use a simple view for data.
So the question is this  something  beyond the capabilities of codeigniter and I should turn into
something else to accomplish it or this is something I could do with the framework as is?

Thanks.

basic Helper get your defines routes list

$
0
0
PHP Code:
function app_route_list()
    {
        
$routes = \Config\Services::routes();
        
$routes $routes->getRoutes();
        
        
$arrR = [];
        foreach (
$routes as $key => $val)
        {
            if (
is_string($val)) {
                
$arr explode('/'$key);
                
$cR  '';
                
$cM  '';
                foreach (
$arr as $ind => $item)
                {
                    if (
$ind == && $item != '/') {
                        
$cR $item;
                    } else if (
$item != '' && $item != '(.*)') {
                        
$cM $item;
                    }
                }
                if (
$cR != '') {
                    
$arrR[$cR][] = $cM;
                }
            } else {
                break;
            }
        }
        
        foreach (
$arrR as $key => $val)
        {
            
$arr = [];
            foreach (
$val as $item)
            {
                if (
$item != '') {
                    
$arr[] = $item;
                }
            }
            if (
count($arr)) {
                
$arrR[$key] = $arr;
            } else {
                
$arrR[$key] = '';
            }
        }
        
        return 
$arrR;
    }
    
    
/*
        Example Return :: 
        
        Array
        (
            [mining] => Array
                (
                    [0] => initblock
                    [1] => inittoken
                    [2] => firstblock
                    [3] => miningstart
                    [4] => miningelapsed
                    [5] => miningend
                    [6] => miningresult
                    [7] => validblock
                    [8] => ...
                )

            [register] => 
            [login] => 
            [logout] => 
            [encrypt] => 
            [decrypt] => 
            [records] => 
            [factory] => 
            [coin] => 
            [miner] => 
            [index] => 
            [buycoin] => 
            [sellcoin] => 
            [deposit] => 
            [withdraw] => 
            [validtoken] => 
            [...] => ...
        )
    */ 

Use for setting role by route and method
Viewing all 14348 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>