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

Custom Validation Messages not shown

$
0
0
Hello everyone,

I'm trying to validate a form with a custom error message.

The message displayed is always the default, in English. Here is my code:

PHP Code:
        $validation = \Config\Services::validation();

        $validation->setRules([
 
'sonde_nom' => [
                'label' => 'Nom',
                'rules' => 'required|min_length[3]',
                'errors' => [
                    'required' => 'Le champ {field} est obligatoire.',
                    'min_length' => 'Le champ {field} doit contenir au moins {param} caractères.',
                ],
            ],
 
 ]);
        if (!$this->validate($validation->getRules())) {
            return redirect()->back()->withInput()->with('errors'$validation->getErrors());
        }
 
print_r($validation->getRules());die(); 

For testing I print the getRules():
PHP Code:
Array ( [sonde_nom] => Array ( [label] => Nom [rules] => Array ( [0] => required [1] => min_length[3] ) ) ) 

What did I miss? Thank you in advance for your help Smile

pagination adding params

$
0
0
With codeigneter 4, can someone guide me to how to add additional parameters to links?

Is it fine to have multiple rows in auth_identities table in SHIELD CI4?

$
0
0
Hi

I have used SHIELD Auth for first time in CI4, and I created APIs to register or login the users.
It's working fine.

But I checked the "auth_identities" table and I got multiple rows for one user. I just want to know is it fine have multiple rows in auth_identities table for one user or is it any issue. Please check screenshot.

https://prnt.sc/k1G9W0bFgS7S


This is creating issue while fetching users list, I am getting multiple records for one user. I have joined users table with auth_identities table to get the user email.
https://prnt.sc/QgEfitRqlmfR


If it's any issue, please help me how can fir this?
Thanks

CodeIgniter 4 route is not updated on the server

$
0
0
Hi,
I am using CodeIgniter 4 framework for one of my project. I recently added few parameters in one of the line of the route.php file, and it works well in my local. But the problem is when I test the same thing on the server, server sending me an error message 404 (as this route is not exist anymore, which is totally understandable as that particular line is not exist), I am not sure why server still send the request on the older route rather than updated one.
I also try to clear cache of the server via this code : php spark cache:clear

but still the issue persist. 
It would be greatly appreciated if anyone could help me to figuring out this problem.

Fatal Error. Uncaught error: Class 'CI_Controller' not found

$
0
0
So this is a kinda old project running CI3 and we're facing this issue. It's very sporadic, it seems like it happens when requesting Ajax routes and the temporary fix testers have found is to "Clear the browser's cache".
From what I can see, people that faced this exact error and reported on StackOverflow have so many different causes too far and between, so I couldn't pinpoint the exact issue.
Of course we don't touch core files, just extend from them in our own controllers, and the fact that it happens at random doesn't help to the issue.

This is a screenshot of what we see in one of the Ajax responses:

[Image: 552b72ef-b77f-4917-8c76-2272b6c7a095]
This stack trace points to this file called MY_Exceptions.php which has this code, reading another issue report here I kinda thought it was because at this point in the lifecycle CI_Controller wasn't loaded, but this is an Ajax call though, wouldn't the Core components be up even before my code is executed at that point?:

[Image: 08e528c6-2986-4f25-97d6-5f65f96acd50]

Again, let me emphasize that this doesn't happen all the time with all the existing Ajax requests, nor consistently through all the user machines and browsers, it just happens, a browse cache clear and it's working as intended again.

What you read previously is the original post on Stack Overflow and Github repo, but I did some further testing:
I tried something, which was removing the file MY_Exception, thinking it wasn't being really used/referenced anywhere and it was just being loaded as a result of a line batch loading the files of a folder in codeigniter, also, that it seemed to be made by one of the previous developers of this project.
Turns out it's absolutely needed, any Exception thrown in the project goes through this file, so everything was breaking in it's absence.
Now, that got me thinking, this CI error is happening on the development environment after any exception is thrown out? maybe? that would've been worrysome because that would compromise the entire try - catch structure we have in the code, fortunatelly it wasn't the case, I forced a condition to throw an Exception and it worked just fine.
But that puts us to the beginning, the only thing we know is that this is a random thing we can't catch just yet, I'll even say more, our tester said last week he got the CI error in another random place, but a couple hours later when I told him to check something for me, he went to test it again and it wasn't happening anymore, he didn't even need to clear cache.
Can you people help me try to find the cause of this issue? thanks in advance

