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

How do sites use other people sub domains to run their site through

$
0
0
Hi,

I had a service from a company where I set up a sub domain for my website, and their service ran on it. It was a social media writing service, where I charged people to use the service, and they used it on my website, but via a sub domain (something like SEO.mydomain.co.uk) and to all intents and purposes they thought it was my service.

php 8.2

$
0
0
how to make codeigniter 3 work with php 8.2

C4 version 4.4.1 posts me a route problem

$
0
0
hello devs

i come to you because C4 version 4.4.1 posts me a route problem, i explain:
CONFIG.
debian 12
php 8.3.11
ci4 version 4.4.1
apache 2.4

when launching the application the software executes a javascript script

<code>
//run email queue
$(document).ready(function () {
$.ajax({
type: 'POST',
url: MdsConfig.baseURL + '/Ajax/runEmailQueue',
data: setAjaxData({})
});
});
</code>
the url really exists OK

the routing is in static form

<code>
$postArray = [
//Ajax
'Ajax/runEmailQueue',
'Ajax/getBlogCategoriesByLang',
//Auth
'Auth/sendActivationEmailPost',
];

foreach ($postArray as $item) {
$array = explode('/', $item);
$routes->post($item, $array[0] . 'Controller::' . $array[1]);
</code>
the line url: MdsConfig.baseURL + '/Ajax/runEmailQueue', causes a 404 error

the other routing links also cause a 404 error example $routes->post('login-post', 'AuthController::loginPost');

what is the hardest, is that the application runs on a debian 12 workstation development machine and
on a debian 12 user workstation same problem on a debian 12 VPN server same crash

really thank you for those who can help me
Gabriel

Obtain database error message from model

$
0
0
Hello

I need to obtain the mysqli_sql_exception message from the database when using a model.

For example (doing a manual query):

PHP Code:
$db Database::connect();
$sql "SHOW TABLES from missing_database";
$query $db->query($sql);
$error $db->error(); 

This works fine and I can obtain the error code and message from the associative array.

However, I am unable to do this for models.

Example:

PHP Code:
$user = new User(['username' => 'user', 'email' => 'user@email.com', 'password' => 'password']);
$model = new UserModel();
$model->save($user); 

If the user already exists, this generates an error, as it should do:

Code:
mysqli_sql_exception: Duplicate entry 'user' for key 'username'

I need to capture error messages from the model like this:

PHP Code:
$error $model->db->error(); 

This does not retrieve the error, this is the array that is returned:

Code:
"code" => 0
"message" => ""

I suspect another query is being run by the framework immediately after the "INSERT INTO..." query fails, hence I am unable to obtain the error.

How do I obtain database error messages from the model?

Thanks

Strange logic of CI Model with useCasts and validate for json-array field

$
0
0
Hi everybody. I faced the following problem in CI 4.5.5. I use validation and casts on the CI Model side here is an example code:

PHP Code:
protected array $casts = [
        'id'            => 'int',
        'profile'      => '?json-array',
        'extra'        => '?json-array',
        'expires'      => 'int',
        'created_by_id' => 'int',
        'updated_by_id' => 'int',
        'roleId'        => 'int',
        'moduleId'      => 'int',
        'selfAuth'      => 'int',
    ];

protected 
$validationRules = [
        'profile.surname' => [
            'label' => 'surname',
            'rules' => 'required|max_length[255]',
        ],
        'profile.name' => [
            'label' => 'name',
            'rules' => 'required|max_length[255]',
        ],
        'profile.patronymic' => [
            'label' => 'patronymic',
            'rules' => 'permit_empty|max_length[255]',
        ],
        'phone' => [
            'label'  => 'phone',
            'rules'  => 'required|mob_phone|is_unique[users.phone]',
        ],
        'email' => [
            'label'  => 'Email',
            'rules'  => 'required|max_length[255]|valid_email|is_unique[users.email]',
        ],
        'password' => [
            'label' => 'Пароль',
            'rules' => 'required|verify_password',
        ],
        'password_conf' => [
            'label'  => 'password conf',
            'rules'  => 'required|matches[password]',
        ],
    ]; 

When I try to insert data, a validation error occurs: profile.surname and profile.name - are required fields to fill in. After examining the BaseModel source code, I see that the transformDataToArray method casts profile values into a string and after that data validation occurs and, accordingly, an error occurs. As for me, the logic of the sequence of processes is strange. I understand that the validation method expects an array, but why casts it before that and is it a Bug or did I not understand the logic?

Registrar: Merge Config arrays

$
0
0
The current behavior looks incorrect.
If I want to add Filters, supportedLocales, for example, then my settings will overwrite the default data. But it would be logical to combine them.

PHP Code:
// before, globals filters
array(2) {
  ["before"]=>
  array(3) {
    [0]=>
    string(8"honeypot"
    [1]=>
    string(4"csrf"
    [2]=>
    string(12"invalidchars"
  }
  ["after"]=>
  array(1) {
    [0]=>
    string(13"secureheaders"
  }
}

// after Registrar
array(2) {
  ["before"]=>
  array(1) {
    [0]=>
    string(23"some_filter"
  }
  ["after"]=>
  array(0) {
  }

// Expected
array(2) {
  ["before"]=>
  array(4) {
    [0]=>
    string(8"honeypot"
    [1]=>
    string(4"csrf"
    [2]=>
    string(12"invalidchars"
    [3]=>
    string(23"some_filter"
  }
  ["after"]=>
  array(1) {
    [0]=>
    string(13"secureheaders"
  }

Am I wrong? Of course, you can manually combine the previous values with the new ones, but it doesn't look. good. It will probably cause recursion.
Should I change it to array_merge_recursive()

Otherwise, you will have to duplicate all the values manually. This is bad for a modular system where each component changes arrays.

Unable to authenticate user when doing unit testing

$
0
0
I'm building an API with CodeIgniter v4.5.5.

I'm also using Shield and using the token based authentication.

I can successfully register and login a user through a POST request using a REST client.

However, I am unable to login the user in a unit test. Other POST requests (like registering a new user) work fine in unit tests.

This is the section of code which authenticates a user:

PHP Code:
// Attempt to login
$result auth()->attempt($validData);

// If login fails
if (!$result->isOK()) {
    throw new UnauthorizedException(['auth' => 'Unable to log you in. Please check your credentials.']);


Works fine with a REST client.

This is the output of dump($result) when attempting to POST to /login in my unit tests:

Code:
CodeIgniter\Shield\Result^ {#498
  #success: false
  #reason: "Every request must have a bearer token in the Authorization header."
  #extraInfo: null
}

So when attempting the POST request through the framework , Shield is refusing to authenticate due to a bearer token missing.

This endpoint (/login) is excluded from the tokens filter in the Filters.php configuration.

How do I workaround this with a POST request to /login?

Benchmark mark - converting from CI3 to CI4

$
0
0
Hello,
I'm converting a large project from CI3 to CI4.  I have the following lines that needs to be converted: 
Code:
$this->benchmark->mark('getProjectMethods_start');
//code in between
$this->benchmark->mark('getProjectMethods_end');

I don't see an equivalent function to 'mark' in the CI4 documentation on benchmarking https://codeigniter4.github.io/CodeIgnit...hmark.html
How would I do this in CI4? Do I just use start and end with the same name, something like: 
Code:
$benchmark = service('timer');
$benchmark->start('getProjectMethods');
//code in between
$benchmark->end('getProjectMethods');

Help with custom command

$
0
0
Hello. I have created a command to generate most of the template files associated with CRUD based on a specific controller name but I want store that command class inside a sub directory of ```app\Command``` so something like ```app\Command\TemplateGen``` or similar.

How can I do this?

PHP 8.4 + 8.4JIT, EOL, Releases and more !

CodeIgniter 4 Tasks, Execute task in controller ?

$
0
0
Hello,
I would like to know if it is possible to execute a cron task instantly from CI TASK (https://tasks.codeigniter.com/)?

PS: My tasks work perfectly with PHP Spark Task... or via CRON on my live server.

What I want to do:

I have a task in my Tasks.php file:

PHP Code:
$schedule->call(static function () {
    $tasksController = new TasksController();
    $tasksController->TaskCleanLogs();
})->
sundays('0:00')->named('CleanLogs'); 

But if I go into one of my controllers, for example, my Admin panel, in:

PHP Code:
public function index() {
// test
  echo command('tasks:run --task CleanLogs');



This works, but it does not execute the task; it just goes through the file, and here's what I have in var_dump/echo:

Running Task...
Completed Running Tasks

Without actually executing the task in question...
I do not see how to perform this action.

Thank you for your help.
Florian

Request for Enhanced Validation Rules: is_unique and is_not_unique

$
0
0
The is_unique and is_not_unique validation rules offer robust ways to ensure data integrity when checking for the uniqueness or existence of values within a specific table. 
However, there's a scenario where the current implementation can be further enhanced, particularly when dealing with multiple database groups (dbGroup) in a model with foreign keys from different databases.

Current Validation Rules
  1. is_not_unique
    The is_not_unique rule checks the database to see if a value exists in a specified table and field. It allows filtering based on one field and value.
    PHP Code:
    is_not_unique[table.field,where_field,where_value
    Example:
    PHP Code:
    'email' => 'is_not_unique[users.email,id,123]' 

  2. is_unique
    The is_unique rule checks if the field's value is unique within the database. It can optionally ignore a specific record by field and value, which is useful when updating records.
    PHP Code:
    is_unique[table.field,ignore_field,ignore_value
    Example:
    PHP Code:
    'username' => 'is_unique[users.username,id,5]' 

Proposed Enhancement: Supporting Multiple dbGroup

In many real-world applications, models can involve multiple foreign keys referencing tables in different database groups. To streamline the validation process, I propose introducing support for a database group (dbGroup) prefix within the is_unique and is_not_unique rules. This would allow developers to specify the database group directly in the validation rule, improving flexibility and reducing complexity in code that handles multiple databases.

Example: 

Consider a scenario where you have two foreign keys in a model, each pointing to different databases:
  • dbGroup1 contains a users table.
  • dbGroup2 contains a customers table.
Here’s how the validation rule might look for checking uniqueness within dbGroup1 and dbGroup2:


PHP Code:
'email' => 'is_unique[dbGroup1.users.email,id,123]',
'customer_code' => 'is_not_unique[dbGroup2.customers.code,id,456]' 

This implementation would ensure that the validation rule queries the correct database group, which is particularly useful when working with multiple data sources.


Priority of dbGroup
In this proposal, the priority of which dbGroup is used during validation would follow a clear order:
  • Highest Priority: If the dbGroup is specified in the validation rule itself, such as is_unique[dbGroup1.users.email,id,123], this database group takes precedence.
  • Next Priority: If the dbGroup is not specified in the rule, then the dbGroup parameter passed to the run() method during validation will be used: $this->validate($rules, null, 'dbGroup2');
  • Default: If neither the validation rule nor the run() method specifies a dbGroup, the default database connection will be used.
Conclusion:
The proposed enhancement to the is_unique and is_not_unique validation rules by allowing the optional inclusion of dbGroup would greatly simplify validation for models that span multiple database groups. This enhancement aligns well with CodeIgniter's existing feature of specifying dbGroup in the run() method for validation.

I believe this improvement would enhance the developer experience, reduce boilerplate code, and offer greater flexibility in managing complex database structures.
Feel free to share your thoughts and any feedback on this proposal.

Librarie File & SplFileInfo Namespace Error

$
0
0
Hi,
I am trying to read a CSV file with the Class 'File' but ran in some errors.
PHP Code:
$file "test.csv";
$objFileCsv = new \CodeIgniter\Files\File($file);
echo 
$objFileCsv->getMTime();
$splFileCsv $objFileCsv->openFile('r');
 
$splFileCsv->setFlags(SplFileObject::READ_CSV); 
This i tryed in a helper without namespace and there is no problem. But in a Controller there is a error.
Quote:Class "App\Controllers\SplFileObject" not found

I didn't get it. I know its because the Namespace but SplFileInfo is a PHP build in Class and the Scope should be global or?

I also try

PHP Code:
namespace App\Controllers;
use 
SplFileInfo

What i am missing?

how to keep session folder empty?

$
0
0
Hello

I created a little cms for myself and use it as a light application.  I try to put it in an 100 Mega hosting. My sources are 60 Mega so at the begining all went fine. Then I forget the website. Recently  I found a 

Whoops!

We seem to have hit a snag. Please try again later...

After a while I found the problem . The session folder had so many files that my hostiong was full. Then I deleted them manually it works but after a while I need to delete them again.

What is your suggestion ? I don't need session actually. How to keep this folder empty

Cant connect to db

$
0
0
I have this error:
Access denied for user '*****'@localhost (using password: YES)
But its a weird issue.

If I connect throught model the connection works with no problem. By example if I do
$orders = (new OrdersModel)->findAll();
works OK
but If I try
$db = \Config\Database::connect();
$query = $db->query("SELECT * FROM view_orders ORDER BY id DESC");
$orders = $query->getResult();

then I got this message:

ERROR - 2024-10-06 16:21:12 --> Access denied for user '****'@localhost (using password: YES)

CRITICAL - 2024-10-06 16:21:12 --> Call to a member function getResult() on bool
Any ideas?

Add variables in routes with view

$
0
0
Add the ability to pass simple variables in the route for views. Sometimes we derive a route from a template where we want to pass a title or fixed variable, but it's not possible.

An example of how this would be used:

PHP Code:
$routes->view('/''login', ['title' => 'Login''message' => 'Welcome to login']);

$routes->view('change-password''change-pass', ['title' => 'Change Password']); 

PHP PSR Logger Error

$
0
0
I ran composer update and now I am getting the following error:

My composer has "psr/log": "^3.0",

I tried sudo dnf remove php8.2-psr but it was not found. Tried 8.1 and 8.3 too, I am running PHP 8.3.12.

extension=psr.so isn't in my php.ini file.

What else can I try? I read all the previous threads I can find but have no luck. This worked fine before I ran composer update.

Codeigniter 4.4.4


Code:
AH01071: Got error 'PHP message: PHP Fatal error: Declaration of CodeIgniter\\Log\\Logger::emergency($message, array $context = []): bool must be compatible with Psr\\Log\\LoggerInterface::emergency(Stringable|string $message, array $context = []): void in /var/www/vhosts/domain.com/httpdocs/system/Log/Logger.php on line 159; PHP message: PHP Fatal error: Uncaught Error: Class "CodeIgniter\\Log\\Logger" not found in /var/www/vhosts/domain.com/httpdocs/system/Config/Services.php:401\nStack trace:\n#0 /var/www/vhosts/domain.com/httpdocs/system/Config/BaseService.php(258)

Why CI4 Shield do not store groups, permissions and rule on database

$
0
0
Hi,
I am still working with CI3 and a custom authentication library.
I tried CI4 and am excited about Shield for the same reason, but I noticed that it stores some things in a config file (AuthGroups.php).
Why doesn’t CI4 Shield store groups, permissions, and roles in the database?
Thanks

CLi issues

$
0
0
Routes:
$routes->cli('send-broadcast/ ( : segment)', 'BroadcastControl :: sendBroadcast/$1');

Trying to run the command:
php public/index.php send-broadcast "1"

get this error:
[TypeError]
Cannot assign CodeIgniter\HTTP\CLIRequest to property CodeIgniter\Security\Security::$request of type CodeIgniter\HTTP\IncomingRequest


May I know how to define the CLiRequest and how to I run the command using php code instead?

How do I update from 4.4.4 to 4.5.5?

$
0
0
I tried following the instructions here:
https://codeigniter.com/user_guide/insta...-upgrading
and added this to my root composer.json: "codeigniter4/framework": "4.5.5" (under require)
but I get the error: 
Root package 'codeigniter4/framework' cannot require itself in its composer.json 
Did you accidentally name your root package after an external package?

How do I upgrade correctly?
Viewing all 14343 articles
Browse latest View live


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