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

Why were security config settings in env template removed in recent versions?

$
0
0
Hi All,

Hope you are having a great day.

Been relying on the below parameters in the .env file for quite some time:


Code:
#--------------------------------------------------------------------
# SECURITY
#--------------------------------------------------------------------

security.csrfProtection = 'session'
security.tokenRandomize = true
security.tokenName = 'csrf_token'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie'
security.expires = 7200
security.regenerate = false
security.redirect = true
security.samesite = 'Lax'


Why were these and some others such as CSP and Honeypot settings removed? Is it a bad practice to manually add these to the .env file and that we should hard-code them in their appropriate config classes in app/Config ?

(can't seem to find anything in the docs with regards to changes in the .env file)

Keep on getting error about max_byte

$
0
0
Hi everyone and thanks in advance,
I'm working with CodeIgniter 4 and Shield, but every time I try to use max_byte
rule I get this error:
PHP Code:
CodeIgniter\Validation\Exceptions\ValidationException

"max_byte" is not a valid rule

This is happening on Login, where I'm using the config suggested in Shield
documentation:
PHP Code:
public $login = [
        'username' => [
            'label' => 'Auth.email',
            'rules' => [
                'required',
                'max_length[254]',
                'valid_email'
            ],
        ],
        'current-password' => [
            'label' => 'Auth.password',
                'rules' => [
                    'required',
                    'max_byte[72]',
                ],
            'errors' => [
                'max_byte' => 'Auth.errorPasswordTooLongBytes',
            ]
        ],
    ]; 
So I don't understand why it says that the rule is not valid.

Questions about csrf protection

$
0
0
working forward protecting my site, I enabled csrf protection and noted two effects, which I do not understand:
1) I use jquery autocomplete which calls a function which is not in the "except" list for csrf and the ajax call also do not pass any token. Still, the autocomplete works. Is this magic?
2) In trying to understand the effect under 1), I added the two methods PUT and GET to csrf in Filters.php:
Code:
public array $methods = [
        'GET'  => ['csrf'],
        'POST' => ['csrf'],
    ];
However, after doing this, the functions listed in the except list were blocked although they were not before. In my case it was the POST method. Taking it away from the $methods list, made everything return as before. Does the definition of the $method array overwrite the except list?
I can live with this two effects at the moment, since 1) I do not want to filter autocomplete and 2) I don't need the $methods array, but I'd like to know for the future...
Thank you btw for the good work! Everything works perfectly as soon as one understand how to use it.

Send errors sot stderr instead of stdout

$
0
0
Hi,


Is there a way to send PHP/CI4.5 generated errors to stderr instead of stdout ?

For eg, I have a crontab which sends an email only when it detects content on stderr : 

PHP Code:
*/10 * * * * root php myscript.php > /dev/null 


Here are some examples to illustrate the different scenarii:


