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

Understanding JSON Web Tokens (JWT) in JavaScript


Web Design & Development

$
0
0
Hello! My name is Reriya, and I am a professional PHP Developer with a strong passion for creating dynamic and user-friendly websites. Over the years, I have developed several web projects that have received excellent feedback. Two of my most notable works are Golden Bird Jewels and Ouros Jewels, both of which have been well-received in the jewelry industry. I would love to share these projects with you for your feedback or potential collaboration. Please let me know if you'd be interested in taking a look!

How can I pass multiple queries from different tables to a single view in CodeIgniter

$
0
0
Hi everyone,
I'm very new to CodeIgniter. I'm trying to send queries from the controller to a single view. I have two different functions, each with a different query, and I want to style their results differently in the same view.
Here’s my controller code:
Code:
public function publications()
{
    $query = $this->db->query('SELECT P_ID, TITLE FROM publications WHERE SSN = 1');
    $data['name'] = 'publications';
    $data['section'] = 'Publication';
    $data['query'] = $query;
    $this->load->view('adel', $data);
}
public function teaching()
{
    $query = $this->db->query('SELECT C_ID, DEP_CODE, C_NAME, C_DESC FROM TEACHING WHERE SSN = 1');
    $data['name'] = 'teaching';
    $data['section'] = 'Teaching';
    $data['query'] = $query;
    $this->load->view('adel', $data);
}
And here’s the corrected view code:
Code:
<div class="col-lg-12">
    <h1><?= $section ?></h1>
    <?php if ($name == 'publications'): ?>
        <?php foreach ($query->result() as $row): ?>
            <?= $row->P_ID ?>: <?= $row->TITLE ?><br><br>
        <?php endforeach; ?>
       
    <?php elseif ($name == 'teaching'): ?>
        <?php foreach ($query->result() as $row): ?>
            <?= $row->DEP_CODE ?><?= $row->C_ID ?> <?= $row->C_NAME ?><br>
            Course Description:<br>
            <?= $row->C_DESC ?><br><br>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

Main fixes:
  • Use == for comparison, not = .
  • Use cleaner PHP short syntax inside HTML.
  • Close PHP properly for loops and conditions.

CI4 validation greater_than on date field

$
0
0
HI ,

can i validate date with grater than ? 
this is my validation :
Code:
                'data_tour' => [
                    'label' => 'Data Partenza',
                    'rules' => 'required|valid_date[Y-m-d]|greater_than[' . date('Y-m-d') . ']',
                    'errors' => [
                        'required' => '{field} obbligatorio',
                        'valid_date' => ' {field} deve essere una data valida',
                        'greater_than' => ' {field} deve essere maggiore di oggi'.$post['data_tour'].'|'. date('Y-m-d'),                   
                    ]

                ],

and this is the validation (not passed) :
                Data Partenza deve essere maggiore di oggi2025-04-21|2025-04-20
2025-04-21 is bigger than 2025-04-20...

Problem with CLI script routing or execution

$
0
0
Hi All,
I'm trying to add some cron scheduled jobs to my site. I've started with a simple controller:

PHP Code:
<?php

namespace App\Controllers\CLI;

use 
CodeIgniter\Controller;