shared hosting public folder get route

$
0
0
I just wanted to post this for anyone that struggled with getting their site working on shared hosting.  So I installed codeigniter using shared hosting plan from Hostinger.  I transfered all the controllers, models, views, app config and the main page was working fine.  As soon as I had a get request it wouldn't work.  I would get 404 Can't find a route for 'GET: .  The url would change to example.com/pubic/getname.  The public was added and I thought it was an issue with .htaccess in the main CI folder.  So I searched forever trying to find the solution why this was happening.  The thing is post routes worked fine, it was only a problem with get routes.  Come to find out it was an issue with the .htaccess file in the /CI/public folder.  
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]


The Redirect Trailing Slashes was causing this problem. I commented out the three lines in this group and it is working perfectly on the live shared hosting server.  Thought I would put this on the forum for those who struggled with this problem.  It took me a long time and tried different hosting providers before I finally got my site to work.  
Just curious why are these written by default?  Will this cause an issue with something else now that I have them commented out?
Thanks

Problem with Query Builder Not Returning Results for a LIKE Query

$
0
0
Hi everyone,

I've recently started working with CodeIgniter 4, and I'm encountering an issue with the Query Builder when using the LIKE clause. I'm trying to filter records from my database based on a search term, but it seems like the query isn't returning any results, even though I know matching records exist.

Here's a simplified version of my code:

Code:
$searchTerm = 'example';
$builder = $db->table('my_table');
$query = $builder->like('column_name', $searchTerm)->get();
$results = $query->getResult();

if (empty($results)) {
    echo "No records found";
} else {
    foreach ($results as $row) {
        echo $row->column_name;
    }
}

I've checked my database, and there are definitely rows where column_name contains the word 'example'. I've tried tweaking the query, but no luck so far. Could it be something related to how CodeIgniter 4 handles the like clause or perhaps an issue with the character encoding?

Any insights or suggestions on what I might be doing wrong would be greatly appreciated.
Thanks and Regards,
Elena

Creating a personal brand: How to sell yourself as a developer


Logout message using shield

$
0
0
I've tried the following approaches in order to send a logout message to the login view while using CI4 Shield:
PHP Code:
auth()->logout();
session()->setFlashdata('message''This is a message!');
return 
redirect()->to('login'); 

Also:
PHP Code:
auth()->logout();
return 
redirect()->to('login')->with('message''This is a message'); 

But both didn't work. What is the standard procedure to do a logout while passing a logout message other than 'successLogout'?

Session trouble

$
0
0
I am on Windows 11 with a CI3 website. The online site is throwing an error like this:

Message: session_start(): Failed to read session data: user (path: /var/cpanel/php/sessions/ea-php83)

This is because I was trying to clear out redundant session files and I inadvertently (some would say stupidly!) deleted the ea-php83 file with all the others. I've had a look at the php.ini file and the session path, sure enough, is this. The question is, how do I fix it? Will it go away after some time when new session files are created or do I have to do something? So far it is still throwing the error after a day. I have been in touch with the service providers who tell me this can only be fixed by my code although I don't know how. The site is, unsurprisigly, perfectly OK on my local server.

Grateful for advice.

GET query doesn't work

$
0
0
I'm trying to use GET parameters in an URL (for example myserver.com/acontroler/?alias=q) but it doesn't work.

First it raised a BadRequestException #400 because it has disallowed characters, but adding "?&=" to $permittedURIChars returns a "404-Page not found" error.
What I'm doing wrong?  Shouldn't CI parse GET parameters by itself?

Open for Work - Full Stack Developer

$
0
0
Hello
I am currently seeking a new project.
The type of project I am interested in:
  • Contract / Freelance work
  • Rate: $25/hr
  • Fully Remote
  • Position: Full-Stack Developer
I have over 8 years of experience as a PHP developer and have been woking in the field since I graduated from my bachelor's degree. As a developer, I have worked on both small and large projects.

I am able to work independently as well as collaboatively with others on teams.
email: fashion.david94@gmail.com

Codeigniter 4 Query Builder Getting all match records from second table