PHP Code:
    public function test()
    {
        CLI::write("hello");
    

=> No mail sent => OK because written to stdout



    public function test()
PHP Code:
    {
        CLI::error("An error");
    }    
=> mail sent => OK because written to stderr

    public function test()
PHP Code:
    {
        $t 0;
    
=> no mail sent => Not ok because it generates a DivisionByZeroError to stdout instead of stderr

Thanks for your help,

Fred

Shield - Permission constraint?

$
0
0
Hi all,

currently my project is using a custom built authorization system. I am considering implementing Shield instead. However the way I need permissions is slightly different from Shield. I could summarize to say that I also need a constraint of some sort. Let me give an example.

Example permissions: child-basic:ch:r, child-sensitive:nh:w, ...

Permission structure:
  • name (child-basic)
  • constraint (ch) -- in this case the 'relation' attribute of a child entity
  • mode ® -- read, write, ...
Leaving out the constraint, I believe the Shield equivalent could be
child-basic.read, child-sensitive.write, etc...

I could, of course, generate a permission for every constraint like
child-basic.read-ch
or so, but my relation Ids are somewhat dynamic.

My ideal would be to be able to something like this:

PHP Code:
auth()->user()->addPermission('child-basic.read''ch');

if (
auth()->user()->can('child.basic.read'$child->relationId) { // .. 


What would be your suggestions for the best practice?

data in .ENV on risk? Security best practices

$
0
0
What is your opinion, how save are the data in our .ENV file?
What additional security measures do you use aside the CI4 standards?


Risky Biz News:

A threat actor is hacking and extorting companies that have misconfigured their cloud server infrastructure. The data extortion campaign has been taking place since earlier this year and involves a large-scale scan of the internet for companies that have exposed their environment variable files. Also known as .ENV, these files act as a centralized location for storing configuration data by multiple software solutions. Security firm Palo Alto Network says the attacker has been scanning the internet for ENV files, extracting login credentials, and accessing cloud servers. The attacker has allegedly scanned more than 230 million unique servers and successfully retrieved 90,000 environment variables—with around 7,000 of these being access keys associated with cloud services. PAN researchers say that in some cases, the attacker accessed cloud servers, exfiltrated data, deleted the original files, and then asked for a ransom to return the stolen documents.

https://unit42.paloaltonetworks.com/larg....risky.biz

Script working well at localhost but not remotely

$
0
0
Hi,
I'm french so please forgive me because I don't speak english fluently.

Here is my issue :
I am updating an application who works well on localhost. (I use XAMPP as development tool).
My application was first created at 2013 and it use CodeIgniter 2.1.4.
I have a domain named izte.fr.
I have ceated a sub-domain named gipel2024.
Now, I want to access my appli remotely. So I have sent all files omy app on my sub-domain, using FileZilla.
I have also created a MySQL database, and imported my local database.
I have updated the files in the folder config.
I have added a line to be able to display errors in my index.php file :
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
ini_set('display_errors', 1); // added
break;

When I want to display my app at https://gipel2024.izte.fr, I get this error :

Code:
Deprecated: Optional parameter $level declared before required parameter $message is implicitly treated as a required parameter in /home/qogi5174/gipel2024/system/core/Common.php on line 349

A PHP Error was encountered
Severity: Notice
Message: Only variable references should be returned by reference
Filename: core/Common.php
Line Number: 257

Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in /home/qogi5174/gipel2024/system/database/drivers/mysql/mysql_driver.php:91 Stack trace: #0 /home/qogi5174/gipel2024/system/database/DB_driver.php(115): CI_DB_mysql_driver->db_pconnect() #1 /home/qogi5174/gipel2024/system/database/DB.php(148): CI_DB_driver->initialize() #2 /home/qogi5174/gipel2024/system/core/Loader.php(346): DB() #3 /home/qogi5174/gipel2024/system/core/Loader.php(1171): CI_Loader->database() #4 /home/qogi5174/gipel2024/system/core/Loader.php(152): CI_Loader->_ci_autoloader() #5 /home/qogi5174/gipel2024/system/core/Controller.php(51): CI_Loader->initialize() #6 /home/qogi5174/gipel2024/application/controllers/home.php(7): CI_Controller->__construct() #7 /home/qogi5174/gipel2024/system/core/CodeIgniter.php(308): Home->__construct() #8 /home/qogi5174/gipel2024/index.php(92): require_once('/home/qogi5174/...') #9 {main} thrown in /home/qogi5174/gipel2024/system/database/drivers/mysql/mysql_driver.php on line 91

Is there somebody who can help me ?
Thanks in advanced
Kind egards

php spart displays ""%

$
0
0
Hi everyone,
I cloned a ci4 project in my new laptop but when i run
Code:
php spark
it displays in the terminal: 
Code:
""%
i already have run
Code:
composer install


please help

Validation Issue

$
0
0
Just got my project updated to CI 4.5.4, most of the issue solved by following guide and internet forum, but this I found by myself and currently tweak bit my code for compatibility with latest update:

Issue:
Validation field now will not accept number, even has been passed as string like (string)$myvariable , this will still raise an error.

Step to produce:
Just make database field name using only number e.g. field "111" or "222", make validation such as required/string/int/etc then it will raise an error when running validation.

Hope in the future this could be fixed because I use number as field number, adding prefix into code is somewhat challenging risk of bug.

Translate validation errors / messages based on locale

$
0
0
We are added language support in our program.

I have a mechanism that will set the locale to es / en.

Everything is dandy, until you get a validation error / message.

For example: Let's say i have an "I Agree" checkbox that is required to be checked upon form submission.

in my controller I have:

PHP Code:
$this->validate(['agree' => ['label' => 'I agree''rules' => 'required']]); 


And it will give me an error: "The I agree field is required." if the checkbox is left unchecked.

That's great if this were the 'en' version, but I get the same built-in language for the 'es' version.

Is there a way I can add language support for these built-in messages without having to type out every validation message for every field in other languages?

Thank in advanced.

Max

CURL Request Class - urlencode

$
0
0
Hi,
I working with a 3rd Party API and need to configure the URL as per the 3rd party spec.
PHP Code:
$my_row $client->get('/THIRDPARTY/?filter__Company%20Name__equal=my%20company%20(sports%20department) 

However, CURL Request Class encodes the url to:
Code:
GET /THIRDPARTY/?filter__Company_Name__equal=my+company+%28sports+department%29
Is there a way to instruct the CURL Request Class not to encode the url? 
I can't see anything obvious in the documentation and the only setting I can find in Config->CURLRequest is
PHP Code:
public $shareOptions true
Any help is appreciated

VUEJS3

$
0
0
How can we add vuejs3 with Codeigniter 4 step by step? I've been trying for a day. But no luck. There is always something that is not working anymore.

Those who use bonfire skelton

$
0
0
I tried implementing the module outside the app (root) but not work what is wrong???
PHP Code:
//this work
public $appModules = [
    
'Acme' => APPPATH .'Modules',
]; 
PHP Code:
//this does not work 
public $appModules = [
    
'Acme' => ROOTPATH .'Modules',
]; 

10 Game-Changing Web Development Tools to Supercharge Your Workflow in 2024

upload images on server side and save url in mysql database

$
0
0
for my codeigniter 3 view page i have a form submission to get new data to sql tale in phpmyadmin:


PHP Code:
<div class="container mt-5">
    <button class="btn btn-primary" data-toggle="modal" data-target="#directorModal">Add Director</button>

    <!-- Modal -->
    <div class="modal fade" id="directorModal" tabindex="-1" aria-labelledby="directorModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="directorModalLabel">Add Director</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                <form id="directorForm" method="get" enctype="multipart/form-data" action='<?=$user_base_url?>/profil/save_directors'>
                    <div class="form-group">
                        <label for="director_name">Director Name</label>
                        <input type="text" class="form-control" name="director_name" required>
                    </div>
                    <div class="form-group">
                        <label for="info">Info</label>
                        <textarea class="form-control" name="info" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="position">Position</label>
                        <input type="text" class="form-control" name="position" required>
                    </div>
                    <div class="form-group">
                        <label for="director_image">Director Image</label>
                        <input type="file" class="form-control" name="director_image" required>
                    </div>
                    
                    
<button type="submit" class="btn btn-primary">Save</button>
                </form>
                </div>
            </div>
        </div>
    </div>
</
div


here i try to get new user info to save in sql table as well their images in server. 
in controller i have following:


PHP Code:
public function save_directors() {
    $this->load->library('upload');
    $config['upload_path'] = './uploads/board_of_directors_images/';
    $config['allowed_types'] = 'gif|jpg|png|jpeg'// Adjust as needed
    $config['max_size'] = 2048// 2MB max size
    $config['encrypt_name'] = TRUE// Encrypt the file name
    $this->upload->initialize($config);
    if ($this->upload->do_upload('director_image')) {
        $upload_data $this->upload->data();
        $director_image $upload_data['file_name'];
    } else {
        $error $this->upload->display_errors();
        log_message('error''Image upload error: ' $error);
        $director_image NULL// Set to NULL or handle accordingly
    }
    $director_data = [
        'director_name' => $this->input->get('director_name'),
        'info' => $this->input->get('info'),
        'position' => $this->input->get('position'),
        'director_image' => $director_image
    
];
    $this->db->insert('board_of_directors'$director_data);
    if ($this->db->affected_rows() > 0) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error']);
    }


and ajax in view page:


PHP Code:
$(document).ready(function() {
    $('#directorsForm').on('submit', function(event) {
        event.preventDefault(); // Prevent the form from submitting the traditional way

        // Create a FormData object to hold the form data, including the file
        var formData = new FormData(this);
        $.ajax({
            url'<?=$user_base_url?>/profil/save_directors'// Adjust the URL according to your setup

            type'GET',
            dataformData,
            processDatafalse,  // Important! Prevent jQuery from automatically transforming the data into a query string
            contentTypefalse,  // Important! Prevent jQuery from overriding the content type
            dataType'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Director saved successfully!');
                    // Optionally, redirect or refresh the page
                } else {
                    alert('Failed to save director.');
                }
            },
            error: function(xhrstatuserror) {
                console.log('AJAX error:'error);
                alert('An error occurred while saving the director.');
            }
        });
    });
}); 



i fill the form and upload an image but i have recieved :

You did not select a file to upload.

any one can help how should i resolve that?

How to detect fake function with PHPStan

$
0
0
I'm using phpstan-codeigniter and it seems to work fine, except for the `fake' function, which is not recognized wherever I use it. It says "Function fake not found".

This is my phpstan.neon:

Code:
includes:
  - vendor/codeigniter/phpstan-codeigniter/extension.neon

parameters:
  level: 6
  paths:
    - app/
    - tests/
  bootstrapFiles:
    - vendor/codeigniter4/codeigniter4-phpstan/bootstrap.php
  excludePaths:
    - app/Views/*

How to make PHPStan detect the fake function?

Line Numbers for using SVG

Introducing Dev Encyclopedia: A "Wikipedia", but for developers

Tasks Library logPerformance

$
0
0
When I use Tasks library without making 
PHP Code:
$logPerformance=true
I can run any task without an issue. However when I list the tasks, "Last Run" column is always "--" dashed. After, I realized that it is because of logPerformance is not enabled. Therefore I made it true first ("settings" table is already exists). Again, when I run
PHP Code:
php spark tasks:list 
I face with this error in terminal:
Code:
Typed property CodeIgniter\Tasks\Task::$name must not be accessed before initialization
at VENDORPATH\codeigniter4\tasks\src\Task.php:187

Backtrace:
  1    VENDORPATH\codeigniter4\tasks\src\Commands\Lister.php:62
      CodeIgniter\Tasks\Task()->lastRun()

  2    SYSTEMPATH\CLI\Commands.php:65
      CodeIgniter\Tasks\Commands\Lister()->run([])

  3    SYSTEMPATH\CLI\Console.php:46
      CodeIgniter\CLI\Commands()->run('tasks:list', [])

  4    ROOTPATH\spark:102
      CodeIgniter\CLI\Console()->run()

strange redirects urlS

$
0
0
Hello!

Checking my SEO search console, I found strange urls without indexing, it should redirect to 404 or 301, but it redirects me with NS_ERROR_REDIRECT_LOOP and the search console warns me of the wrong redirect.

The urls are like "/index.phpproduct/R?3447087=uscrivesv", "/index.phpreview/item/list", "/index.phpconfig/login"," /index.phpproduct/S?2552902=znonpraedialy" and much others...

my CI4 htaccess
Code:
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

# REDIRECT HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# REDIRECT 301 WITHOUT WWW
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# REDIRECT 301 WITHOUT //
RewriteCond %{THE_REQUEST} //
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# REDIRECT 301 WITHOUT INDEX.PHP
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)$ [NC]
RewriteRule ^index\.php$ / [R=301,L]
RewriteCond %{THE_REQUEST} \s/index\.php [NC]
RewriteRule ^(.*)index\.php/(.*)$ https://%{HTTP_HOST}/$1$2 [R=301,L]
Viewing all 14343 articles
Browse latest View live


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