class 
Cronjob extends Controller
{
    public function cliMessage($to 'World')
    {
        return "Hello {$to}!" PHP_EOL;
    }


When I call it in my public directory

Code:
php index.php CLI/cronjob message

no output is showed. The index.php and routing are executed for sure, infact if I make some mistakes on porpouse, they are showed. For example, this is the output of the following command

Code:
PS C:\develop\horizon\public> php index.php CLI/cronjob mAssage
ERROR: 404

Controller or its method is not found: \App\Controllers\CLI\Cronjob::cliMAssage

Any help is appreciated.

Receiving Email from within CI 4 and possible integration with the built-in Email cla

$
0
0
Hello friends and community members,

I reached a point where at least one of my CI4 apps needs to receive (or intercept incoming) e-mail, and it looks like the built-in Email class has no facility for it - which is natural.

Common sense would point to a 3rd party library, and in today's jungle of 'me too' products ranging from 'great fit's to misfits, I wanted to ask experts who might have already done this before. 

What do you think is the best email client library for integrating with CI4 compatible with PHP 8.3 (or 8.4 even better)?

My specific need is to receive (or intercept) emails sent to a specific account, do some processing (analytics, maybe SMAP check), and then re-forward the same e-mail to a pre-defined set of recipients. I can do the sending already thanks to the built-in 

Email class, but receiving is not possible with the built-in classes and/or functions AFAIK.
Any ideas?

JetBrains PHPverse 2025 Join the free virtual event along with community experts to c

funny mysql issue i don't understand

$
0
0
Hi,
i'm running into a funny issue i can't understand with a simple query, this
Code:
$this->db->query("update table set field = NULL where id = xx");
doesn't do anything (whether the updated column is alone or aamong other cols, prepared query or not) and, of course, the field is set to be NULL by default
i must admit i do not understand at all why because pastnng exactly the same query in the phpmydamin sql tab query field it works like a charm!
(codeigniter 4.5.3)
if any of you had a lightful idea that would help me understand why my old brain is stuck Smile
have a nice day

edited just because i forgot to say it's a date field

New version of PHP: The "Right" Way is available

Best way to add an anchor to pager links

$
0
0
Hi everyone,

I was interested in adding an anchor to my pager links to make sure that when users navigate through their results, they don't have to scroll back down to them, but rather stay at the same page level. Better user experience...
I thought I could add an anchor as a parameter maybe, but looking at the pager documentation, It does not look possible. 
I thought maybe I could pass a value to the template from my $viewData variable but when I tried, I got an 'undefined variable' error ; the template does not have access to my views variables?
In the end I made it work this way: I created 2 different templates, one to be used in my bookings page, with the #bookings anchor I need, one in my presentations page where there are reviews, with the #reviews anchor I need and I select the template to be used in my controller or my view.
It works but I feel there could be a better way to avoid having 2 template files where the only thing that changes is an anchor.
Can you share your thoughts on the best way to do this?

How to refer to 'session' in my code

$
0
0
Hi Team,
Chugging my way through the 3->4 migration guide, I did as suggested and changed all my old $this->session calls to $session (and all the slightly different methods).
I then wondered how/where to initialise it as the superglobal is no more and v3 autoloading has been "improved".
Eventually I read about the BaseController and how to initialise stuff there.
However, the example in the forum (somewhere) suggests setting a private $session variable and then calling $this->session = \Config\Services:Confusedession(); in the constructor.
I think I now need to refer to the session object using $this->session.
So is is $session or $this->session?
I'm so bewildered.
cheers, Paul

How use MATCH(action) AGAINST(?)

$
0
0
How use MATCH(action) AGAINST(?) in Query Builder Class
i have found only like mode

Option to translate uri to camel case

$
0
0
Hi All,
I'm currently using improved auto-routing, so the option to convert URIs to camelCase caught my attention. It was introduced in version 4.5.0 and enabled by default starting from version 4.6.0. I had to disable it to avoid breaking my project's code, but I'm seriously considering refactoring the code to make use of it.
The documentation notes that "The option to disable 'Translate URI To CamelCase' exists only for backward compatibility. We don’t recommend to disable it." — but the reasons behind this recommendation aren't entirely clear to me.
Before diving headfirst into the refactor, I'd like to hear your thoughts on the pros and cons of enabling this option.
Thanks in advance for any suggestions, advice, and opinions!

Model Find function Changed?

$
0
0
In the past when I used the find() function on a model while passing the primary key, I would get a single result as the documentation states. It seems now in v. 4.6.0 it acts like it is going to return multiple results. This requires me to call $returnedArray[0]['name'] instead of just $returnedArray[0]['name']

My Relevant Code:
PHP Code:
$transID $this->request->getPost('trans_id',FILTER_SANITIZE_NUMBER_INT);
$transModel = new \App\Models\TransactionModel();
$prevTran $transModel->find($transID);

//Make sure this payment intent isn't already paid
if($prevTran['status'] == 'paid') {
                    
    
//This transaction is already paid
    
echo json_encode(array('status'=>'alread_paid','message'=> 'This transaction is already marked as paid.'));
    exit();
                    



This results in error:
Quote:message 'Undefined array key "status"'

Upon inspecting the return from the database I can see the issue is that it's returning the row within a multidimensional array.

Expected Return:
Code:
$transModel = [
    'id'         => 1,
    'name'    => 'Registration',
    'status'    => 'paid',
]

Actual Return
Code:
$transModel = [
    [0]    =>    [
        'id'         => 1,
        'name'    => 'Registration',
        'status'    => 'paid',
    ],
]

I can do a work around by just overwriting the response. But am I wrong in believing this should already be the default response.

PHP Code:
$transID $this->request->getPost('trans_id',FILTER_SANITIZE_NUMBER_INT);
$transModel = new \App\Models\TransactionModel();
$prevTran $transModel->find($transID);

//Overwrite the return here
$prevTran $prevTran[0];

//Make sure this payment intent isn't already paid
if($prevTran['status'] == 'paid') {
                    
    
//This transaction is already paid
    
echo json_encode(array('status'=>'alread_paid','message'=> 'This transaction is already marked as paid.'));
    exit();
                    

Feature to not append database prefix in QueryBuilder

$
0
0
Currently I'm not aware of the means to prevent query builder from appending the database prefix, so which you need to run a query where you do not want the prefix appended, you either can't use QueryBuilder or you have to use acrobatics to make it work. Please consider adding a parameter to QueryBuilder turning off the appending of the database prefix.

Take this code as an example of what I mean

PHP Code:
function dropForeignKeyConstraints(array $foreignKeysstring $table): void {
    
$db Database::connect();

    
$prefixName $db->getPrefix();
    
$db->setPrefix('');
    
$database_name $db->database;

    foreach (
$foreignKeys as $fk)
    {
        
$builder $db->table('INFORMATION_SCHEMA.TABLE_CONSTRAINTS');
        
$builder->select('CONSTRAINT_NAME');
        
$builder->where('TABLE_SCHEMA'$database_name);
        
$builder->where('TABLE_NAME'$table);
        
$builder->where('CONSTRAINT_TYPE''FOREIGN KEY');
        
$builder->where('CONSTRAINT_NAME'$fk);
        
$query $builder->get();

        if(
$query->getNumRows() > 0)
        {
            
$db->query("ALTER TABLE `$table` DROP FOREIGN KEY `$fk`");
        }
    }

    
$db->setPrefix($prefixName);


To prevent the query builder from appending the dbPrefix to INFORMATION_SCHEMA.TABLE_CONSTRAINTS, which would break the query, I need to capture the prefix, set it to an empty string, then put it back after I'm done with the QueryBuilder so that code below resumes the prefix appending. While this isn't needed all the time, it's better if I don't pepper the code with these extra three lines. I could write $prefixName = removePrefix() and restorePrefix($prefixName) helper functions, but that really only saves me one line of code. It would be better if I could call something like $builder = $db->table('INFORMATION_SCHEMA.TABLE_CONSTRAINTS', false); where the false parameter in the table() function returned the query without the prefix appended.

CodeIgniter 4.6.1 released!

$
0
0
Hi all,

We are pleased to announce the immediate availability of v4.6.1! This is a patch release. Please update to this version when possible.

Changeloghttps://codeigniter4.github.io/userguide...4.6.1.html
Upgradinghttps://codeigniter4.github.io/userguide...e_461.html

NOTE: When upgrading, please pay attention to the project files that need to be updated, particularly the config files.

CodeIgniter v4.6.1 Translations is also released!

Here is the status of the translations: https://codeigniter4.github.io/translations/
If you are fluent or a native speaker of any of the languages with incomplete translations, please send a pull request to update!

CodeIgniter 4.6.1 has been released

$
0
0
CodeIgniter 4.6.1 has been released Download
Upgrading from 4.6.0 to 4.6.1
Changes
Bugs Fixed
I' am sorry to say that while I was cleaning up the SPAM this morning I Accidently deleted the thread.
Which I' am reporting to MyBB because the thread was not even checked a post was.
Again sorry for my mistake.

I have emailed Paul to let him know about it.

CI4 not loading after fresh install — blank page on localhost Post:

$
0
0
I’m trying to set up CodeIgniter 4 on my local dev machine (Ubuntu 22.04, PHP 8.1) for a side project — a fresher job board I’m working on: https://247uaefreshers.com.
I followed the official CI4 install guide using Composer, no issues during setup. But when I navigate to
Code:
localhost:8080
, I just get a blank white page — no error, no logs, nothing in the browser console either.
I’ve tried:
• Running
Code:
php spark serve
(starts fine)
• Double-checked
Code:
.env
settings
• Permissions on writable/ seem okay
• Tried adding basic echo in
Code:
app/Controllers/Home.php
— still blank
Anyone seen this behavior before? Wondering if I missed something basic. Appreciate any tips ?

Is hiring a digital marketing agency really worth it for startups?

$
0
0
Hey folks,
I'm in the early stages of launching my startup and I keep hearing that working with a digital marketing agency can make a big difference in growth and online presence. But I’m not totally convinced yet—there’s a lot of conflicting advice out there.
So I wanted to ask: Has anyone here actually hired a digital marketing agency when their business was just starting out? What kind of impact did it have? Was it worth the cost?
Also, what should a startup really expect from a digital marketing agency? I’m talking realistic outcomes—not just vague promises of "more traffic."
Would love to hear any personal experiences or tips before I commit to anything. Thanks in advance!

intermittent smtp failures with gmail

$
0
0
CI version 3.1.13
We've seen this more than a few times where, out of the blue, sending mail thru google randomly declines to auth.  Usually about 24 hours or so later the problem resolves itself.  

No changes to my config/email.php file since Dec of '23.  

Sending 200ish emails a day will work fine for months on end, and then suddenly I human notified that emails that CI has sent are not appearing in the gmail sent mail folder.  

The CI logs show about 1 in 10 smtp failure messages like the one below.  Server is running on a DigitalOcean droplet in the SF region.  Requested help at DO as well.

How can I best troubleshoot this? 

Code:
220 [url=http://smtp.googlemail.com]smtp.googlemail.com[/url] ESMTP<uuid>.110 - gsmtp
<br /><pre>hello: 250-smtp.googlemail.com at your service, [159.65.78.78]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
</pre>Failed to authenticate password. Error: 535-5.7.8 Username and Password not accepted. For more information, go to
535 5.7.8  [url=https://support.google.com/mail/?p=BadCredentials]https://support.google.com/mail/?p=BadCredentials[/url] <uuid>.110 - gsmtp
<br />Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.<br /><pre>Date: Thu, 24 Apr 2025 15:24:09 +0000

My config/email.php:

Code:
$config['useragent'] = '';
$config['protocol'] = 'smtp'; 
$config['mailpath'] = '/usr/sbin/sendmail'; 
$config['smtp_host'] = 'ssl://smtp.googlemail.com'; 
$config['smtp_user'] = 'user@domain.com'; 
$config['smtp_pass'] = 'passwd'; 
$config['smtp_port'] = 465; 
$config['smtp_timeout'] = 30; 
$config['smtp_keepalive'] = FALSE; 
$config['smtp_crypto'] = ""; 
$config['wordwrap'] = TRUE; 
$config['wrapchars'] = 76; 
$config['mailtype'] = 'html'; 
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = '3'; 
$config['crlf'] = "\r\n"; 
$config['newline'] = "\r\n"; 
$config['bcc_batch_mode'] = ''; 
$config['bcc_batch_size'] = ''; 
$config['dsn'] = ''; 
Viewing all 14343 articles
Browse latest View live


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