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

dompdf page numbering and cover image for html content exceeding one print page.

$
0
0
Hi everyone.
i fetched some html content from phpmyadmin sql table and print them to pdf by dompdf in my codeigniter 3 project.
here, i have some columns (page titles) with some html content which could be exceeds one print page (A4 landscape).
as well i add page number or background cover for pages, but just the first page in each column content has cover image and just the last page has footers for page number.
here is the function i used to create html content for dompdf:

    // Helper function to generate page HTML with title
PHP Code:
    public function generatePageHtml($name,$title1$title2 null$title3 null$content$image_path$page_number=null) {
        $html '<div style="position: relative; width: 100%; height: 100%; page-break-after: always; margin: 0; padding: 0;">';
        $html .= '<style>@page { margin: 0; }</style>';
    
        
if ($image_path && file_exists($image_path)) {
            $image file_get_contents($image_path);
            $base64 'data:image/jpeg;base64,' base64_encode($image);
            $html .= '<img src="' $base64 '" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; object-fit: cover; margin: 0; padding: 0;">'// opacity: 0.7;
        }
    
        $html 
.= '<div style="padding: 20px; position: relative; z-index: 1; margin: 0;">';
        $html .= '<h1 style="text-align: center; text-decoration: underline; margin: 0;">' $title1 '</h1>';
    
        
if ($title2) {
            $html .= '<h2 style="text-align: center; margin: 0;">' $title2 '</h2>';
        }
        if ($title3) {
            $html .= '<h3 style="text-align: center; margin: 0;">' $title3 '</h3>';
        }
    
        $html 
.= $content;
        $html .= '</div>';
        $html .= '<div style="position: absolute; bottom: 20px; left: 20px; font-size: 12px; font-weight: bold;font-style: italic; color: gray;"> '$name .' - '$title1' - '$title2'</div>';

        if ($page_number !== null) {
            $html .= '<div style="position: absolute; bottom: 20px; right: 10px; font-size: 12px; font-weight: bold; color: gray;border: 1px solid black; padding: 10px; display: inline-block; border-radius: 3px;"> '.$page_number '</div>';
        }
        $html .= '</div>';
        return $html;
    


how should i consider coding so that when a html content exceeds one print page, the next pages of same content as well has cover image and get numbering as well.

Content Security Policy Header and Debug bar

$
0
0
Why isn't the CSP response header displayed in the Var section of the CI debug bar? 
It is showing Permissions Policy, Cache Control, Referrer Policy, Accept-CH, and Content-Type but no Content-Security-Policy. 

Code:
Response ( 200 - OK )
HEADERS
Content-Type text/html; charset=UTF-8
Accept-CH sec-ch-save-sata, save-data, width, sec-ch-width, viewport-width, sec-ch-viewport-width, sec-ch-viewport-height, viewport-height, device-memory, ect, sec-ch-prefers-color-scheme, sec-ch-prefers-reduced-motion, sec-ch-prefers-reduced-transparency, sec-ch-prefers-contrast, sec-ch-forced-colors, sec-ch-prefers-reduced-data
Cache-Control private, max-age=86400
Referrer-Policy no-referrer
Permissions-Policy accelerometer(), ambient-light-sensor(), autoplay(), battery() bluetooth(), camera(), ch-ua(), ch-ua-arch(), ch-ua-bitness(), ch-ua-full-version(), ch-ua-full-version-list(), ch-ua-mobile(), ch-ua-model(), ch-ua-platform(), ch-ua-platform-version(), ch-ua-wow64(), cross-origin-isolated(), display-capture(), encrypted-media(), execution-while-not-rendered(), execution-while-out-of-viewport(), fullscreen(self), geolocation(), gyroscope(), hid(), idle-detection(self), keyboard-map(), magnetometer(), microphone(), midi(), navigation-override(), payment(), picture-in-picture(), publickey-credentials-get(), screen-wake-lock(), serial(), sync-xhr(), usb(), web-share(), xr-spatial-tracking()

CodeIgniter Content Security Policy and Website Assets

$
0
0
It appears implementing a Content Security Policy using CodeIgniter is falling short of what is required for a website. Individual resources fetched from our server to support my app are not subjected to the CSP. My security people are complaining that jpg, png, and other assets are allowed to be framed because the frame-ancestors policy is not in effect for them. I do have it set in Config/Registrar.php along with my other config mods. They are only complaining about these assets and not the html pages built by CodeIgniter.
Am I going to have to put the CSP directives in Apache's httpd.conf and not use CodeIgniter to do this? Or maybe using the Registrar facility is the problem and I need to put them in Config/ContentSecurityPolicy.php?
The CSP frame-ancestors is working for the entire page but not individual resources. Personally I think the security guys have become extremists.

Another thing I noticed. If I put a partial CSP directive in Apache's httpd.conf it wipes out everything in the CodeIgniter config.

Complex Array Validation Rules

$
0
0
I'm trying to develop some complex rules to validate a JSON document being sent to the codeigniter script.  I think I might have a misunderstanding of the specific rules.
For example, here is a snippet of the validation rules I'm currently using:
PHP Code:
"fees" => [
            "label" => "Fees",
            "rules" => "permit_empty|fee_valid_structure|is_array",
        ],
        
        
"fees.*.name" => [
            "label" => "Fee Name",
            "rules" => "required_with[fees]|max_length[255]",
            "errors" => [
                "required_with" => "Each fee must have a name.",
                "max_length" => "The fee name must not exceed 255 characters.",
            ]
        ],
        "fees.*.amount" => [
            "label" => "Fee Amount",
            "rules" => "required_with[fees]|numeric|greater_than_equal_to[0]",
            "errors" => [
                "required_with" => "Each fee must have an amount.",
                "numeric" => "The fee amount must be a number.",
                "greater_than_equal_to" => "The fee amount must be at least 0.",
            ],
        ], 

My expectation is that the fees.*.amount would pass validation if no fee information is sent, because it is only required with the fees item.  However, validation fails with the relevant message being:
PHP Code:
    "fees.*.amount""The fee amount must be a number."

I don't get an error about the name. So, I'm missing something.  Is the permit_empty also required for the fee amount?
Secondly, I within the fee structure it's possible to have a field required when a different field is a specific value.  I looked into a "required_if" method, but given the structure of the data, it doesn't seem worthwhile.  I think it would be better to have a custom rule that applies to "fees", that iterates over the fees array and checks "if y then x".  Is it possible to set a custom error message from within a class?  For example, a method might look like:
PHP Code:
class FeeRules extends Rules
{
    public function fee_valid_structure($str null, ?string $params null, array $data = []): bool
    
{}


The callable and closure rules look like they have an error parameter, but this does not...

Shield: check user isActivated() do not work properly by using custom action register

$
0
0
Hi guys. I need little help for this case.
I am using custom action for register, like this one below:
PHP Code:
public array $actions = [
        'register'  => RegisterAction::class,
        'login'    => null,
    ]; 


and it works properly. but when i wanna to check if the user is already active or not by using
auth()->user()->isActivated() or auth()->user()->isNotActivated() it return differently from active properties.
PHP Code:
/** @var Session $authenticator */
        $authenticator auth('session')->getAuthenticator();

        $user $authenticator->getPendingUser();

        dd([
            'isActivated'  => $user->isActivated(),
            'isNotActivated'=> $user->isNotActivated(),
            'active'        => $user->active
        
]); 


result:
Code:
['isActivated' => true, 'isNotActivated' => false, 'active' => false]

or am i doing it wrongly?

Thank you in advanced.

How can I integrate software and hardware in my product?

$
0
0
AJProTech specializes in both hardware and software integration, making sure your product functions flawlessly. Their team manages the entire process from design to implementation. Visit https://ajprotech.com for more info.

I create simple Plugin to generate swagger file

Best Practices for Optimizing Database Queries in CodeIgniter 4

$
0
0
Hi everyone,
I’m currently working on a project using CodeIgniter 4, and I'm looking for advice on how to optimize database queries to improve performance. What are some best practices you’ve found useful when working with CodeIgniter’s Query Builder or raw queries? Specifically, I’m interested in reducing query execution time and improving the overall database efficiency for larger datasets. Additionally, any tips on indexing or caching within CodeIgniter would be greatly appreciated!
Looking forward to your insights and suggestions!

[DISCUSSION] - wanna join to opensourcepledge.com?

$
0
0
After reading blog on rector-is-joining-open-source-pledge, I'm interested in making this thread, even though Codeigniter is actually community-based. And the goal is maintain small footprint for light and fast. As i see it, core member have another work, There are many libraries out there for Codeigniter that are made independently. Maybe it could be managed better officially so that it gets attention from the community, just like Shield.

Likewise, moderators are always active in providing answers to the forum, I hope this can make more people join the community.

Quote:What is the Open Source Pledge?
Open Source Pledge is a group of companies with a shared commitment to paying the maintainers of the Open Source software we all consume. Our goal is to establish a new social norm in the tech industry of companies paying Open Source maintainers, so that burnout and related security issues such as those in XZ and Apache Log4j can become a thing of the past.

Read full on https://opensourcepledge.com/about/

PHP + Codeigniter + Perfex CRM

$
0
0
Hi guys,
I'm looking for a developer for some perfex Modules.

We are interested in building a long-term partnership for the development of multiple modules for our company, as we know that other businesses could benefit from these solutions as well.

To start, we're looking for a relatively simple module for our web hosting company. We're currently using Plesk and Keyhelp (a German web hosting panel similar to Plesk, with an API). The module we need would enable web hosting account management directly through PerfexCRM. Specifically, we would like the following features:

Create hosting packages on the server side.
Display access details within the PerfexCRM customer portal.
Provide basic account management features (similar to the WHMCS Plesk Extension module: https://marketplace.whmcs.com/product/13...-for-whmcs, but with fewer functions, as we don’t need everything that module offers).
Additionally, we are looking for a full-fledged order system, similar to WHMCS, that allows us to manage packages, server limits, and web hosting plans. It should include:

Subscription cycles.
Auto-creation of web hosting and domain orders (with domain API integration).
For reference, something along the lines of this module: https://codecanyon.net/item/purchase-man...BexQy94-xo, but tailored to our needs.

Do you think you can handle this project? If so, could you provide a rough estimate of the cost for a module like this?

PHP 8.3.13. This is a bug fix release.

$
0
0
PHP 8.3.13. This is a bug fix release.

How to match a model field with a database field?

$
0
0
I want the variables inside my model to automatically match the database fields. For example, when I write
Code:
public string $name;
, it should automatically correspond to the
Code:
name
field in the database. I want to avoid having to write
Code:
$name = "name"
. How can I achieve this, or does the model structure have support for such functionality?

11 Data Structures Every Developer Should Know

Restoring old Codeigniter 2 website. 404 errors.

$
0
0
Hi my website is http://www.interjo.in/ and it's running PHP5.6 and MariaDB10.4

The homepage works just fine but when I try clicking on internal links that hit their respective controllers, I get 404 errors. But not Codeigniter's 404 errors, but rather my host's.
The website should work fine because when I backed it up years ago, the website was functioning just fine.
What's the problem with my website? How can I fix it?
Thanks in advance! I miss the website and want to restore it so bad.

How to handle SecurityException #403 globally?

$
0
0
Hello folks,
When I restored browser pages from the last session, I noticed my CI4 app throwing "CodeIgniter\Security\Exceptions\SecurityException #403 The action you requested is not allowed." taking place at the url 'localhost:8080/login/magic-link'. I know this occurs when a csrf token expired, but I'm looking for a nicer way to output to the browser like showing a flash message or redirecting the user to the last form they were on.
How and where can one capture this in a try catch block to begin with?

Can a Nest Router be configured in "access point" mode?

$
0
0
Hi guys,
I have FTTH (fiber to the house) with the ONT inside my home, and my ISP-supplied router is connected to it. 
Iam thinking about getting a Nest router, but since the ISP router provides a VOIP phone line, I won't be replacing it. My plan is to connect the Nest router to the ISP router and turn off Wi-Fi on the ISP router.

Can the Nest router be configured in access point mode?

I also know you can add Google Wi-Fi points to the Nest system. If I have one Nest router and a few Wi-Fi points, can I set up a wired backhaul like you would with an all-Wi-Fi solution by connecting them all to a switch?
give me any suggestions if it is possible to you,
Thank you.

Vue not set the session on Codeigniter

$
0
0
Hi! I use CI 4.5.3 with Vue 3. I have Vue installed in localhost under http and CI on my server under https.
When i try to set a session for login from Vue something go wrong and the session is not setting correctly. The data of user are not in the session.
When i try to set session directly from CI all work perfectly.
I haven't errors from vue neither CI.
Any idea for help me?
My CI login:
PHP Code:
    public function login()
    {
        $request service('request');

        if ($request->isAJAX()) {

            $rules = [
                'email' => [
                    'label' => 'E-mail',
                    'rules' => 'required|max_length[254]|valid_email',
                ],
                'password' => [
                    'label' => 'Password',
                    'rules' => 'required',
                ],
            ];

            if (! $this->validate($rules)) {
                return $this->fail($this->validator->getErrors());
            }

            $model = new UserModel();
            $user $model->where('email'$this->request->getPost('email'))->first();

            if (!$user || !password_verify($this->request->getPost('password'), $user['password'])) {
                return $this->failUnauthorized('Invalid email and/or password.');
            }
            else {
                $session service('session');
                
                $sessionData 
= [
                    'id' => $user['id'],
                    'name' => $user['name'],
                    'surname' => $user['surname'],
                    'gender' => $user['gender'],
                    'email' => $user['email'],
                    'isLoggedIn' => TRUE
                
];

                log_message('debug''Initial session status: ' json_encode($session->get()));
                $session->set($sessionData);
                log_message('debug''Session status after set: ' json_encode($session->get()));

                if ($session->get('isLoggedIn')) {
                    return $this->respond([
                        'message' => 'Hi ' $user['name'], 
                        'success' => true,
                        'userdata' => [ 
                            'id' => $user['id'],
                            'name' => $user['name'],
                            'surname' => $user['surname'],
                            'gender' => $user['gender'],
                            'email' => $user['email'],
                        ]
                    ]);
                }
                else
                {
                    return $this->failUnauthorized('Session not setting');
                }
            }
        
        else 
        {
        return $this->failUnauthorized('Error AJAX.'); 
    }
 } 

[4.5.5] Strangeness with CSRF, sessions, AJAX

$
0
0
I'm using CI 4.5.5 and session based CSRF.

I have token randomization enabled, and token regeneration disabled.

I have set custom a custom token name, a custom header name, and I've set redirect to false.

For regular POSTs, it works as expected, except that when the CSRF validation fails, I simply get a 'false' return from the call


PHP Code:
if ( ! $this->request->is'post' ) ) {
  error_log'Not POST' );
  ..
  ..


I would have expected something else to happen, like a SecurityException being thrown.

For AJAX POSTs, it does not work as expected, so I guess I'm doing something wrong.

I'm passing the correct headers, but they seem to be stripped by something. I know they're passed with their correct value and correct (header) name, because I output them in other fields just to check, and in my global before filters, I have my class defined before csrf. But, I still get a 403 (after my class outputs all request headers in the PHP log file).

The AJAX call looks like this:


Code:
let response = await fetch( myURL, {
                    method: "POST",
                    headers:{
                        "Accept": "application/json",
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest",
                        "<?php echo  csrf_header(); ?>": "<?php echo csrf_hash(); ?>",
                        "ThisIsMyHeader": "ThisIsMyValue and '" + "<?php echo csrf_header(); ?>'"
                        "ThisIsMyHeader2": "ThisIsMyValue and '" + "<?php echo csrf_hash(); ?>'"
                    },
                    mode: "same-origin",
                    cache: "no-cache",
                    credentials: "same-origin",
                    body: JSON.stringify(filter_array),
                }
            );

           
The ThisIsMyHeader and ThisIsMyHeader2 values contain what I would expect according to my configuration.


Also, the hash is regenerated every time I re-load the page, even though I have disabled csrf token regeneration.

Interrupt transaction

$
0
0
hi is there a way to set $db->transStatus() to false forcing the transaction ?
i must control a record inside transaction and rollback if a culumn is not null .
Is it possible ?

Best way for two models in one controller?

$
0
0
Hi everyone,
My question is about following: I have two tables, products and products_description. First holds the general information like price and article number of the products, the description the textual description for each language, so 1:n (like 1 product can have many descriptions in different languages).
So I have controller "Products" and two models for each table.
When I like to query ALL product info in one call.... like general information plus description and details, what do I do best?
Viewing all 14082 articles
Browse latest View live


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