Welcome Guest, Not a member yet? Register   Sign In
  Open source devs are fighting AI crawlers with cleverness and vengeance
Posted by: InsiteFX - 03-28-2025, 12:58 PM - No Replies

Open source devs are fighting AI crawlers with cleverness and vengeance


  Support for 'perPage' Parameter in Pager Library
Posted by: campio97 - 03-28-2025, 07:38 AM - Replies (5)

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!


  Configure CORS for test API
Posted by: wolverine4277 - 03-27-2025, 11:46 AM - Replies (3)

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.


  Routing Issue: Optional ID and Named Routes in CodeIgniter 4
Posted by: Elias - 03-26-2025, 04:18 AM - Replies (4)

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!


Big Grin loading ci4 app on server
Posted by: xmax1991 - 03-26-2025, 03:30 AM - Replies (8)

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


  How does CodeIgniter load images from a CSS file?
Posted by: maplecave - 03-26-2025, 02:41 AM - Replies (1)

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!


  php parse error
Posted by: gilles - 03-24-2025, 06:25 AM - Replies (3)

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.


  Codeigniter alongisde Wordpress, both of them on subfolders
Posted by: starfire2k2 - 03-23-2025, 04:04 AM - No Replies

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?


  ErrorException: $strictLocaleNegotiation
Posted by: Vespa - 03-22-2025, 08:29 AM - Replies (4)

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


Lightbulb [DEPRECATED] Creation of dynamic property
Posted by: BlayMo - 03-22-2025, 04:15 AM - Replies (2)

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


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
The pipe operator in PHP ...
by InsiteFX
3 hours ago
Heads up for users using ...
by FlavioSuar
8 hours ago
Best Way to Implement Aff...
by InsiteFX
Today, 02:58 AM
Table (view class) Row ID
by grimpirate
Yesterday, 11:22 PM
curl + response body
by michalsn
Yesterday, 10:10 PM
Happy 4th Everyone
by InsiteFX
Yesterday, 09:31 PM
AbuseIPDB Module
by InsiteFX
Yesterday, 09:27 PM
tool bar not showing
by Luiz Marin
Yesterday, 04:46 AM
Tool bar not showing
by Luiz Marin
Yesterday, 04:28 AM
The Hidden Cost of “Innov...
by fcoder
07-02-2025, 03:11 AM

Forum Statistics
» Members: 154,766
» Latest member: bacarats
» Forum threads: 78,440
» Forum posts: 379,728

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB