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

A model that calls a store procedure that returns multipal tables

$
0
0
Hello.
Hope your well.
I am fairly new to PHP frameworks. But I have a project I'm doing where I need to call a store procedure that returns multipal tables.  I have no issues setting up the model and the call is working, but the issue is the multipal tables being returned I can only ever access the first table, there is meant to be 11 tables being returned and the store procedure works as expected but when I try and put the tables into an array of tables I only ever get the first table.

I have tried a few things like looping through the response, using the Mysqli_next_result. But nothing works.
Codeignitor V4.4.4
Running on cyberpanel open light speed server. For "production"  just using spark for testing.
Any ideas on how to fix this would be great.

[Solved] Initialising Session with BaseController

$
0
0
I'm trying to initialise Sessions in the BaseController but I'm getting error Attempt to read property "driver" on null
My Config\app variables

public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler';
public $sessionCookieName = 'ci_session';
public $sessionExpiration = 7200;
public $sessionSavePath = WRITEPATH . 'session';
public $sessionTimeToUpdate = 300;

My Base class
Code:
<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
*    class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
class BaseController extends Controller
{
    /**
    * Instance of the main Request object.
    *
    * @var CLIRequest|IncomingRequest
    */
    protected $request;

    /**
    * An array of helpers to be loaded automatically upon
    * class instantiation. These helpers will be available
    * to all other controllers that extend BaseController.
    *
    * @var array
    */
    protected $helpers = [];

    /**
    * @var string
    * Holds the session instance
    */
    protected $session;

    /**
    * Constructor.
    */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
       
      // Ensure that the session is started and running
      if (session_status() == PHP_SESSION_NONE)
      {
          $this->session = \Config\Services::session();
      }
    }
}

PHP Attributes Routes

$
0
0
Good Morning Everyone,
Longtime No Talk.
I've seen the package by Kenjis for PHP Route Attributes (haven't tried it yet but will be soon), Question is, Is there any plans in the not to distant future to integrate this into the main framework? Only reason I ask is, personally, I like the idea of keeping Routes together with Controllers.

Cache doesn't work, InfoCache.php throws errors

$
0
0
I'm trying to figure out why my caching isn't working. It's set to filesystem
Code:
public string $handler = 'file';)
I haven't changed anything in the initial app/Config/Cache.php. .env is set to: CI_ENVIRONMENT = development . I haven't found any indication in the help at https://www.codeigniter.com/user_guide/l...ching.html or https://www.codeigniter.com/user_guide/g...ching.html that there are automatic differences depending on the ENV.

In the controller method I use:
Code:
$this->cachePage($this->cacheTTL);

The controller property is defined as:
Code:
protected $cacheTTL = 604800;

Nothing is created under writeable/cache.

In the console,
Code:
php spark cache:info
results in:
Quote:CodeIgniter v4.5.2 Command Line Tool - Server Time: 2024-06-16 16:02:35 UTC+02:00

[Error]
Object of class CodeIgniter\Cache\Handlers\DummyHandler could not be converted to string
at SYSTEMPATH\Commands\Cache\InfoCache.php:70

Backtrace:
  1    SYSTEMPATH\CLI\Commands.php:70
      CodeIgniter\Commands\Cache\InfoCache()->run([])

  2    SYSTEMPATH\CLI\Console.php:48
      CodeIgniter\CLI\Commands()->run('cache:info', [])

  3    SYSTEMPATH\Boot.php:351
      CodeIgniter\CLI\Console()->run()

  4    SYSTEMPATH\Boot.php:104
      CodeIgniter\Boot::runCommand(Object(CodeIgniter\CLI\Console))

  5    ROOTPATH\spark:84
      CodeIgniter\Boot::bootSpark(Object(Config\Paths))

This error should not actually occur because there is a check:
Code:
if ($config->handler !== 'file') {
    CLI::error('This command only supports the file cache handler.');

    return;
}
Does anyone know what's going wrong here? I'm using Windows 11 Pro with a Wamp Server.

Edit:
Code:
var_dump(cache()->isSupported('file'));

=> bool(true)

I do not get it Sad

Solution:

Through further debugging, I discovered that the write protection is always set by Windows Explorer. I was able to solve it using cmd and then

Code:
attrib -r "C:\path\ci4directory\writable" /S /D

Fatal error on setting CI_ENVIRONMENT to testing

$
0
0
I just downloaded the latest CI in my local xampp server. I was using php 8.2. When I changed the variable  CI_ENVIRONMENT = testing in  .env file. I got the below error:
Fatal error: Uncaught Error: Undefined constant "CodeIgniter\Config\SUPPORTPATH" in C:\xampp82\htdocs\imflancer\system\Config\AutoloadConfig.php:144 Stack trace: #0 C:\xampp82\htdocs\imflancer\system\Boot.php(244): CodeIgniter\Config\AutoloadConfig->__construct() #1 C:\xampp82\htdocs\imflancer\system\Boot.php(54): CodeIgniter\Boot::loadAutoloader() #2 C:\xampp82\htdocs\imflancer\public\index.php(56): CodeIgniter\Boot::bootWeb(Object(Config\Paths)) #3 {main} thrown in C:\xampp82\htdocs\imflancer\system\Config\AutoloadConfig.php on line 144

Requesting to check and fix the issue.

Error handling with Ajax requests

$
0
0
Hi there,
is there a way to customize the error that is being showed in production environment when the request is made with Ajax? Currently for normal requests the response is the Whoops page, but for Ajax requests only "" is returned. Is there a way add a custom message or something?

Thanks!

sqlite3 and result ordering according to non-ASCII collations

$
0
0
For a while I was not sure how to order query results in Codeigniter when using sqlite3 database, which natively lacks non-ascii text collation functions. So I resorted to sorting php arrays, which is quite suboptimal with larger datasets.

When I took a closer look, I realized that it is quite simple to handle sorting in vanilla PHP case. Below I post an example of creating a Lithuanian collation and using it with sqlite3.

But I see createCollation and createFunction sqlite3 driver methods are not used in Codeigniter4 code. So I have to find a way to implement these myself.

Could someone take a look at the vanilla php example below and maybe throw in a suggestion on how to optimally do that in Codeigniter?

Vanilla php example

PHP Code:
// the locale offers proper collation order, set it if it is not default
setlocale(LC_ALL'lt_LT.UTF-8');

$db = new SQLite3(baz.db);

// create collation
$db->createCollation('LT', function ($a$b) {
   return strcoll($a$b);
});

// create alternative to native LOWER function for case-insensitive comparisons
$db->createFunction('LT_LOWER', function ($str) {
   return mb_strtolower($str);
}); 

And you continue as if you were using native sqlite3 functions:

PHP Code:
$results $db->query('SELECT bar FROM foo where LT_LOWER(foo) LIKE %Žemai%' ORDER BY bar ASC COLLATE LT);
while (
$row $results->fetchArray()) {
    var_dump($row);


You can also assign this LT collation as default to individual columns when creating a table (and then omit it in select statements), but then you won't be able to read that table without declaring those additional collation methods before the basic select queries.

Enhance Your Tailwind CSS Skills: Essential Tips and Tricks


Curl best practice for API calls? Protecting sensitive data like API keys

$
0
0
Hey! Assuming I use the following in a self-created OpenAI library:
PHP Code:
<?php
namespace App\Libraries;

class 
OpenAILibrary
{
    public function __construct()
    {
        $this->apiKey getenv('OPENAI_API_KEY');
        $this->curl service(
            'curlrequest',
            [
                'baseURI' => 'https://api.openai.com/v1/',
                'headers' => [
                    'Authorization' => 'Bearer ' $this->apiKey,
                    'Content-Type' => 'application/json',
                ],
            ]
        );
    }



If I then use the curlrequest service elsewhere in the application, this could potentially cause my API key to be accidentally sent to other servers (shared instance - https://codeigniter.com/user_guide/conce...vices.html). Or do I understand the information under https://codeigniter.com/user_guide/libra...quest.html since version 4.4.0 correctly, that $shareOptions = false by default ensures that I don't need to worry about this?

Are there other things to keep in mind here?

Thanks for your help!

Update docs: Testing > Benchmarks

$
0
0
Hi there! It's described here: https://www.codeigniter.com/user_guide/t...ution-time timer()->getElapsedTime('render view'); Returns elapsed time in seconds. But it's microseconds.

PHP Code:
/**
    * Returns the array of timers, with the duration pre-calculated for you.
    *
    * @param int $decimals Number of decimal places
    */
    public function getTimers(int $decimals 4): array
    {
        $timers $this->timers;

        foreach ($timers as &$timer) {
            if (empty($timer['end'])) {
                $timer['end'] = microtime(true);
            }

            $timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
        }

        return $timers;
    

ci_session is it secure and other questions

$
0
0
Hello!
I was wondering about 2 questions.
1. Is the ci_session (sess cookie name) secure?
2. If I try to add a prefix to it like __Secure, it breaks the URL. Example index(login) will then route me to localhost/dashboard/localhost/dashboard/index. Why is this? What in the ci_session control's this? 

Thank you for your time.

Htmx 2.0 released, aims to replace complex JavaScript frameworks with easily understo

Why CI4 mail not working on smpt now like gmail

$
0
0
Mail failure - rejected by local scanning code

(The message that you sent was rejected by the local scanning code that
checks incoming messages in the system. The following error was givenSmile

Settings
public string $SMTPHost = 'smtp.gmail.com';
    /**
    * SMTP Username
    */
    public string $SMTPUser = 'dinna@gmail.com'

Help with server setup

$
0
0
Hello everyone, I have created a multiple applications inside of  codeingiter which share the common system folder by following the guide in Code Igniter documentation.
The setup is as follows (I have removed the application and system folder outside the public_html as I have read it provides security)
codeigniter/
application/
project1/
project2
system/
webroot/
index.php  -Points to project1
project2.php  --Points to project2

I am able to call my applications in the following way
example.com
example.com/project2.php
Now the problem is that I want to setup these on a server as the following Urls.
example.com
project2.example.com
How can I achieve this ...I am a newbie to codeigniter..

form_open / $request->getMethod

$
0
0
Hello,



I getting mad about this one and don't know if it really has to do with CI (I use 4.5.1).



When I use form_open resp. form_open_multipart and submit the form, the $_REQUEST variable is empty. I could nail it down to the fact that form_open adds a method="post" attribute and this seems to be the problem...



my view:



Code:
<?php
echo form_open('addTest/add/','style="display: inline" id="formLoad"');

echo form_label('Latitude: ');
echo form_input(array('name'=>'latitude','style'=>'width:1em','value'=>0)).'&deg; <br/>';

echo form_submit('save','Save');
echo form_close();
?>


my controller:



Code:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;

class AddTest extends Controller {

public function add() {
   
    echo 'Value of $_REQUEST:';
    print_r($_REQUEST);
    echo '<br/>Method:';
    print_r(strtolower($this->request->getMethod()));

  }
}

?>
the output:



Value of $_REQUEST:Array ( )

Method:get



So, although the form_open generates a form tag with method="post", getMethod() finds a "get" method.

If I replace the first line of my view (the line with form_open) with the same form tag as the one produced by form_open, but without the two attributes method="post" and accept-charset="utf-8"



Code:
echo '<form action="http://localhost/index.php/addTest/add/" style="display: inline" id="formLoad">';


the result is, as expected:



Value of $_REQUEST:Array ( [latitude] => 0 [save] => Save )
Method:get



I could of course as a workaround use the html code directly but I would like to understand what happens here.

Any idea where to search?



thanks in advance

Philippe

5 Reasons Why Your Side Projects Fail to Make Money And How to Avoid Them

404 default Controller Home 2nd method

$
0
0
Hi,
i setup a new Project with CI4. 
app/Config/Feature.php
PHP Code:
public bool $autoRoutesImproved true

app/Config/Routing.php
PHP Code:
public string $defaultController 'Home';
public 
bool $autoRoute true

app/Config/Routes.php
PHP Code:
<?php

use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */
//$routes->get('/', 'Home::index');

service('auth')->routes($routes); 

app/Controllers/Home.php
PHP Code:
<?php

namespace App\Controllers;

class 
Home extends BaseController
{
    public function getIndex(): string
    
{
        return "Home";
    }
    public function getTest()
    {
        
        
return "Test";
    }


But i get a 404 on Https://xxxxx.de/Test
with following error 
Quote:Cannot access the default controller "\App\Controllers\Home::getTest"

What am i missing?
I don't wanna write every route in app/Config/Routes.php

Best regards.

Upgrading from version 4.4.6 to 4.5.2

$
0
0
I updated codeigniter from version 4..4.6 to the latest version (4.5.2) using composer update command but I was having errors with spark so I took spark and index.php files inside vendor folder and replaced my project files through them, and the error was resolved. Do I need to do anything else to update codeigniter?

Spark command not working in controller after upgrade to CI 4.5.2

$
0
0
Hi guys,

I've updated from CI 4.4.6 to 4.5.2. One of my previously working code was calling a spark command in the controller using command(). This no longer works and results in the redirection to my xammp root (i.e. localhost/dashboard).

There are no logs or error messages, so I cannot figure out what's going on. I'm using the legacy auto routing, so perhaps some changes in that area or how the filters work? I've read the change logs and upgrade instructions but nothing is obvious.

If I run the spark command via the command line, it works fine.

Here's a snippet of the controller in question:

PHP Code:
class Update extends BaseController
{        
      
    
public function index()
    {        
        $cmd_result 
command('app:update');                        
    
        
// we never reach here
        log_message('debug''hello');
    }    
 


To ensure that the command doesn't do anything that would cause it, I even removed all lines from the run command, but no change in behaviour.

PHP Code:
class Update extends BaseCommand
{
    protected $group      'App';
    protected $name        'app:update';
    protected $description 'Checks for any updates.';

    public function run(array $params)
    {
        // even with this empty, the same behaviour exists
    }


I would appreciate any ideas or debugging tips.

Integrating shield on existing login system?

$
0
0
I have a simplistic login using username and password. I have heard about shield. Can I utilize it to strengthen the authentication of my system but without using email as the username but some unique name? If yes then how should I proceed it with?
TIA
Viewing all 14343 articles
Browse latest View live


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