$
0
0
I want to improve my sql query, can you please check and let me know how i can do this within one query? right know i am using two different function but i want to do this with one query.
I am getting conversation details included verifying is user blocked or not or part of this conversation or not and also getting list of all participants of conversation. right now with two different query and functions its working fine and giving me result which i need. but i want to do this with one function with one query.
FIRST FUNCTION/ QUERY:
PHP Code:
function get_user_chat_info($chat_id$user_id){

    $builder $this->db->table('chats cht')
  ->select('cht.chat_id, cht.room_id, cht.user_id, cht.recipient_id, cht.admin_id, cht.started_at, cht.total_participants, cht.total_messages, cht.last_message_at, COUNT(eu.participant_id) as joined, COUNT(blk.block_id) as blocked')
  ->join('chat_participants eu''eu.room_id=cht.room_id AND eu.user_id='.$user_id'LEFT')
  ->join('blocks blk''blk.chat_id=cht.chat_id AND blk.user_id='.$user_id'LEFT')
  ->having('joined > 0 OR COUNT(CASE WHEN cht.user_id = '.$user_id.' OR cht.recipient_id = '.$user_id.' THEN 1 END) >= 1')
  ->where('cht.chat_id'$chat_id)
  ->groupBy('cht.chat_id');
  $query $builder->get();
  $db_data $query->getRowArray();
  if($db_data){    
    $select_participant 
'participant_id, room_id, chat_id, user_id, participant_at';
      $where_participant = array('chat_id' => $chat_id);  
      $db_data
['participants'] = $this->get_all_chat_participants($where_participant$select_participant);
  }
  return $db_data;

  


SECOND FUNCTION/QUERY:
PHP Code:
function get_all_chat_participants($where$select=''){

    $builder $this->db->table('chat_participants');
    if($select){
    $builder->select($select);
    }
    $query $builder->where($where)
                    ->get();
    $db_data $query->getResultArray();
    return $db_data;

  


RESULT:
[Image: Screenshot-2024-08-08-at-01-56-22.png]

I want same result with one query without using get_all_chat_participants function and same query use in first function.

Rate Limit when they throw exception?

$
0
0
Hi!
I have an annoying spammer who will occasionally trigger lots of error logs for bad CSRF tokens.
Basically they keep throwing the throw SecurityException::forDisallowedAction(); action from system/Security/Security.php

Is there a way to trigger a rate limit so that for every time this error occurs, they will eventually get blocked from using the site? This person did it like 500+ times over the course of an hour so it wouldn't catch many innocent users.

Would You Like an Automated Prompt to Install Additional Packages After CI4 Setup?

$
0
0
Hi everyone,

When setting up our projects with the framework, we typically start by installing the framework itself using the composer install command. After that, we move on to additional packages, such as the Shield authentication package and the Translation package, which we install individually using the composer require command.

My question is:
Would you prefer to have a prompt immediately after the framework installation asking if you'd like to install any of these packages (e.g., Shield and Translation)? This would allow you to select the packages you want, and the installation would proceed automatically in the command line.

Deploying a CodeIgniter 4 Application with React Frontend and MySQL Database

$
0
0
I've created a web application using CodeIgniter 4 as the backend, React as the frontend, and MySQL as the database. The application is working fine locally, but I'm unsure how to properly deploy it to a production server.

Where should I place the React app within the CodeIgniter 4 project structure? I've currently put it in the public folder, but is that the best approach?

Newbie Seeking JavaScript Help for CodeIgniter 4

$
0
0
PHP Code:
<!DOCTYPE html>
<
html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body style="display:flex;justify-content: center;padding-top: 200px;">
        <div style="width:500px">
            <p style="text-align: center;">Version 1</p>
            <h2 id="showName" style="padding:20px;text-align: center;margin-bottom: 10px;height:30px;"></h2>
            <div style="display:flex;justify-content: center;">
                <input type="text" name="fullname" id="inputFullname"
                style="width:80%;padding:5px;">
            </div>
        </div>
        <div style="width:500px">
            <p style="text-align: center;">Version 2</p>
            <h2 id="showName2" style="padding:20px;text-align: center;margin-bottom: 10px;height:30px"></h2>
            <div style="display:flex;justify-content: center;">
                <input type="text" name="fullname" id="inputFullname2"
                style="width:80%;padding:5px;">
            </div>
        </div>

    </body>
</
html

Sorry for asking this, but I have a bit of a silly question:

I have two versions of a JavaScript snippet: version 1 and version 2. Both produce the same output, as shown in this proof (https://ibb.co.com/Ws1QWrx). What are the advantages and disadvantages of each?

PHP Code:
<script>
    // version 1 <-- using getElementById()
    const theFullname document.getElementById('inputFullname');
    theFullname.addEventListener ('keyup', ()=>{
        const theShowName document.getElementById ('showName');
        theShowName.innerHTML theFullname.value;    
    
})

    // version 2 <-- using element's id directly
    inputFullname2.addEventListener ('keyup',()=>{
        showName2.innerHTML inputFullname2.value;
    })

</
script

Problem with shield password validation

$
0
0
I am making a dialog to allow users to change their passwords, and it seems that the function to save the user data does not check for password validity (e.g. length). For example, in my controller:

Code:
$user = auth()->user();
$user->fill([
'password' => '123'//$this->request->getPost('newPassword')
]);

$result=auth()->getProvider()->save($user);
if ($result) log_message('info',"result: ok");
else log_message('info',"result: not ok");

$result is true, even if the password is too short (in Auth.php, $minimumPasswordLength = 8)
However, at the command line, it works and I get the message password too short.
What did I miss?


second question: since I was on the cli, I tried different passwords, and if I enter "12345678" or my username as password, it is accepted. is this normal?
I didn't change anything in Config/Auth.php

How to list mysql results grouped by one column value, groups listed bellow

$
0
0
I have table "properties" with columns id, name, location, type, price, sq_ft and some other...

I want properties to be listed grouped by value of "type"column (i.e. values in this columns are Townhome, Appartment, Condo). But, with "type" values as titles of the groups, and dinamically so when I add new value in type column i.e. "Commercial" those properties are listed too. So, what I want is:

Townhome
Townhome Property 1
Townhome Property 2

Appartment
Appartment Property 1
Appartment Property 2

Condo
Condo Property 1
Condo Property 2.... and bellow this, after adding "Commercial" in type column

Commercial
Commercial Property 1
Commercial Property 2

So, basically, any new type of properties is dinamically added with its properties and with title of type.

I am doing this in CodeIgniter 4 and so far I managed to list properties only per one type per page/view.

Cotroller:
Code:
public function getByPropType($type)
{
    $properties = $this->db->query("SELECT * FROM properties WHERE type = '$type'")->getResult();

    return view('props/props-by-type', compact('properties', 'type'));
}

View:
PHP Code:
<?php foreach($properties as $prop) : ?>
    <div class="col-md-6 col-lg-4 mb-4">
        <div class="property-entry h-100">
            <a href="<?= url_to('prop.single'$prop->id); ?>" class="property-thumbnail">
                <div class="offer-type-wrap">
                    <span class="offer-type bg-success"><?= $prop->type?></span>
                </div>
                <img src="<?= base_url('public/assets/images/'.$prop->image.''?>" alt="Image"
                    class="img-fluid">
            </a>
            <div class="p-4 property-body">
                <h2 class="property-title"><a
                        href="<?= url_to('prop.single'$prop->id); ?>"><?= $prop->name?></a></h2>
                <span class="property-location d-block mb-3"><span class="property-icon icon-room"></span>
                    <?= $prop->location?></span>
                <strong
                    class="property-price text-primary mb-3 d-block text-success">$<?= $prop->price?></strong>
                <ul class="property-specs-wrap mb-3 mb-lg-0">
                    <li>
                        <span class="property-specs">Beds</span>
                        <span class="property-specs-number"><?= $prop->num_beds?></span>

                    </li>
                    <li>
                        <span class="property-specs">Baths</span>
                        <span class="property-specs-number"><?= $prop->num_baths?></span>

                    </li>
                    <li>
                        <span class="property-specs">SQ FT</span>
                        <span class="property-specs-number"><?= $prop->sq_ft?></span>

                    </li>
                </ul>

            </div>
        </div>
    </div>
<?php endforeach; ?>

PHP - CodeIgniter Application - deployment error

$
0
0
I am getting error while deployment of PHP (CodeIgniter) application. I don’t want any runtime installation. And I see the issue is related to something PHP version but I am not sure. So can anyone help me to resolve issue ASAP. This is testing environment and After running successful on testing I have to create new production server.

Error Image:

[Image: 8487405660ef204bfd998bcb9ed5f9f965a69fde.png]
Viewing all 14343 articles
Browse latest View live


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