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

9 Clever Tailwind Code Snippets for Faster Development


Sentry CodeIgniter4 SDK Integration

$
0
0
Hello everyone,
I am exploring the possibility of integrating Sentry with CodeIgniter 4. Has anyone already developed this integration? If not, would anyone be interested in collaborating on creating a dedicated Sentry-CodeIgniter4 SDK?
For error logging, the basic Sentry-PHP SDK is sufficient, but when it comes to performance monitoring and tracing, a more integrated solution is necessary. CodeIgniter 4 already gathers all the essential data for performance and traces through its debug toolbar, which uses collectors (see: https://codeigniter4.github.io/userguide...gging.html). We could potentially leverage these collectors, making the development of the SDK relatively straightforward.
What are your thoughts on this? Looking forward to your feedback and any potential collaboration!
Best regards,

PS: I opened a feature request on sentry-php sdk github too: https://github.com/getsentry/sentry-php/issues/1811

Installation & Setup on Windows IIS

$
0
0
First of all, if the topic should go in another subforum feel free to move it.
After a long time trying to run an application developed with CodeIgniter4 on a server with IIS and due to some difficulties I decided to write this kind of tutorial.
On Apache in a local environment the applications work immediately, but when making the move to IIS is not so easy (or at least that's what happened to me).
Everything I am going to describe is in addition to what is indicated in the Getting started guide.

We will need:
  • Enable the mod_rewrite extension
  • Import the .htaccess file of the project to generate a web.config file like this:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada" stopProcessing="true">
                        <match url="^(.*)$" ignoreCase="false" />
                        <action type="Rewrite" url="public/{R:1}" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Import the .htaccess file of the public folder to generate a web.config file like this:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada-1" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                            <add input="{URL}" pattern="(.+)/$" ignoreCase="false" />
                        </conditions>
                        <action type="Redirect" url="{C:1}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 2 importada" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{HTTPS}" pattern="^on$" ignoreCase="false" negate="true" />
                            <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                        </conditions>
                        <action type="Redirect" url="http://{C:1}{URL}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 3 importada" stopProcessing="true">
                        <match url="^([\s\S]*)$" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Create a virtual directory pointing to the public folder of the project (for example, if the project is located in c:\inetpub\wwwroot\myproject then we must add the virtual directory myproject pointing to c:\inetpub\wwwroot\myproject\public)
    To do this we select the folder above the project folder, right click on the folder and select the option Add virtual directory and configure an alias (myproject) and the physical path c:\inetpub\wwwroot\myproject\public.
  • Configure the HTTP verbs that we are going to use since not all are enabled by default (PUT is not enabled by default and when testing it threw me error 500, without recording in any error log the reason).
    To do this we select the project folder, double click on Handler mappings, double click on the PHP version we are using, then click on the Request Restrictions button
  • In the verbs tab we select the option All verbs or we select the option One of the following verbs and separate them with comma (for example: GET, PUT).

I hope it helps you, it would have saved me a lot of time to know all this when uploading my application to a Windows server.
Regards.


Luego de un buen tiempo intentando hacer funcionar un aplicación desarrollada con CodeIgniter4 sobre un servidor con IIS y debido a algunas dificultades que se me presentaron, me decidí a escribir esta especie de tutorial.
Sobre Apache en un entorno local las aplicaciones funcionan inmediatamente, pero al hacer el pase a IIS no es tan sencillo (o por lo menos es lo que me ha sucedido a mi).
Todo lo que voy a describir es adicional a lo indicado en la guía Como empezar.

Vamos a necesitar:
  • Habilitar la extensión mod_rewrite
  • Importar el archivo .htaccess del proyecto para generar un archivo web.config similar a este:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada" stopProcessing="true">
                        <match url="^(.*)$" ignoreCase="false" />
                        <action type="Rewrite" url="public/{R:1}" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Importar el archivo .htaccess de la carpeta public para generar un archivo web.config similar a este:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada-1" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                            <add input="{URL}" pattern="(.+)/$" ignoreCase="false" />
                        </conditions>
                        <action type="Redirect" url="{C:1}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 2 importada" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{HTTPS}" pattern="^on$" ignoreCase="false" negate="true" />
                            <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                        </conditions>
                        <action type="Redirect" url="http://{C:1}{URL}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 3 importada" stopProcessing="true">
                        <match url="^([\s\S]*)$" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Crear un directorio virtual apuntando a la carpeta public del proyecto (por ejemplo, si el proyecto se encuentra en c:\inetpub\wwwroot\myproject\ entonces debemos agregar el directorio virtual myproject apuntando a c:\inetpub\myproject\public).
    Para esto seleccionamos la carpeta superior a la del proyecto, hacemos clic con el botón derecho sobre la carpeta y seleccionamos la opción Agregar directorio virtual y configuramos un alias (myproject) y la ruta de acceso física c:\inetpub\wwwroot\myproject\public
  • Configurar los verbos HTTP que vamos a utilizar ya que no todos están habilitados por defecto (PUT no está habilitado por defecto y al hacer pruebas me arrojaba error 500, sin grabar en ningún log de errores el motivo).
    Para esto seleccionamos la carpeta del proyecto, hacemos doble clic en asignaciones del controlador, hacemos doble clic en la versión de PHP que estamos utilizando, luego clic en el botón Restricciones de solicitudes
  • En la pestaña verbos seleccionamos la opción Todos los verbos o seleccionamos la opción Uno de los siguientes verbos y los separamos con coma (por ejemplo: GET, PUT).

Espero les ayude, a mi me habría ahorrado un buen tiempo saber todo esto a la hora de subir mi aplicación a un servidor Windows.
Saludos.

Debug Toolbar -> show whole SQL query on error

$
0
0
Hey guys,
the toolbar is rather useless in its current state if a sql query error occurs. For example
-----------------------------------------------
CodeIgniter\Database\Exceptions\DatabaseException #1054
Unknown column 'a.status' in 'field list'
 ----------------------------------------------
One has to scroll down the call stack to manually find the code where the query was executed which is unnecessarily time consuming.
Instead, the last query should be printed on top to quickly identify the corresponding code.

Thanks!

Shield remove deleted at to user

$
0
0
i i try to remove deleted at symply by :

Code:
      $data_to_update = [

        'deleted_at' => NULL,
      ];

      $users_model->update($id, $data_to_update);

But i receive There is no data to update, i control $id it'ok

unit test class with phpunit

$
0
0
for my codeigniter 3 project i have creating a unit test class with phpunit:
i have following test controller :


PHP Code:
<?php
require_once("C:\\My_PC\\Birim Test\\...\\application\\core\\MY_UserController.php"); 
require_once 
'C:\\My_PC\\Birim Test\\...\\config.php';
require_once 
'C:\\My_PC\\Birim Test\\...\\application\\tests\\bootstrap.php';

if (!
defined('BASE_URL')) {
    define('BASE_URL''https://...com/'); 
}
use 
PHPUnit\Framework\TestCase;

class 
UserControllerTest extends TestCase {
    protected $CI;

    protected function setUp(): void {
        // Manually load CodeIgniter instance
        $this->CI = &get_instance();
        
        
// Load required models and libraries
        $this->CI->load->model('user_model');
        $this->CI->load->library('unit_test');

        // Load the controller manually
        require_once APPPATH 'controllers/Profil.php';
        $this->controller = new Profil();
    }

    public function testSaveCommentSuccess() {
        // Mock input data
        $_GET['issue'] = 'profil__comment';
        $_GET['report_id'] = 4901; 
        $_GET
['comment'] = 'This is a test comment';

        // Mock the model method
        $this->CI->user_model $this->createMock('User_model');
        $this->CI->user_model->method('update_comment')->willReturn(true);

        // Capture the output
        ob_start();
        $this->controller->save_comment();
        $output ob_get_clean();

        // Assert the output
        $this->assertJsonStringEqualsJsonString(json_encode(['success' => true]), $output);
    }

    public function testSaveCommentFailure() {
        // Mock input data
        $_GET['issue'] = 'profil__comment';
        $_GET['report_id'] = 4901; 
        $_GET
['comment'] = 'This is a test comment';

        // Mock the model method
        $this->CI->user_model $this->createMock('User_model');
        $this->CI->user_model->method('update_comment')->willReturn(false);

        // Capture the output
        ob_start();
        $this->controller->save_comment();
        $output ob_get_clean();

        // Assert the output
        $this->assertJsonStringEqualsJsonString(json_encode(['success' => false]), $output);
    }


in bootstrap then i have:

PHP Code:
define('APPPATH''C:\\My_PC\\Birim Test\\...\\application\\');
define('ENVIRONMENT''testing');

// Include your main configuration file
require_once 'C:\\My_PC\\Birim Test\\...\\config.php'// Adjust the path as needed
require_once 'C:\\My_PC\\Birim Test\\...\\system\\core\\CodeIgniter.php'; 

// Define BASE_URL if not already defined
if (!defined('BASE_URL')) {
    define('BASE_URL''https://....com/'); 


when i ran on local in terminal using:

PHP Code:
vendor/bin/phpunit --bootstrap application/tests/bootstrap.php application/tests/UserControllerTest.php 

i get :


PHP Code:
No direct script access allowed 

how can i resolve that? any help?

Dependency Management in Custom Services

$
0
0
Hello
If I create a custom service, is it considered good practice to load models and other libraries/services directly within the service itself?Or is it better to pass all these instances from the controller when calling the service?

For example, if I have a service that requires 6 models and 3 other services or libraries, should I pass them all through the constructor?
Thank you [Image: smile.png]

[DEPRECATED] Creation of dynamic property

$
0
0
I have added in SYSTEMPATH\Config\BaseConfig.php (Codeigniter 4.6.0):
PHP Code:
#[\AllowDynamicProperties]
class BaseConfig
This avoids the WARNING 
[DEPRECATEDCreation of dynamic property Config\Validation::$users
I think it is important to make this adjustment


ErrorException: $strictLocaleNegotiation

$
0
0
Hi, I got in trouble with my locally installed Codeigniter project.
I was developing my web site on my local PC, Windows 10 as OS...so I had installed PHP 8.3, Codeigniter using Composer and MySQL
Now I have updated PHP to 8.4.5 version...updated Composer...and when I run the command
Code:
php spark serve
I get he following error
Code:
D:\_GAVS_nuovo_sito\composer-gavs>php spark serve
PHP Fatal error:  Uncaught ErrorException: Undefined property: Config\Feature::$strictLocaleNegotiation in D:\_GAVS_nuovo_sito\composer-gavs\vendor\codeigniter4\framework\system\HTTP\Negotiate.php:131
Any hint to fix the issue? Thanks a lot for any feedback

Routing Issue: Optional ID and Named Routes in CodeIgniter 4

$
0
0
Hi everyone,

I’ve encountered an issue with routing and I’m not sure whether it’s a bug or expected behavior not clearly explained in the documentation.
I like to handle form processing in the same method that renders the form’s HTML. Additionally, I prefer using optional IDs in these methods:
  • When there’s no ID, it handles entity creation.
  • When there is an ID, it handles entity editing.
I’ve seen this approach in various projects and find it quite intuitive.

Now, I want to create a method for editing a post with an optional ID. From what I understand, the only way to achieve this is by defining two routes:
PHP Code:
$routes->match(['GET''POST'], 'edit''PostController::edit');
$routes->match(['GET''POST'], 'edit/(:num)''PostController::edit/$1'); 

However, if I want to assign a name to one of these routes, I can only name the route without the ID:
PHP Code:
$routes->match(['GET''POST'], 'edit''PostController::edit', ['as' => 'edit']);
$routes->match(['GET''POST'], 'edit/(:num)''PostController::edit/$1'); 

If I try to name the route with the ID instead, navigating to it returns a 404 error:
PHP Code:
$routes->match(['GET''POST'], 'edit''PostController::edit');
$routes->match(['GET''POST'], 'edit/(:num)''PostController::edit/$1', ['as' => 'edit']); 

For example, navigating to /edit/12 results in a 404.

Is this behavior intentional? Or am I missing something in the way named routes and optional parameters are meant to work in CodeIgniter 4? Any guidance would be appreciated.
Thanks in advance!

Question on include() in a module [newbie!!]

$
0
0
Hi guys
I am just starting my Ci journey, and am following a tutorial from Udemy. Basic app is allow users to register and then create a blog article.
As extra "homework" I am adding functionality to edit a users name and email address. I have everything working but am hitting an issue with an include file and am after some guidance - I am sure I am missing something obvious here..
So, I have an Admin module, laid out thus:
Code:
Admin
-> Config
-> Database
-> Helpers
-> View
->->Users
->->->Edit.php
->->->form.php
->->->index.php
->->->show.php
app
->Config
etc...
The issue is is with the Edit, the code for which is:
Code:
<?= $this->extend('Layouts\default') ?>

<?= $this->section("title") ?>Edit User<?= $this->endSection() ?>

<?= $this->section("content") ?>

  <h1>Edit User</h1>

  <?php if (session()->has("errors")): ?>

      <ul>
        <?php foreach(session("errors") as $error): ?>
          <li><?= $error ?></li>
        <?php endforeach; ?> 
      </ul>
  <?php endif; ?>

  <?= form_open("admin/users/" . $user->id) ?>
 
    <input type="hidden" name="_method" value="PATCH">

    <?= $this->include("Admin\Views\Users\\form") ?>
    <!-- <label for="title">Email:</label>
    <input type="text" id="email" name="email" value="<?= old("title", esc($user->email)) ?>">
    <label for="content">First Name:</label>
    <input type="text" id="first_name" name="first_name" value="<?= old("title", esc($user->first_name)) ?>"> -->

    <button>Save</button>

  </form>

<?= $this->endSection() ?>
The issue is the line:

Code:
<?= $this->include("Admin\Views\Users\\form") ?>
As you can see, I have had to escape the name of the file in order to get it to be picked up - but this doesn't feel right to me.
I have played with adding APPPATH and ROOTPATH to the include path, but these don't work either.
The error I get "Invalid file" and I have tried various combinations of the Admin\Views\Users, with backslashes, forward slashes - all with the same error.
The code in the form.php file is in the code above, just commented out. If I uncomment it and comment out the include call, it all works.

Please help a newbie!

Thanks
Darren

Codeigniter alongisde Wordpress, both of them on subfolders

$
0
0
Hello,
I am trying to install CI4 alongside WordPress, each of them in an own subfolder.
WordPress should be accessible directly via the main domain (www.example.com)
CodeIgniter should be accessible via www.example.com/codeigniter.
For the future, I would like to have multiple instances of CodeIgniter each on its own folder.
The structure of CodeIgniter has not been changed
My current folder structure looks like this:

Code:
/httpdocs/
│── /wordpress/    (WordPress subdirectory)
│── /codeigniter/  (CodeIgniter subdirectory)
│── index.php   (redirects to /wordpress/index.php)
│── .htaccess

The .htaccess under httpdocs (created by ChatGPT) looks like this:
Code:
RewriteEngine On

# Exception for CodeIgniter so that it is not overwritten by WordPress
RewriteCond %{REQUEST_URI} ^/codeigniter/ [NC]
RewriteRule .* - [L]

# Redirect all requests to WordPress (unless it is a real file/directory)
RewriteCond %{REQUEST_URI} !^/wordpress/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /wordpress/$1 [L]

# WordPress default rules (customised for subfolders)
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]

.htaccess under www.example.com/codeigniter:
Code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

<FilesMatch "^\.">
    Require all denied
    Satisfy All
</FilesMatch>


.htaccess under www.example.com/codeigniter/public:
Code:
# Disable directory browsing
Options -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 /codeigniter/

# Redirect Trailing Slashes...
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteCond %{REQUEST_URI} (.+)/$
#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 ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

# 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

BTW: the base_url has been set to 'http://www.example.com/codeigniter/'
The problem I am facing is that CodeIgniter uses relative links (e.g.  <a href="/about">) that now point to www.example.com/about instead of www.example.com/codeigniter/about
The only solution I have found for me is to use base_url() on each link and form actions.

Is there any other solution to this?

php parse error

$
0
0
Hi !
I have this error
Parse error: syntax error, unexpected token ")" in /home/mywork/vendor/codeigniter4/framework/system/Autoloader/Autoloader.php on line 165
because of the line
spl_autoload_register($this->loadClassmap(...), true);
I am running codeigniter 4.6.0 on php8.0.
I spent hours on this error and now I ask some help because I really have no idea how to fix it !!!
Someone a solution ?
Thanks in advance.

How does CodeIgniter load images from a CSS file?

$
0
0
I'm having trouble loading images in coedigniter. I was able to load css using base_url(), but not images. Images are called in a css file (style.css), therefore, to load style.css, I updated the HTML as follows:

Code:
<link href="<?php echo base_url('css/style.css'); ?>" rel="stylesheet" type="text/css" media="screen" />

Okay, all styles and css are loading, but the images used in the styl.css preview of css are not loading:

Code:
html, body { height: 100%; }
* {
    margin: 0;
    padding: 0;
}
body {
    background: url(images/img04.jpg) repeat left top;
}

So any idea or advice would be greatly appreciated. Thank you!

loading ci4 app on server

$
0
0
Goodmorning,
i'm loading ci4 4.6 version app from local to server online. i ve seen some post online but no one helped me. Every time i enter the url of the domain i don't see the the relative page. 
i have var -> www -> html folders.
Thank you

Configure CORS for test API

$
0
0
Hi, a few days ago I finished an API and after testing it a little bit I published it for a coworker to test it from his terminal.
The issue is that having the API on a server and the html/javascript that consumes the API appeared the problem with CORS.
If I don't use authorization (Bearer {token}) everything works fine, when I add a filter for JWT it stops working.
From this I started to do the configurations indicated in https://codeigniter.com/user_guide/libraries/cors.html whitout success!

<Cors.php>
PHP Code:
public array $api = [
    'allowedOrigins'         => ['http://localhost'],
    'allowedOriginsPatterns' => [],
    'supportsCredentials'    => false,
    'allowedHeaders'         => ['Authorization''Content-Type'],
    'exposedHeaders'         => [],
    'allowedMethods'         => ['GET''POST''PATCH''PUT''DELETE'],
    'maxAge'                 => 7200,
]; 

<Routes.php>
PHP Code:
$routes->group('', ['filter' => ['cors:api']], static function (RouteCollection $routes): void {
    $routes->resource('client', ['controller' => 'ClientController']);
    $routes->options('client', static function () {}); 
    $routes->options('client/(:any)', static function () {});
}); 
PHP Code:
CodeIgniter v4.6.0 Command Line Tool Server Time2025-03-27 18:20:17 UTC+00:00

+---------+------------------+------+----------------------------------------------+------------------+---------------+
Method  Route            Name Handler                                      Before Filters   After Filters |
+---------+------------------+------+----------------------------------------------+------------------+---------------+
GET     client           »    | \App\Controllers\ClientController::index     authjwt cors:api cors:api      |
GET     client/new       »    | \App\Controllers\ClientController::new       authjwt cors:api cors:api      |
GET     client/(.*)/edit »    | \App\Controllers\ClientController::edit/$1   authjwt cors:api cors:api      |
GET     client/(.*)      »    | \App\Controllers\ClientController::show/$1   authjwt cors:api cors:api      |
POST    client           »    | \App\Controllers\ClientController::create    authjwt cors:api cors:api      |
PATCH   client/(.*)      »    | \App\Controllers\ClientController::update/$authjwt cors:api cors:api      |
PUT     client/(.*)      »    | \App\Controllers\ClientController::update/$authjwt cors:api cors:api      |
DELETE  client/(.*)      »    | \App\Controllers\ClientController::delete/$authjwt cors:api cors:api      |
OPTIONS client           »    | (Closure)                                    authjwt cors:api cors:api      |
OPTIONS client/(.*)      »    | (Closure)                                    authjwt cors:api cors:api      |
+---------+------------------+------+----------------------------------------------+------------------+---------------+ 
Required Before Filters: forcehttps,pagecache
Required After Filters: pagecache, performance, toolbar

Also try something like this:

PHP Code:
$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
    $routes->resource('client');

    $routes->options('client', static function () {
        // Implement processing for normal non-preflight OPTIONS requests,
        // if necessary.
        $response response();
        $response->setStatusCode(204);
        $response->setHeader('Allow:''OPTIONS, GET, POST, PUT, PATCH, DELETE');

        return $response;
    });
    $routes->options('client/(:any)', static function () {});
}); 
without luck!
If I comment the line 'authjwt' => ['except' => ['/']], in Filters.php all works fine:


<Filters.php>
PHP Code:
public array $globals = [
    ...
    'authjwt' => ['except' => ['/']], 
    ... 
The code of JWT filter is like this:

<AuthJwtFilter.php>
PHP Code:
namespace App\Filters;

use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;

class 
AuthJWTFilter implements FilterInterface
{
    public function before(RequestInterface $request$arguments null)
    {
        // Get the Authorization header
        $authHeader $request->getHeader('Authorization');
        if (!$authHeader) {
            return $this->unauthorizedResponse();
        }

        // Extract the token from the header
        $token str_replace('Bearer '''$authHeader->getValue());

        // Validate the token (you can implement your own validation logic here)
        if (!$this->isValidToken($token)) {
            return $this->unauthorizedResponse();
        }
    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        // Do something after the request is processed
    }

    private function isValidToken($token)
    {
        // Implement your token validation logic here
        // For example, check against a database or decode a JWT

        return $token === env('auth.JWT'); // Testing code, not the real one
    }

    private function unauthorizedResponse()
    {
        return service('response')
            ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED)
            ->setJSON(['error' => 'Authentication is required.']);
    }




The code on client es like this:

PHP Code:
    const token 'token'
    fetch('http://mydomain.com/myproject/client', {
        method'GET',
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type''application/json'
       }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' response.statusText);
        }
        return response.json();
    })
    .then(data => {
        const dataDiv document.getElementById('data');
        dataDiv.innerHTML = `<p>${JSON.stringify(data)}</p>`;
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:'error);
    }); 
Image with error



I'm probably getting something wrong but I don't realize it.
Can someone help me?
Regards.

Support for 'perPage' Parameter in Pager Library

$
0
0
Hello,

I've been working with the Pager library in CodeIgniter 4 and noticed that while it automatically handles the `page` parameter from the URL query string, it doesn't provide similar functionality for the number of items per page.

Current Behavior

Currently, the Pager class automatically reads the `page` parameter from the URL (e.g., `?page=5`), but the number of items per page (`perPage`) must be manually specified in the code:

PHP Code:
// Controller method
public function index()
{
    $model = new MyModel();
    $data = [
        'items' => $model->paginate(20), // perPage hardcoded as 20
        'pager' => $model->pager
    
];
    return view('my_view'$data);



Proposed Enhancement

I'd like to propose adding support for a `perPage` parameter in the URL query string, similar to how the `page` parameter works. This would allow clients to specify how many items they want per page directly in the URL:

Code:
/users?page=5&perPage=50


The Pager library would automatically detect this parameter and use it instead of the default value or the one specified in the code.

Benefits

1. Improved API Development: This would make the Pager more suitable for RESTful API development, where clients often need to control the pagination parameters.
2. Consistent Interface: It would provide a consistent interface for both page number and page size parameters.
3. Reduced Boilerplate: Developers wouldn't need to manually check for and apply the `perPage` parameter in every controller method.
4. Better User Experience: Frontend applications could allow users to choose how many items they want to see per page.

Implementation Suggestion

The implementation could be similar to how the `page` parameter is handled in the `calculateCurrentPage()` method, with appropriate safety checks to ensure the value is within acceptable limits:

PHP Code:
// Inside the Pager class
protected function calculatePerPage(string $group)
{
    $perPageSelector 'perPage'// or configurable
   
    
if (isset($_GET[$perPageSelector])) {
        $perPage = (int) $_GET[$perPageSelector];
        $minPerPage 1;
        $maxPerPage $this->config->maxPerPage ?? 100;
       
        $this
->groups[$group]['perPage'] = max($minPerPagemin($perPage$maxPerPage));
    }



This would respect the existing API while adding the new functionality in a backward-compatible way.

Has anyone else found this limitation? Would this feature be valuable to the community?

Thank you for considering this enhancement!

Open source devs are fighting AI crawlers with cleverness and vengeance

SMTP server problem

$
0
0
HI , i have a bad server..
 When i try to send multiple mail (this is only for testing, i must send 3 different email simoultanously ) : 

Code:
    public function test_invio_3_mail()
    {
        $email_to = 'xxxxxx@gmail.com';
        $oggetto_mail = 'Test Email';
        $message = '<p>This is a test email sent to multiple recipients.</p>';

        $result = $this->invia_mail_tratta($email_to, $oggetto_mail, $message);

        if ($result === 'inviata') {
            echo 'Emails sent successfully to ' . $email_to;
        } else {
            echo 'Failed to send emails: ' . $result;
        }


        $email_to = 'xxxxxx+cliente2@gmail.com';
        $oggetto_mail = 'Test Email';
        $message = '<p>This is a test email sent to multiple recipients.</p>';

        $result = $this->invia_mail_tratta($email_to, $oggetto_mail, $message);

        if ($result === 'inviata') {
            echo 'Emails sent successfully to ' . $email_to;
        } else {
            echo 'Failed to send emails: ' . $result;
        }



        $email_to = 'xxxxxxxx@yahoo.it';
        $oggetto_mail = 'Test Email';
        $message = '<p>This is a test email sent to multiple recipients.</p>';

        $result = $this->invia_mail_tratta($email_to, $oggetto_mail, $message);

        if ($result === 'inviata') {
            echo 'Emails sent successfully to ' . $email_to;
        } else {
            echo 'Failed to send emails: ' . $result;
        }
    }

this is invia_mail_tratta
Code:
    private function invia_mail_tratta($email_to,$oggetto_mail,$message){


        $email = \Config\Services::email();


        //$dati_azienda_model = new Dati_aziendaModel();

        //$dati_azienda = $dati_azienda_model->find(1);

        $email->setMailType('html');
        $email->setFrom('info@xxxxxxx.com');
        $email->setTo($email_to);
        //$email->cc('another@another-example.com');
        //$email->bcc('them@their-example.com');

        $email->setSubject($oggetto_mail);



        $email->setMessage($message);

        if ($email->send(true)) {
           
            $email->clear(true);

            return 'inviata';
         
        }else{


            return $email->printDebugger();
        }

    }
this is the error :
Code:
Failed to send emails: 220 hpt01.web.l1.armada.it ESMTP Postfix
hello: 250-hpt01.web.l1.armada.it
250-PIPELINING
250-SIZE 52428800
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250 CHUNKING
from: 250 2.1.0 Ok
to: 250 2.1.5 Ok
data: 354 End data with .

quit: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered:
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Date: Sat, 29 Mar 2025 12:14:13 +0100
From: <info@xxx.com>
Return-Path: <info@xxx.com>
To: xxxx@gmail.com
Subject: =?UTF-8?Q?Test=20Email?=
Reply-To: <info@xxxx.com>
User-Agent: CodeIgniter
X-Sender: info@xxx.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <67e7d6052e96a5.48094254@xxx.com>
Mime-Version: 1.0


Content-Type: multipart/alternative; boundary="B_ALT_67e7d6052e97f9.15655388"

This is a multi-part message in MIME format.
Your email application may not support this format.

--B_ALT_67e7d6052e97f9.15655388
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is a test email sent to multiple recipients.


--B_ALT_67e7d6052e97f9.15655388
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<p>This is a test email sent to multiple recipients.</p>

--B_ALT_67e7d6052e97f9.15655388--
Failed to send emails: 220 hpt01.web.l1.armada.it ESMTP Postfix
hello: 250-hpt01.web.l1.armada.it
250-PIPELINING
250-SIZE 52428800
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250 CHUNKING
from: 250 2.1.0 Ok
to: 250 2.1.5 Ok
data: 354 End data with .

quit: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered:
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Failed to send AUTH LOGIN command. Error: 221 2.0.0 Bye
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Date: Sat, 29 Mar 2025 12:14:13 +0100
From: <info@xxx.com>
Return-Path: <info@xxx.com>
To: xxx+cliente2@gmail.com
Subject: =?UTF-8?Q?Test=20Email?=
Reply-To: <info@xxx.com>
User-Agent: CodeIgniter
X-Sender: info@xxx.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <67e7d60ed09d76.50708510@xxx.com>
Mime-Version: 1.0


Content-Type: multipart/alternative; boundary="B_ALT_67e7d60ed09ef8.63370120"

This is a multi-part message in MIME format.
Your email application may not support this format.

--B_ALT_67e7d60ed09ef8.63370120
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is a test email sent to multiple recipients.


--B_ALT_67e7d60ed09ef8.63370120
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<p>This is a test email sent to multiple recipients.</p>

--B_ALT_67e7d60ed09ef8.63370120--
Failed to send emails: 220 hpt01.web.l1.armada.it ESMTP Postfix
hello: 250-hpt01.web.l1.armada.it
250-PIPELINING
250-SIZE 52428800
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250 CHUNKING
from: 250 2.1.0 Ok
to: 250 2.1.5 Ok
data: 354 End data with .

quit: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered: 250 2.0.0 Ok: queued as 3F5BDCC695
The following SMTP error was encountered:
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Failed to send AUTH LOGIN command. Error: 221 2.0.0 Bye
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Unable to send email using SMTP. Your server might not be configured to send mail using this method.
Date: Sat, 29 Mar 2025 12:14:13 +0100
From: <info@falconservicegroup.com>
Return-Path: <info@xxx.com>
To: xxxx@yahoo.it
Subject: =?UTF-8?Q?Test=20Email?=
Reply-To: <info@xxx.com>
User-Agent: CodeIgniter
X-Sender: info@xxx.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <67e7d60ed0b938.07593514@xxx.com>
Mime-Version: 1.0


Content-Type: multipart/alternative; boundary="B_ALT_67e7d60ed0ba07.08117340"

This is a multi-part message in MIME format.
Your email application may not support this format.

--B_ALT_67e7d60ed0ba07.08117340
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is a test email sent to multiple recipients.


--B_ALT_67e7d60ed0ba07.08117340
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<p>This is a test email sent to multiple recipients.</p>

--B_ALT_67e7d60ed0ba07.08117340--


It send only first email

Class App\Controllers\stdClass not found error

$
0
0
I have a controller with the following code, working fine till CI 4.5 version.
Code:
34     public function index(): string
35     {
36        $model = new RegisterModel();
37        $total = new stdClass;
38        $total->registrations = $model->countRegistrations();
39        $total->pictures = $model->countPictures();
40        $this->viewData['total'] = $total;
41        return view('pages/public/registers/civil/main', $this->viewData);
42    }
After the latest update I get the error: Class "App\Controllers\stdClass" not found
What's wrong with the code above? Thanks a lot for any hint
Viewing all 14343 articles
Browse latest View live


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