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

Running session GC from CLI

$
0
0
Hello is there a better way to clean up sessions from CLI than the following example?


PHP Code:
public function clear_sessions():void{
    $this->session = \Config\Services::session();
    $rf = new ReflectionProperty($this->session'driver');
    $rf->setAccessible(true);
    $rf->getValue($this->session)->gc(env('app.sessionExpiration'));
    
C::print('Sessions Cleared');
    
C::newLine();


Find Bug in CI4

$
0
0
 hi i m huge fan ci4 
i was facing issue which pin  in ass but  solve it Smile 

i  figure out which CI4 can not validate Ajax request (JSON  Raw Input) with Postman or Angular 9 

i was customizing Math/Auth for RestFull  API JWT Authentication
 i got error which can not validate Raw Input JSON     
heres part of  code  auth controoler  

 
Code:
if ($this->request->isAJAX()) {


            /**
            * Attempts to verify the user's credentials
            * through a POST request.
            */
            $rules = [
                'login' => 'required',
                'password' => 'required',
            ];

            $config = config('Myth\Auth\Config\Auth');


            if ($config->validFields == ['email']) {
                $rules['login'] .= '|valid_email';
            };


 i connot validate And Got Error I dont send login and password   



Code:
            if (!$this->validate($rules)) {

                $responseDataModel->setToken('');
                $responseDataModel->setData($this->validator->getErrors());
                $responseDataModel->setMessage('error during login validate ');
                $responseDataModel->setSuccess(false);
                return $this->response->setJSON($responseDataModel->getRowData())->setStatusCode(400)->setContentType('application/json');
            }


          }



i  go to    validation class CI4  then function 

withRequest() 
Code:
public function withRequest(RequestInterface $request): ValidationInterface
{
    if (in_array($request->getMethod(), ['put', 'patch', 'delete'])) {
        $this->data = $request->getRawInput();
    }  else {
        $this->data = $request->getVar() ?? [];
    }


    return $this;
}


add this line  to code and fix bug easily Smile

Code:
public function withRequest(RequestInterface $request): ValidationInterface
{
    if (in_array($request->getMethod(), ['put', 'patch', 'delete'])) {
        $this->data = $request->getRawInput();
    } else if ($request->isAJAX()) {

        $this->data = $request->getJSON(true);

    } else {
        $this->data = $request->getVar() ?? [];
    }


    return $this;
}



i hope next version ci4 add this line to code 

thanks to great team ci4  

Codeigniter not showing helpful error messgaes

$
0
0
Codeigniter normally used to show helpful error messages but for some unknown reasons, all it shows is

    Uncaught ErrorException: htmlspecialchars() expects parameter 1 to be string, resource given in C:\xampp\htdocs\app\Views\errors\html\error_exception.php:182 Stack trace: #0 [internal function]: CodeIgniter\Debug\Exceptions->errorHandler(2, 'htmlspecialchar...', 'C:\\xampp\\htdocs...', 182, Array) #1 C:\xampp\htdocs\app\Views\errors\html\error_exception.php(182): htmlspecialchars(Resource id #23, 8, 'UTF-8') #2 C:\xampp\htdocs\system\Debug\Exceptions.php(299): include('C:\\xampp\\htdocs...') #3 C:\xampp\htdocs\system\Debug\Exceptions.php(172): CodeIgniter\Debug\Exceptions->render(Object(ParseError), 500) #4 [internal function]: CodeIgniter\Debug\Exceptions->exceptionHandler(Object(ParseError)) #5 {main} thrown

I have NO idea what is going on.Whether it is a parse error, synat error etc, that is all it ever shows now.Please help

Ps: this happened after installing some composer pacakages

Struggling with transaction using multiple models

$
0
0
I'm struggling with how to get transactions to work when saving with multiple models.  I am developing a Property Management application.  When a single tenant property is created, the data for the property as well as a default unit is saved to the database.  Here is my code:

PHP Code:
$property_model = new PropertyModel;
$unit_model = new UnitModel;

$property_model->transStart();

$property_save = $property_model->save($property);
$unit_save = $unit_model->save($unit);

$property_model->transComplete(); 

if(!$property_save || !$unit_save) {
   //Handle validation errors
} elseif($property_model->transStatus() !== TRUE) {             
   
//Handle failed transaction
} else {
   
//Success action


When I force $unit_model->save($unit) to fail, the $property-model->save($property) is still inserted into the database.  I know I am probably using transactions incorrectly with my models, but I am not experienced enough with CodeIgniter 4 to know what I am doing wrong.

Call to undefined method VI_Loader::_ci_load_class()

$
0
0
I am try to update a site from CodeIgnitor 2.2.2 to 3.1.6

I am getting

A PHP Error was encountered
Severity: Warning
Message: Declaration of MX_Loader::helper($helper) should be compatible with CI_Loader::helper($helpers = Array)
Filename: MX/Loader.php
Line Number: 389
A PHP Error was encountered
Severity: Warning
Message: Declaration of MX_Loader::helpers($helpers) should be compatible with CI_Loader::helpers($helpers = Array)
Filename: MX/Loader.php
Line Number: 0
A PHP Error was encountered
Severity: Warning
Message: Declaration of MX_Loader::_ci_get_component($component) should be compatible with & CI_Loader::_ci_get_component($component)
Filename: MX/Loader.php
Line Number: 0
A PHP Error was encountered
Severity: Notice
Message: Only variables should be assigned by reference
Filename: core/Loader.php
Line Number: 784
A PHP Error was encountered
Severity: Notice
Message: Only variables should be passed by reference
Filename: MX/Loader.php
Line Number: 135
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method VI_Loader::_ci_load_class()
Filename: /home/zqnoinxl/cherylibarra.burtonconstruction.net/application/libraries/MX/Loader.php
Line Number: 152

Line 152 is

$this->_ci_load_class($library, $params, $object_name);

VI_Loader is under the core library

cand start with

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

/* load the MX_Loader class */
require APPPATH."libraries/MX/Loader.php";

class VI_Loader extends MX_Loader {

Why can't it find it? Any ideas please

Best regards

First steps of newbie in CI.

$
0
0
Hello,
I'm just starting to know CI. I need to make a little application for Registration of some users. This users have the posibility of referred new prospects. I need to link that 2 tables. And I want to approach the best of a genial tool like Codeigniter. 
I'm not sure if I can link that 2 tables in the model and if that take me away of the original schema that CI offer to us and miss advantages there.
I like the structure of CI and from the start I want learn to use in the right way.

Sorry for this super basic question, thanks in advance,

JP

All First Tries with CI4 Failing

$
0
0
I have been using Codeigniter for years and wanted to upgrade to CI4 on the assumption it will represent an upgrade in performance. 

 I refuse to have the application in the public web directory for security reasons. This was always easy to accomplish with CI3, but I cannot get it to work with CI4 despite editing all the files I could find with paths.

 CI4 appears to have dependencies and hard coded ideas about the location of applications such as PEAR. I am very reluctant to install additional software on the server because I have zero trust in their security. Hence, the server functions with the minimum necessary and the maximum possible number of programs disabled.

 I am really unsure how to proceed, other than sticking with CI3. Recoding applications for a new system is not an issue for me. But, out of the box functionality like we have in CI3 is.

Ion Auth Forgot Password email


Need help for complex query

$
0
0
I have a product table, category table and another table to join product and category where category stored in JSON format. What I need to do is to get all the product with a list category IDs.

Category table

Code:
-----------------------
| id | category_name
-----------------------

Product table

Code:
-----------------------
| id | product_title
-----------------------

Product Category relation table

Code:
-----------------------
| product_id | categories [varchar(100) but data stored in JSON format]
-----------------------
| 1          | [1,4,6]
-----------------------
| 2          | [34,8,9]
-----------------------
| 2          | [27,18,29]

According to example, what will be the query if I need to get all the product with the category list (array)[34,18,6]

I will be very glad if you suggest any better table structures. Thanks in advance.  Shy

required_with Validation Rule works on inserts but not updates

$
0
0
I have a form where a select menu is disabled by default.  It's enabled when a when a checkbox is checked and disabled when the checkbox is uncheck using a bit of javascript.  I would like this select menu to be required only when the box is checked  The required_with validation rule is perfect for this and it works great on inserts.  However, it does not work on updates.  It's like the required_with rule somehow vanished with the update query.  The validation is taking place in the model before insert and update queries.  Both insert and update controller methods use the same view, so the HTML form is essentially the same.  I inspected the POST data when both inserting and updating and it is exactly the same.  The only difference is whether the data is being inserted or updated in the database.  Am I doing something wrong?  Is this a bug?

Found a Bug with the "set_radio()" function

$
0
0
There is a strange bug with the set_radio() function.  I have two sets of radio bullets.  Lets call them $set1 and $set2.  Each set is made up of two radio bullets where the value is either 1 for "yes" or 0 for "no". 

If the form initially loads with no radio bullets marked as checked set_radio() works just fine.  If validation fails, the form remembers if "yes" or "no" is checked for $set1 and $set2. If the values are changed to from "yes" to "no" or vice-versa, it works even after multiple forced validation failures and multiple radio bullet selections.

The sames follows if the form initially loads with the "yes" radio bullets marked as checked.  Each set remembers the POST value after validation fails when the form reloads. If the values are changed to from "yes" to "no", it works. If the values are changed back to "yes" from "no" after a validation failures, it works.

This is where it gets weird.  If the form initially loads with the "no" radio bullets already marked as checked, set_radio() no longer works correctly.  The set value always defaults to "no". If the values are changed from "no" to "yes" and a validation error occurs when the form is submitted, the radio bullets flip back to "no" when the form view loads after the validation failure.  set_radio() always gets a value of 0 when 0 is the initial checked value.

No, I did not use the optional third parameter to set a default value.

I've included some code from my view.  Please let me know if I am missing something.

Code:
            <div class="form-row">
                <div class="form-group col-6">
                    <legend class="col-form-label pt-0" style="font-weight: 600;">HVAC Installed:</legend>
                    <div class="form-check form-check-inline">
                    <?php
                        $attributes = [
                            'name' => 'hvac',
                            'id' => 'hvac_yes',
                            'class' => 'form-check-input' . is_invalid($errors['hvac']),
                            //'required' => 'required',
                        ];
                        echo form_radio($attributes, '1', ($unit->hvac == '1' ? TRUE : FALSE), set_radio('hvac', '1'));
                        $attributes = [
                            'class' => 'form-check-label',
                        ];
                        echo form_label('Yes', 'hvac', $attributes);
                    ?>
                    </div>
                    <div class="form-check form-check-inline">
                    <?php
                        $attributes = [
                            'name' => 'hvac',
                            'id' => 'hvac_no',
                            'class' => 'form-check-input' . is_invalid($errors['hvac']),
                            //'required' => 'required',
                        ];
                        echo form_radio($attributes, '0', ($unit->hvac == '0' ? TRUE : FALSE), set_radio('hvac', '0'));
                        $attributes = [
                            'class' => 'form-check-label',
                        ];
                        echo form_label('No', 'hvac', $attributes);
                    ?>
                    </div>
                    <?= invalid_feedback($errors['hvac']) ?>
                </div>
                <div class="form-group col-6">
                    <legend class="col-form-label pt-0" style="font-weight: 600;">3ϕ Power Installed:</legend>
                    <div class="form-check form-check-inline">
                    <?php
                        $attributes = [
                            'name' => 'three_phase',
                            'id' => 'three_phase_yes',
                            'class' => 'form-check-input' . is_invalid($errors['three_phase']),
                            //'required' => 'required',
                        ];
                        echo form_radio($attributes, '1', ($unit->three_phase == '1' ? TRUE : FALSE), set_radio('three_phase', '1'));
                        $attributes = [
                            'class' => 'form-check-label',
                        ];
                        echo form_label('Yes', 'three_phase', $attributes);
                    ?>
                    </div>
                    <div class="form-check form-check-inline">
                    <?php
                        $attributes = [
                            'name' => 'three_phase',
                            'id' => 'three_phase_no',
                            'class' => 'form-check-input' . is_invalid($errors['three_phase']),
                            //'required' => 'required',
                        ];
                        echo form_radio($attributes, '0', ($unit->three_phase == '0' ? TRUE : FALSE), set_radio('three_phase', '0'));
                        $attributes = [
                            'class' => 'form-check-label',
                        ];
                        echo form_label('No', 'three_phase', $attributes);
                    ?>
                    </div>
                    <?= invalid_feedback($errors['three_phase']) ?>
                </div>
            </div>

I guess this has already been reported. I just found this on GitHub via Google: https://github.com/codeigniter4/CodeIgni...ssues/2728.  It says this has been fixed, but I'm using 4.0.4 and still having the same issue.

Extending Autoloader

$
0
0
Hello,

I made make to CodeIgniter\Autoloader\Autoloader extends.

Normally services extends after errors;
Fatal error: Uncaught Error: Class 'App\CoreExtends\Autoloader' not found
Code:
# Time Memory Function Location
1 0.0000 416496 {main}( ) .../rewrite.php:0
2 0.0001 419648 require_once( '/home/user/public_html/dev/public/index.php' ) .../rewrite.php:26
3 0.0002 420928 require( '/home/user/public_html/dev/core/bootstrap.php' ) .../index.php:115
4 0.0019 441952 Config\Services::autoloader( ) .../bootstrap.php:137

App\Config\Services;

PHP Code:
public static function autoloader(bool $getShared true)
{
    if (
$getShared)
    {
        if (empty(static::
$instances['autoloader']))
        {
            static::
$instances['autoloader'] = new \App\CoreExtends\Autoloader();
        }

        return static::
$instances['autoloader'];
    }

    return new \
App\CoreExtends\Autoloader();


\App\CoreExtends\Autoloader;
PHP Code:
<?php namespace App\CoreExtends;

class 
Autoloader extends \CodeIgniter\Autoloader\Autoloader
{



The purpose for me to do this process.
I need composerFile autoload like Composer.
Sample;

Composer.json
Code:
"autoload": {
    "psr-4": {"MyClass \\": "src /"},
    "files": ["src / functions.php"]
},

route filters does not work

$
0
0
Hi, i'm using CI 4.0.4 for my project, i'm working on permission check with routes and filter in it, but it seem to be not woking right. My code look like this:
- In App/Filter i declare an filter alias

[Image: ci-error.png]

- in my Acp module i have 2 routes group like this

[Image: ci-error-1.png]


- and this is my filter class, i'm also print out and exit the code to test

[Image: ci-error-2.png]

- the problem was, the router just call the fillter class once, it only go to the filter class if i visit the permission route group. it run ok like this

[Image: ci-error-3.png]

- and it not working when i'm going to the second route url

[Image: ci-error-4.png]

does any one have the same problem? Can anyone help me with this please

is currently unable to handle this request. HTTP ERROR 500

$
0
0
institutionmixtelesgedeons.000webhostapp.com is currently unable to handle this request.

[color=var(--error-code-color)]HTTP ERROR 500[/color]

[color=var(--error-code-color)]help me please[/color]

Not Passing encoded variable % to Controller

$
0
0
I have to encode urls linking to my invoice pages.

on All invoice page:

Code:
<?php $pdfurl = urlencode(base64_encode($this->encrypt->encode($list->order_id)));
?>
                                                        
<a href="<?php echo base_url('pdf/'.$pdfurl);?>">Pdf2</a></td>
this encodes the url  
www.website.com/pdf/13
to www.website.com/pdf/Z1FSMmNkcG9NWHNrc2V3MzZvY2grY0pzQUVtSEZRYTFrMmU0RTMreWFNa3MzS29tdXhJRzJBUnQwNGJhR1lwcEZLdjUvTTlLbnJ0YmNSQ2Q2RTlyekE9PQ%3D%3D

My controller code is:
in controller when $pdfurl is called it carries Z1FSMmNkcG9NWHNrc2V3MzZvY2grY0pzQUVtSEZRYTFrMmU0RTMreWFNa3MzS29tdXhJRzJBUnQwNGJhR1lwcEZLdjUvTTlLbnJ0YmNSQ2Q2RTlyekE9PQ==
It drops %3D%3D and appends == at the end.

This doesnot decodes to the original variable value which is 13.

instead it decodes to : 
gQR2cdpoMXsksew36och+cJsAEmHFQa1k2e4E3+yaMks3KomuxIG2ARt04baGYppFKv5/M9KnrtbcRCd6E9rzA==

Pls help, i am doing this for first time.
Code:
function pdf($pdfurl){
    $this->load->library('pdf');
    $this->load->library('encrypt');

       $order_id = base64_decode(rawurldecode($pdfurl));
 

      $data = $this->common_data_admin();
        
        $data['order_id'] = $pdfurl;
        $data['order_details'] = $this->common_model->get_order_details($order_id);        

      $this->pdf->load_view('mypdf', $data);

My Config file has:

Code:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-@\=';

Route file:
Code:
$route['pdf/(:any)'] = 'Afterlogin_admin/pdf/$1';

ORDER BY ON SQLite3

$
0
0
When using database SQLite3 and using order by, the query builders produce

SELECT * FROM TABLE ORDER BY RAND();

It must be,

SELECT * FROM TABLE ORDER BY RANDOM();

Best practice for date in entity

$
0
0
hello

in a form i have a date in format 'dd/mm/yyyy'

i use entity and i want save the date in sql with model

i do in my model
Code:
$myEntity = new TheEntity($data);
        if ($this->save($myEntity))

this send me an error

DateTime::__construct(): Failed to parse time string (19/03/2016) at position 0 (1): Unexpected character


i have create a setter in my entity
Code:
protected $dates = ['date_naissance'];
   
    public function setDateNaissance($date)
    {
        if (empty($date)) {
            $this->attributes['date_naissance'] = null;
            return $this;
        }else{
            $this->attributes['date_naissance'] = date('Y-m-d', strtotime(str_replace('/', '-', $date)));
            return $this;
        }
    }
but the setter isn't call before the error

You must use the "set" method to update an entry. (Again)

$
0
0
Hello everyone,

I'm currently migrating my CI3 project to CI4, but unfortunately I'm struggling with I guess one of the easier things Sad . I already searched the forums and tried some things, but couldn't find a fitting solution. I think my main problem is that the error doesn't really tell me what's wrong and I have no clue what could bring me a step closer to the solution at this point.

In general I only want to create a user in my user model.

This is my Controller Test Case
PHP Code:
public function CreateUserTest()
    {
        
$userModel = new UserModel();
        
$returnValue $userModel->create_user('MrXXX''12345678''Max''Muster''x.y@nothing.com');
    } 

This is my UserModel declaration and definitions
PHP Code:
protected $DBGroup 'users';
protected 
$table 'user';
protected 
$allowedFields = ['role_id, first_name, last_name, username, password, '
    
'email_address, mail_me, ack_round, language, referee, xp, uuid, '
    
'activation_token, activation, dsgvo, notified']; 

This is my insert statement inside the createuser method
PHP Code:
$this->set('uuid''UUID()'false);
    
//$this->set('referee', $referee);   
    
$data = ['username' => $username,
            
'first_name' => $first_name,
            
'last_name' => $last_name,
            
'email_address' => $email_address,
            
'password' => $hash,            
            
'activation_token' => $token];
    
var_dump($data);
    
$insert $this->insert($data); 

The result from var_dump looks like this:
Code:
array(6) { ["username"]=> string(5) "MrXXX" ["first_name"]=> string(3) "Max" ["last_name"]=> string(6) "Muster" ["email_address"]=> string(15) "x.y@nothing.com" ["password"]=> string(60) "CleandUpCleandUp..." ["activation_token"]=> string(254) "CleandUpCleandUp..." }

Thx for your help!

Route with http verb

$
0
0
Hi,
This may have been answered, but as the forum search is not working I need to ask.

I am trying to redirect to a page with parameters, but not sure how to configure the redirect, the route or even if the route is necessary.

Essentially I am trying to replicate the following http://mydomain/mypage/mymethod?weekending='something' in the redirect, i.e.

PHP Code:
return redirect()->route('named_route/weekending/25-10-2020'); 


And assuming my route would look something like
PHP Code:
$routes->post('named_route/varName/varValue''myPage::myMethod/parameters'); 

which would interact with my controller
PHP Code:
class myPage extends BaseController {
    
    public function 
index() {
    
         
//This does something
    }

    
    public function 
myMethod() {
    
        if(
$this->request->getGetPost('weekending')) {
            
            
//this does something else    
            
            
}else{
            return redirect()->route('404');
            }
    }

Ci4 problem on newly instal vps

$
0
0
Hello any one can help me I just install a vps and install a plesk cpanel.

My ci4 project is too big that I need a vps for it

Every process went well until I upload my project and I am stuck at error.

500 internal server error.

Error log says
.htacess Option All is not allow here.

I did no know much about command line I have already tries every solution I found on internet.

I comment out all options in .htaccess in the public folder it works but can not locate pages..

Url not found.

When I uncommitted them I get back my 500 error 
Option All not allow here.
Viewing all 14353 articles
Browse latest View live