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

Model Lazy DB Connection

$
0
0
Hello!
Current Model logic creates a db connection as soon as any Model is defined, because of the __constructor of Model.php.
This is a pretty standard behavior for a light app but may create some problems when you're dealing with a lot of requests. Let me elaborate on that:
To handle a lot of incoming "get"/"read" request we implemented a very strong caching policy inside all of our SomethingModel -> getWhatever and we go to the DB only when needed.
Everything is working perfectly performance-wise except when we're having a spike of incoming calls because those were being translated to "empty" (read without any query) connections to MySQL - the only query that was passing is the infamous query to set the STRICT_ALL_TABLES.
That is pretty logic because that is generated by Database::connect() that is somehow warming up the connection someone will later use.
The problem is that in our scenario it greatly affect performances because we have to configure MySQL to at least support thousands of (empty) connections, and, since MySQL is on another machine, it also slows down the application because it's somehow connecting and authenticating to something else on the network.
I have seen that, in general, the query() stuff checks for a valid connection and if there isn't any, it will trigger a Database::connect() itself, so I was wondering how hard it would be do implement a Lazy DB Connection that does nothing when the Model is created and postpone the real connection to the moment any real DB activity is required.
If you think it's reasonable (and maybe have some hints on how to cleanly do that) I can also give it a shot and send a pull request - just wanted to make sure everything makes sense.
Thanks.

How to get Entity datamap from Model

$
0
0
Since Model is responsible for interacting with the database, when writing custom queries on my model, I need to get the actual field used in my table, as set in Entity datamaps, to be sure that I am not breaking my code.

How do I get the mapping for a property from a model? I see that Entity#mapProperty is protected.

I am new to CodeIgniter so I am not sure if my reasoning is correct, feel free to correct me.

How to show total days from date

$
0
0
I have article function to post an article and I want to show total days after this article is posted. For Example : 
I posted article at 27 June 2024, today is 2 July 2024. In my article will show the information "6 Days Ago"

My type data for date posting is : 
Unix Timestamp (1719853709) it will show 1 July 2024

My question is : 


  1. How to show total hours after submit (1 hours ago, 5 hours ago, 23 hours ago) if the article posted under 24 hours
  2. How to show total date after submit (1 Days Ago, 2 Days Ago, 20 Days Ago, 29 Days Ago) if the article posted under 1 month
  3. How to show total month (1 month ago, 2 month ago, 10 month ago, 11 month ago) if the article posted under 1 years
  4. How to show total years (1 Years Ago) 


Master, please help. Thank you very much.

$allowedHostnames only half-useful (?)

$
0
0
Since v4.3.0, Config\App::$allowedHostnames has permitted one to add multiple host URLs to be returned as though they were the base_url(), which is great!

However, having had a look at SiteURIFactory.php, I see the checking against this array of $allowedHostnames (in getValidHost()) is done using a simple text in_array() comparison... so it cannot digest wildcards.

Given that having Filters.php enabled strips out any questionable (or accidental) content in $_REQUEST and replaces the request with base_url(), or the $_REQUEST URL (if the host is in $allowedHostnames), this results in every possible subdomain host needing to be listed in $allowedHostnames.

There appears to be no other easy way to prevent Filters.php from doing this, without making the filtering conditions so wide-open that it renders Filters.php ineffective.  Under certain circumstances (like the ones I currently have), this causes $allowedHostnames to become really, really long... and, without a doubt, a nightmare to manage going forward.

So, my question is whether there is a way around this as the CI code currently stands?


And, if not, suggest that it would be great - and make this headache a complete non-issue - if $allowedHostnames permitted wildcards!  Smile

Would there be any sense to explicitly call these subdomain hosts... and if so, then have them identified only by their (subdomain) hostname, without the base_url() domain name portion?  In other words (in App.php):


Code:
['media.example.com', 'accounts.example.com']

would become:


Code:
['media', 'accounts']

... and this would make it reasonably simple to have getValidHost() upgraded to accept wildcards in the $allowedHostnames.


Edit:
In the interim, I've used a bit of duct-tape to patch it:

In App.php:


Code:
public array $allowedHostnames = ['.domain.com'];    // first hostname set to '.' + root domain (adding the '.' could also be done in SiteURIFactory.php)
 
and an (unfortunate) edit to the CI system code, in SiteURIFactory.php:


Code:
private function getValidHost(string $host): ?string
{
    if (str_ends_with($host, $this->appConfig->allowedHostnames[0])) return $host;
    ...

Set CORS in Codeigniter 4.5.3

$
0
0
Hi, i would like configure CORS on codeigniter 4.5.3. I have read this: https://codeigniter4.github.io/userguide.../cors.html but is not all clear.

in app/Config/Cors.php i set:
Code:
'allowedOrigins' => ['http://localhost:5173'],
'allowedHeaders' => ['Origin, X-Requested-With, Content-Type, Accept, Authorization'],
'supportsCredentials' => true,
'allowedMethods' => ['GET, POST, OPTIONS'],
 

How can i do to set CORS? I have to add something in my htaccess file?
Thanks for help me.

finfo_file(C:\Users\acer\AppData\Local\Temp\php19BC.tmp): Failed to open stream: No s

$
0
0
when i create function store to insert data into database it fine until i'm working the file, the image has been moved but why i got this error? please help me ?


PHP Code:
public function store()
    {
        $getImage $this->request->getFile('image');

        if ($getImage->getError() === 4) {
            if ($this->request->getPost('gender') == 'male') {
                $getImageName "default_male.svg";
            } else {
                $getImageName "default_female.svg";
            }
        } else {
            $getImageName $getImage->getRandomName();
            $getImage->move('img/uploadedImg'$getImageName);
        }

        $data = [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'username' => $this->request->getPost('username'),
            'gender' => $this->request->getPost('gender'),
            'major' => $this->request->getPost('major'),
            'address' => $this->request->getPost('address'),
            'phone' => $this->request->getPost('phone'),
            'image' => $getImageName
        
];

        if ($this->students->save($data) === false) {
            $errors $this->students->errors();
            return redirect()->to('student/create')->withInput()->with('errors'$errors);
        } else {
            session()->setFlashdata('insert''student added!');
            return redirect()->to('student');
        }
    


this the controller.

how should i print data to pdf fetched from phpmyadmin in codeigniter 3 view page?

$
0
0
in codeigniter 3 view page i use following ajax to fetch some data from phpmyadmin which consisted of some html data:


PHP Code:
$(document).ready(function() {
    $('#fetchDataButton').click(function() {
        var activeProfileId '<?php echo $AKTIF_PROFIL->id; ?>';

        $.ajax({
            url'{{$user_base_url}}/profil/get_report_content',
            type'GET',
            data: { activeProfileIdactiveProfileId }, // Pass the active profile ID as data
            dataType'json',
            success: function(response) {
                var reportContent_kullanici_profilleri_Full response.kullanici_profilleri;
                var reportContent_kullanici_profilleri reportContent_kullanici_profilleri_Full.find(function(item) {
                    return item.id == activeProfileId;                  
            
});
            console.log('Data received:'reportContent_kullanici_profilleri);
            },
            error: function(xhrstatuserror) {
                console.error('Error fetching data:'error);
            }
        });
    });  
}); 


i want to print this fetched data as pdf by dompdf.

for example the content of fetched data on console is as follows:


PHP Code:
<p>&nbsp;</p>

<
div class="container">
    <div class="row">
        <div class="col-12 text-center bg-secondary rounded my-5 py-5">
        <class="text-white m-0">Lorem ipsum dolor sit ametconsectetur adipisicing elitQuod tenetur ex natus at dolorem enim!</p>
        </div>
    </div>
</
div


how should i code for that?

could anyone provide required controller /ajax for that purpose?

thanks in advance.

Javascript fetch on a CI route returns 404

$
0
0
I need to send an asynchronous request from my 'thank you' page back to my server so it can do some email sending without blocking the initial thank you response.  This all works fine in my local environment with WAMP.  I get back the text response from the controller serving that route.  However, executing the same code on my website server always returns a 404 to the fetch().
I excluded that route from the CSRF 'before' globals in Filter.php.
My controller function for the route:
PHP Code:
    public function ppStewardOnly()
    {
        $session session();
        $invoiceID $session->get('invoiceID');
        //  RSIMLogger("notice", 'Steward only invoice : ' . $invoiceID);
        $session->remove('invoiceID');

        $transactionsModel model($this->modelPrefix 'TransactionsModel');
        $transaction $transactionsModel->findInvoice("rpu_$invoiceID");
        //  RSIMLogger("notice", 'Transaction : ' . json_encode($transaction, JSON_PRETTY_PRINT));

        if ($transaction != null) {
            $json $transaction->getStewards();
            $stewards json_decode($jsontrue);
            //  RSIMLogger("notice", 'Stewards : ' . $json);

            $this->sendStewardNotificationEmails($stewards);
            RSIMLogger("notice"'sendStewardNotificationEmails : COMPLETE');
        }

        //  RSIMLogger("notice", 'ppStewardOnly : COMPLETE');

        header("Content-Type: application/json");
        header("Access-Control-Allow_Origin: *");

        echo (json_encode('NOTIFY Complete'));
    
My view for the 'thank you' page contains [with my non-jQuery version of documentReady()]:
Code:
<?php $this->section('pagescripts') ?>

<script>
function SendAsyncRequest() {
fetch("/checkout/stewardOnly", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(`Notification failed: ${error}`);
});
}

docReady(function() {
// alert('Testing async function');
SendAsyncRequest();
});
</script>

<?php $this->endSection() ?>
I can successfully execute a fetch() to a stand-alone php file which returns a simple json string.  But I can't get fetch() to give back anything but a 404 when the target of the fetch is a CI route.
When all that logging is enabled in the controller, nothing ever gets written to the log on my server, so I'm sure we never get to the controller.  All very frustrating since I can only really do debugging in the local environment where everything works fine.

Anyone have any ideas?
Thanks for the help.

CFRS Token Problem in CI 4.5.3 ( BUG ??? )

$
0
0
Posted CFRS token value only exists with deprecated getVar method but not with getPost.

Debug $_POST and getPost() output there is no CFRS Token variable.

print_r($_POST) 
print_r($this->request->getPost())


Debug $_REQUEST and getVar() output there is CFRS Token variable.

print_r($_REQUEST) 
print_r($this->request->getVar())

In Codeigniter4 documentation I found a important message and warning message, so I should not use getVar method.
(https://codeigniter.com/user_guide/incom...tml#getvar)
Is it wrong in documentation?

I cannot use csrf_hash(), because it generate every time a new token.
So posted token can't be checked with.


Here are the messages from documentation.

Important
This method exists only for backward compatibility. Do not use it in new projects. Even if you are already using it, we recommend that you use another, more appropriate method.

Warning
If you want to validate POST data only, don’t use
getVar()
. Newer values override older values. POST values may be overridden by the cookies if they have the same name, and you set “C” after “P” in request-order.

Error page in production (CI 3)

$
0
0
Hello,
Actually, in production mode, an error will send blank page to user. Is it possible to send a fixed error html page (blank page is ambigous for users), just to say there is an error ?
In advance, thank you.

SQL

$
0
0
Hello, 
I build a query with query builder and sqlsrv driver, with this code
$this->join("[Ultrafog Sp_ z o_o_\$Production BOM Line] as job_items", "job_line.No_ = job_items.[Production BOM No_]", 'LEFT');
the driver generate this wrong query
LEFT JOIN "ultrafog_prod"."dbo"."[Ultrafog" Sp_ z o_o_$Production BOM Line]" as "job_items" ON "job_line"."No_" = "job_items"."[Production BOM" "No_]"
Seem it have problem with column and field name with space ignoring square bracket
Some one konw a work around?

How to easily learn codeigniter 3?

$
0
0
Hi guys, noob here. I am a new hired dev that the team focuses on codeigniter 3, are there any tips or guides i can use to train my codeigniter skills?

Trouble installing Shield

$
0
0
Hi everyone,

I'm new to COdeIgniter and trying to install Shield.

I have CI installed correctly, I have Shield installed but when I go to run the command:

Code:
php spark shield:setup

I receive the message:

Code:
Command "shield:setup" not found.

At this point I follow the manual installation guide but when i have to execute the command:

Code:
php spark migrate --all

I receive the message:

Code:
Call to a member function routes() on null

at APPPATH\Config\Routes.php:11

Does anyone know how I can solve it?
Thanks!

Magic login link not working - SHIELD CI4

$
0
0
I am using shield for Authorization, I have created API to send magic login link, email receives with magic link. when I click on link, it's makes the user login.
Earlier this whole process was working fine, but now suddenly stopped. 
I tried to test the default links as well, that too not working. Showing "Unable to verify the link." error
https://prnt.sc/Ws3I6O-RFjMA

Below is my code
PHP Code:
public function forgotPassword() {
        $currentLang $this->request->getVar("lang") ?? DEFAULT_LANGUAGE;
        $this->request->setLocale($currentLang);

        $rules = [
            "email"      => "required|valid_email"
        ];

        if(!$this->validate($rules)){
            $response = [
                "status"    => false,
                "message"  => $this->validator->getErrors(),
                "data"      => []
            ];
        } else {

            $userEmail $this->request->getVar('email');
            $users auth()->getProvider();
            
            $user 
$users->findByCredentials(['email' => $userEmail]);

            if($user){
                $firstName $user->first_name;

                // Generate a unique token
                $token bin2hex(random_bytes(16));

                // Store the token in the user's session or any temporary storage
                $session session();
                $session->set('magic_link_token'$token);

                // Generate the magic link URL
                $magicLinkUrl site_url("api/magic-login/{$token}");

                // sending email  here
                sendEmail($emailData);

                $response = [
                    "status"    => true,
                    //"message"  => 'Magic link sent on your email. Please login with this link and update your password.',
                    "message"  => lang('App.forgot_success'),
                    "data"      => ['magic_link_url' => $magicLinkUrl]
                ];
            } else {
                $response = [
                    "status"    => false,
                    "message"  => lang('App.email_notExist'),
                    "data"      => []
                ];
            }
            
        
}

        return $this->respondCreated($response);
    


Here is my code to verify link
PHP Code:
public function magicLogin($token)
    {
        $currentLang $this->request->getVar("lang") ?? DEFAULT_LANGUAGE;
        $this->request->setLocale($currentLang);
        
        
// Retrieve the token from the URL parameter
        // Validate the token, you may check it against the session or temporary storage
        $session session();
        $storedToken $session->get('magic_link_token');

        if ($token === $storedToken) {
            // Token is valid, log the user in
            $user auth()->user();

            $token $user->generateAccessToken(SECRET_KEY);
            $auth_token $token->raw_token;

            // Return a success message as a JSON response
            $response = [
                "status"    => true,
                "message"  => lang('App.login_success'),
                "data"      => ['token' => $auth_token]
            ];
        } else {
            // Invalid token
            $response = [
                "status"    => false,
                "message"  => lang('App.invalid_link'),
                "data"      => []
            ];
        

        return $this->respondCreated($response);
    

Please guide what is the issue. I searched alot regarding this, but didn't find anything regarding this.
Thanks

NGINX: Multiple CI Apps on a Single Domain Not Working

$
0
0
How can I make https://api.domain.com/appname show the contents of /home/www/api.domain.com/appname/public
+ and retain the ability to show /home/www/api.domain.com/index.php at https://api.domain.com/
+ and retain the ability to host other unrelated php-based api backends at https://api.domain.com/anotherAPIthing or any other arbitrary URI structure on api.domain.com?


I have CI4.5.3 installed at /home/www/api.domain.com/appname. My domain (api.domain.com) root is /home/www/api.domain.com.

I do not want to change the main(outer-most) docroot of https://api.domain.com/ because I would like to have multiple api backends hosted there (for example api.domain.com/appname, api.domain.com/anotherapp, etc..). If I change the main docroot then I can only use https://api.domain.com for my 'appname' app.

I've tried so many different configurations I can't even remember all of them... Here is my current configuration (which does not work for me)
Code:
server {
    listen serverip:443 ssl;
    http2 on;
    server_name api.domain.com www.api.domain.com;
    root /home/www/api.domain.com/;
    index index.php index.html index.htm;

    ssl_certificate /etc/pki/tls/certs/api.domain.com.bundle;
    ssl_certificate_key  /etc/pki/tls/private/api.domain.com.key;
    include /etc/nginx/ssl.conf;
    include /etc/nginx/basicheaders.conf;
    include /etc/nginx/nocache.conf;

  location /appname {
      root /home/www/api.domain.com/appname/public/;
#      alias /home/www/api.domain.com/appname/public/;

#      try_files $uri $uri/ /index.php$is_args$args;

      location ~ [^/]\.php(/|$) {
          include /etc/nginx/fastcgi.conf;
          if (!-f $document_root$fastcgi_script_name) {
              return  404;
          }
          fastcgi_pass    unix:/opt/alt/php-fpm83/usr/var/sockets/www.sock;
          fastcgi_index  index.php;
      }
  }


  location / {
    location ~ [^/]\.php(/|$) {
      include /etc/nginx/fastcgi.conf;
      if (!-f $document_root$fastcgi_script_name) {
        return  404;
      }
      fastcgi_pass    unix:/opt/alt/php-fpm83/usr/var/sockets/www.sock;
      fastcgi_index  index.php;
      }
  }
...
}


With the above configuration I get the following error when trying to access my CI app via https://api.domain.com/appname:
Code:
2024/07/05 00:29:39 [error] 72934#72934: *14 "/home/www/api.domain.com/appname/public/appname/index.php" is not found (2: No such file or directory), client: REDACTED, server: api.domain.com, request: "GET /appname/ HTTP/2.0", host: "api.domain.com"
However https://api.domain.com does load /home/www/api.domain.com/index.php as desired/expected.

I'm not very good at nginx configurating but I've tried using rewrites as well and they always end up with infinite redirects or attempting to access "/home/www/api.domain.com/appname/public/appname/public/index.php" or "/home/www/api.domain.com/appname/public/appname/appname/appname/appname/appname/" etc

Cannot use Auto routing (Legacy) [SOLVED]

$
0
0
For a legacy project, I wanted to use Auto routing (Legacy).
I followed as per doc, but the project's routing is not behaving like legacy.
It was showing following error:
404 - File not found
Cannot access CLI Route: /

Today it is showing following error:
404 - File not found
Page not found

I tried to find the errors and here's a parital text of print_r result and I find the same issue where CLI route is blocking this.

Array
(
    [0] => Array
        (
            [file] => D:\laragon\www\portal4\system\CodeIgniter.php
            [line] => 981
            [function] => forPageNotFound
            [class] => CodeIgniter\Exceptions\PageNotFoundException
            [type] => ::
            [args] => Array
                (
                    [0] =>
                )

        )

    [1] => Array
        (
            [file] => D:\laragon\www\portal4\system\CodeIgniter.php
            [line] => 364
            [function] => display404errors
            [class] => CodeIgniter\CodeIgniter
            [type] => ->
            [args] => Array
                (
                    [0] => CodeIgniter\Exceptions\PageNotFoundException Object
                        (
                            [message:protected] => Cannot access CLI Route: /
                            [string:Exception:private] =>
                            [code:protected] => 404
                            [file:protected] => D:\laragon\www\portal4\system\Router\AutoRouter.php
                            [line:protected] => 120
                            [trace:Exception:private] => Array
                                (
                                    [0] => Array
                                        (
                                            [file] => D:\laragon\www\portal4\system\Router\Router.php
                                            [line] => 563
                                            [function] => getRoute
                                            [class] => CodeIgniter\Router\AutoRouter
                                            [type] => ->
                                            [args] => Array
                                                (
                                                    [0] => /
                                                    [1] => GET
                                                )

                                        )


How do I use Auto routing (Legacy) without changing cli routes?


I hope someone may help me resolve this issue

I also put a bug issue but it was closed and advised to seek from the forum.


Thanks in advance

If Programming Languages Were People: The Office Edition

Proposal for Model Events Enhancement

$
0
0
Hello,

I would like to propose an enhancement to the model events functionality in CodeIgniter 4. 
My suggestion is to allow closures as event callbacks in addition to the current method-based callbacks. This change would provide greater flexibility and simplicity in handling model events.

Thank you for considering this suggestion.
Best regards

Enhance Entity Casting with PHP 8 Enum Support

$
0
0
Dear CodeIgniter Development Team,

With the recent transition to PHP 8, I would like to propose an enhancement to the entity casting functionality, specifically focusing on the $defaultCastHandlers array within the Entity class.

The current $defaultCastHandler array manages various data types, providing default convert handlers for types like arrays, booleans, CSV, datetime, floats, integers, JSON, objects, strings, timestamps, and URIs. 
My proposal is to extend this capability to include enums, allowing developers to specify enum types and have them automatically cast to the appropriate enum instances.


This enhancement would bring several benefits:
  • Improved type safety by enforcing enum values.
  • Cleaner and more maintainable code by using enums instead of string constants or other scalar types.
  • Better integration with PHP 8 features, aligning with modern PHP development practices.
Thank you for considering this enhancement. I believe it will significantly improve the developer experience and align CodeIgniter with modern PHP capabilities.
Best regards

site_url possible modification

$
0
0
PHP Code:
http://mysite.com/2

site_url(2crashes because SiteURI->siteUrl is declared as siteUrl(array|stringnull|string....)

if 
I cast it as a string it works eg site_url((string)2)
but maybe the parameter should be changed to array|string|int 

Bill
Viewing all 14343 articles
Browse latest View live


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