Welcome Guest, Not a member yet? Register   Sign In
  Implementing mail send on errors
Posted by: adrianovaroli - 04-11-2024, 12:22 PM - Replies (1)

We have a web application used by several clients, and it would be useful if, upon specific errors happening in production environments (I was thinking errors of type critical, alert o emergency, if possible), the system would send us developers a quick email to let us know, and also retain the current behavior of showing an error page. I started by trying a custom exception exception handler (app/Libraries/CustomExceptionHandler.php)

PHP Code:
<?php

namespace App\Libraries;

use 
CodeIgniter\Debug\BaseExceptionHandler;
use 
CodeIgniter\Debug\ExceptionHandlerInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Throwable;

/**
* Extends BaseExceptionHandler to send mail in case of serious app errors
* @package App\Libraries
*/
class CustomExceptionHandler extends BaseExceptionHandler implements ExceptionHandlerInterface
{
    public ?string $viewPath APPPATH 'Views/errors';

    public function handle(
        Throwable $exception,
        RequestInterface $request,
        ResponseInterface $response,
        int $statusCode,
        int $exitCode
    
): void {
        log_message('error'"handling an exception of statusCode $statusCode. ".$exception->getMessage());
        // TODO actually implement sending an email.
        
        $this
->render($exception$statusCode);

        exit($exitCode);
    }



and I configured app/Config/Exceptions.php like
PHP Code:
public function handler(int $statusCodeThrowable $exception): ExceptionHandlerInterface
    
{
        if (in_array($statusCode, [400404500], true)) {
            return new \App\Libraries\CustomExceptionHandler($this);
        }

        if ($exception instanceof PageNotFoundException) {
            return new \App\Libraries\CustomExceptionHandler($this);
        }

        return new ExceptionHandler($this);
    }


With, thus far, just an extra log_message or two to see that it was working. It does work, but what I see in the browser is not the normal exception trace for development or the error page for production, but an error "The error view files were not found. Cannot render exception trace."
What am I missing? I tried leaving $viewPath as null or removing it from my custom class, but the error message about view files remains.
Then I also read that I could add a custom Logger to send mail in the cases I need. What would be the best thing to do in my case?
Best regards,


  Session issues
Posted by: marcosandrade22 - 04-11-2024, 11:00 AM - Replies (3)

Estou iniciando um projeto no CI4 e estou encontrando alguns problemas relacionados à sessão.
1 - Não consigo levar os dados da sessão para outro controlador, exemplo:
Controlador 1
  session()->set('EmailUser', 'email@user.com');
var_dump(sessão()->get());
Devoluções
array(2) { ["__ci_last_regenerate"]=> int(1712858169) ["UserEmail"]=> string(15) "[email protected]" }

Controlador 2
var_dump(sessão()->get());
retornar
array(1) { ["__ci_last_regenerate"]=> int(1712858209) }

2 - Tentei configurar o banco de dados conforme a documentação, pois estou acostumado a fazer isso com o CI3, mas as sessões não ficam salvas no banco de dados.

Estou usando MAMP no MAC Sonoma e php 8.2


  Codeigniter 4 debug bar header link "disappeared" - color won't change
Posted by: xanabobana - 04-11-2024, 09:34 AM - Replies (3)

I am working on migrating my website from CI3 to CI4. The CI4 debug bar seems like it's having a conflict with CSS somewhere but I can't figure it out. 
Here is the example CI4 page: https://dev.vmc.w3.uvm.edu/xana/CI4/ 
If you click on the Codeigniter flame on the bottom right it pulls up the debug bar. However, the menu items are not visible and the close button on the right is stretched out.
I tried updating the CSS to see if that would change the link color, but it did not.  So I'm not sure what is going on?

Code:
#debug-bar .ci-label a {
  color: inherit; //changed this to #000; but it didn't change the color
  display: flex;
  letter-spacing: normal;
  padding: 0 10px;
  text-decoration: none;
  align-items: center;
}

Any ideas on getting the toolbar showing correctly?

Thanks!


  Undefined variable: request;
Posted by: lucasdemarco - 04-11-2024, 07:25 AM - Replies (5)

I recently migrated from CI 3 to 4 and I'm having a problem displaying $_POST values in my view. I have a filter in my view "listar.php" and when the form is sent the same view is loaded with new information based on the filter, but I cannot print the filter value when the page is loaded.
From what I noticed in CI 4 it is necessary to use
"echo $request->getGet('search');" to print the value sent by the form, but the problem happens because I'm not loading "Config\Services::request()", if I put " $request = \Config\Services::request(); " at the beginning of my view the error "Undefined variable: request" disappears, but it is very exhausting to always have to put this line in all views, I would like to know if anyone has a suggestion on how to always leave Request() loaded in all views by default, I would appreciate it.

Note: I haven't created the logic behind the filter yet, for now I just want to display what was sent in the filter itself
My controller: 


PHP Code:
namespace App\Controllers;
use 
App\Models\Modulo;

class 
Modulos extends My_Controller
{
    public function Getlistar()
    {
        $obj = new Modulo();
        $data['objetos'] = $obj->find();

        return view('estrutura/menu')
            view($this->controllerName.'/listar'$data)
            view('estrutura/rodape');
    }


Input I want to print the value: 
PHP Code:
<input type="text" name="busca" id="busca" value="<?php echo $request->getGet('busca'); ?>" class="form-control"


  Replace very large jS if/elseif/else to show/hide many divs?
Posted by: Madelineknight - 04-11-2024, 07:12 AM - No Replies

Hi Forum,

I've got a page that has a portion of it that displays, or hides, DIV's depending on what option was selected.

There will be around 25 different div's when done, and while developing this I realize that the JS if/else is going to be quite verbose.

For example:

vehicleYearSelect.addEventListener('change', function() {
    if (this.value === '1960') {
        vehicleYear_1960.style.display = 'flex';
        vehicleYear_1961.style.display = 'none';
        vehicleYear_1962.style.display = 'none';
        vehicleYear_1963.style.display = 'none';
        vehicleYear_1964.style.display = 'none';
        vehicleYear_1965.style.display = 'none';
        ...
        [many more years here]
    } else if (this.value === '1961') {
        vehicleYear_1960.style.display = 'none';
        vehicleYear_1961.style.display = 'flex';
        vehicleYear_1962.style.display = 'none';
        vehicleYear_1963.style.display = 'none';
        vehicleYear_1964.style.display = 'none';
        vehicleYear_1965.style.display = 'none';
                ...
        [many more years here]
    } else if (this.value === '1962') {
        vehicleYear_1960.style.display = 'none';
        vehicleYear_1961.style.display = 'none';
        vehicleYear_1962.style.display = 'flex';
        vehicleYear_1963.style.display = 'none';
        vehicleYear_1964.style.display = 'none';
        vehicleYear_1965.style.display = 'none';
                ...
        [many more years here]
    } else if (this.value === '1963') {
        vehicleYear_1960.style.display = 'none';
        vehicleYear_1961.style.display = 'none';
        vehicleYear_1962.style.display = 'none';
        vehicleYear_1963.style.display = 'flex';
        vehicleYear_1964.style.display = 'none';
        vehicleYear_1965.style.display = 'none';
                ...
        [many more years here]
    } else if (this.value === '1964') {
        vehicleYear_1960.style.display = 'none';
        vehicleYear_1961.style.display = 'none';
        vehicleYear_1962.style.display = 'none';
        vehicleYear_1963.style.display = 'none';
        vehicleYear_1964.style.display = 'flex';
        vehicleYear_1965.style.display = 'none';
                ...
        [many more years here]
    } else {
        vehicleYear_1960.style.display = 'none';
        vehicleYear_1961.style.display = 'none';
        vehicleYear_1962.style.display = 'none';
        vehicleYear_1963.style.display = 'none';
        vehicleYear_1964.style.display = 'none';
        vehicleYear_1965.style.display = 'none';
                ...
        [many more years here]
    }
});


Is there a way to make this more "efficient" in terms of maintainability and having to add new options selected to it?

Example, if I need to add else if (this.value === '1965') and else if (this.value === '1966') to this, I'll need to not only add two more else if's, but also add both of the respective tyle.display = 'none'; or tyle.display = 'flex'; to each of the other existing conditions. etc....

There wont' be very many people using this form as it's not public facing, so speed is not a huge concern here.

Just looking for a way to improve this.


  Pass custom variables to Shield custom layout
Posted by: Fred9176 - 04-11-2024, 03:11 AM - Replies (2)

Hi,

I'm trying to integrate Shield into my custom layout.

I copied the login.php view into app/Views/Shield and setup my layout in app/Config/Auth.php

My custom layout takes some custom variables as, for example, the title of the page.

PHP Code:
$view_data = [];
$view_data['pageTitle'] = 'My page title;
$view_data['
pageSubtitle'] = 'Page subtitle';

return view('
Modules\MyModule\Views\myview', $view_data); 

How can I pass these variables in the login View ?

Thanks for your help,

Fred


  Some data is not updating
Posted by: karimm - 04-11-2024, 01:50 AM - Replies (2)

Hi,
I'm on version 4.4.5 of Codeigniter and I have a problem with database fields being ignored with the save() function for Models. So with save(), the insert is done very well and the update too except for two fields "modifiedOn (datetime)" and 'modifiedBy (int) which do not fill up when I update the data. 
Here is my model

PHP Code:
namespace App\Models;

use 
CodeIgniter\Model;

class 
Tender_model extends Model
{
    protected $DBGroup          'default';
    protected $table            'tenders';
    protected $primaryKey      'id';
    protected $useAutoIncrement true;
    protected $insertID        0;
    protected $returnType      'array';
    protected $useSoftDeletes  true;
    protected $protectFields    true;
    protected $allowedFields    = ['id''title''typeId''serviceId''summaryMarket''isPublicMarket''estimatedDuration''estimatedAmount''executionPeriodFrom''executionPeriodTo''publicationDate''deliveryTenderDate''summaryExpectationsProviders''modalitySubmission''modifiedOn''modifiedBy''deletedOn''deletedBy''wp_id''owner''createdBy'];

    // Dates
    protected $useTimestamps false;
    protected $dateFormat    'datetime';
    protected $createdField  'createdOn';
    protected $updatedField  'modifiedOn';
    protected $deletedField  'deletedOn';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages  = [];
    protected $skipValidation      false;
    protected $cleanValidationRules true;

    // Callbacks
    protected $allowCallbacks true;
    protected $beforeInsert  = [];
    protected $afterInsert    = [];
    protected $beforeUpdate  = [];
    protected $afterUpdate    = [];
    protected $beforeFind    = [];
    protected $afterFind      = [];
    protected $beforeDelete  = [];
    protected $afterDelete    = [];

Here is my controller, the useful functions
PHP Code:
public function create()
    {
        //print_r($this->request->getPost()); // check file PDF only
        if($this->request->getPost()){
            
            
if (!empty($this->request->getPost('tenderId'))) {
                $primaryKey 'id';
                $data['id'] = $this->request->getPost('tenderId');
                $data['modifiedBy'] = session('user')['peopleId'];
                $data['modifiedOn'] = date('Y-m-d H:i:s');
                if(! empty($this->request->getPost('contactPeopleId')))
                    $data['owner'] = $this->request->getPost('contactPeopleId');
            } else {
                $data['createdBy'] = session('user')['peopleId'];
                //$data['owner'] = (empty($this->request->getPost('contactPeopleId'))) ? $data['createdBy'] : $this->request->getPost('contactPeopleId');
            }
            $data['title'] = $this->request->getPost('title');
            $data['summaryMarket'] = $this->request->getPost('summaryMarket');
            $data['isPublicMarket'] = $this->request->getPost('isPublicMarket');
            $data['executionPeriodFrom'] = $this->request->getPost('executionPeriodFrom');
            $data['executionPeriodTo'] = $this->request->getPost('executionPeriodTo');
            $data['publicationDate'] = $this->request->getPost('publicationDate');
            $data['estimatedDuration'] = $this->request->getPost('estimatedDuration');
            $data['estimatedAmount'] = $this->request->getPost('estimatedAmount');
            $data['deliveryTenderDate'] = $this->request->getPost('deliveryTenderDate');
            $data['modalitySubmission'] = $this->request->getPost('depositMethod');
            $data['serviceId'] = $this->request->getPost('serviceId');
            $data['typeId'] = $this->request->getPost('typeId');
            $data['countryId'] = $this->request->getPost('countryId');
            $data['wp_id'] = (! empty($this->request->getPost('wp_id'))) ? $this->request->getPost('wp_id') : null;
        }
print_r($data);
 
$this->model->save($data);

the print_r of $data
PHP Code:
Array ( [id] => 587 [modifiedBy] => 8403 [modifiedOn] => 2024-04-09 20:35:11 [title] => Mission de consultance sur les consortiums/fusions [summaryMarket] =>

La mission de consultance a pour objectif de réaliser un état des lieux et d’accompagner ACODEV et ses membres afin de mieux comprendre les intentions du secteur et d’identifier les conditions et méthodes pour les appuyer dans d’éventuels processus de mise en place de consortium et/ou de mise en commun de services et/ou de fusions.Partie A 1. Disposer d’une revue documentaire de la question 2. Disposer d’un état des lieux approfondi des intentions des membres d’ACODEV concernant la mise en place de consortiums et de fusions d’organisations 3. Animer un débat et/ou des travaux de groupes soit lors de l’assemblée générale d’ACODEV (juinsoit lors d’un autre atelier/événement spécifique (même périodequi aboutissent à une note de positionnement sur la question et/ou un mandat pour le secrétariat de la fédération Partie B 4. Elaborer un rapport et un guide qui propose des méthode d’accompagnement des organisations souhaitant s’engager sur la voie d’un consortium ou d’une fusion 5. Mener éventuellement un coaching d’organisations souhaitant s’inscrire dans cette démarche
[isPublicMarket] => [executionPeriodFrom] => 2022-05-01 [executionPeriodTo] => 2022-10-31 [publicationDate] => 2022-04-01 [estimatedDuration] => 20 [estimatedAmount] => 199.99 [deliveryTenderDate] => 2022-04-26 [modalitySubmission] => [serviceId] => [typeId] => [countryId] => [wp_id] => 144 
As you can see, the 2 problematic fields are present in $data. I checked the spelling in the database and it's ok there too. What concerns me is even if I put $allowedFields = [], the insertion and modification (except the 2 fields) work. 
The debug gives me as query
PHP Code:
UPDATE `tendersSET `id` = '587', `title` = 'Mission de consultance sur les consortiums/fusions', `summaryMarket` = '<p>La mission de consultance a pour objectif de réaliser un état des lieux et d’accompagner ACODEV et ses membres afin de mieux comprendre les intentions du secteur et d’identifier les conditions et méthodes pour les appuyer dans d’éventuels processus de mise en place de consortium et/ou de mise en commun de services et/ou de fusions.Partie A : 1. Disposer d’une revue documentaire de la question 2. Disposer d’un état des lieux approfondi des intentions des membres d’ACODEV concernant la mise en place de consortiums et de fusions d’organisations ; 3. Animer un débat et/ou des travaux de groupes soit lors de l’assemblée générale d’ACODEV (juin) soit lors d’un autre atelier/événement spécifique (même période) qui aboutissent à une note de positionnement sur la question et/ou un mandat pour le secrétariat de la fédération Partie B : 4. Elaborer un rapport et un guide qui propose des méthode d’accompagnement des organisations souhaitant s’engager sur la voie d’un consortium ou d’une fusion 5. Mener éventuellement un coaching d’organisations souhaitant s’inscrire dans cette démarche</p>', `isPublicMarket` = '0', `executionPeriodFrom` = '2022-05-01', `executionPeriodTo` = '2022-10-31', `publicationDate` = '2022-04-01', `estimatedDuration` = '20', `estimatedAmount` = '199.99', `deliveryTenderDate` = '2022-04-26', `modalitySubmission` = '1', `serviceId` = '4', `typeId` = '6' WHERE `tenders`.`idIN ('587'

The 2 fields are not in the query. There you go, I don't know what lead anymore, I can investigate.
Thanks in advance


  $session->destroy() throws exception
Posted by: joho - 04-11-2024, 01:44 AM - Replies (5)

Why does this throw an exception?

PHP Code:
        $session = \Config\Services::session();
        $session_username $session->get'session_username' );
        $session_login_time $session->get'session_login_time' );
        $session_login_ip $session->get'session_login_ip' );
        if ( ! empty( $session_username) && ! empty( $session_login_time )  && ! empty( $session_login_ip ) ) {
            error_logbasename__FILE__ ) . ' (' __FUNCTION__ '): Session already active, re-directing to /' );
            return( $this->response->redirectbase_url() ) );
        }
        $ip_address $this->request->getIPAddress();
        if ( empty( $ip_address ) ) {
            error_logbasename__FILE__ ) . ' (' __FUNCTION__ '): Missing or invalid IP address "' $ip_address '", re-directing' );
            $session->destroy();
            return( $this->response->redirectbase_url() ) );
        }
        // .. code continues 

It throws an exception ("session_destroy(): Trying to destroy uninitialized session") when it gets to $session->destroy().

But if it's an uninitialized session, why doesn't it throw the exception sooner?

I honestly don't think the destroy() call should throw an exception. I have several blocks of code that do cleanup and then re-direct, so I add a destroy() call inside each of those blocks. I can't see anywhere in the PHP reference that session_destroy() in itself would ever throw an exception.


  VIRUS reported after Chrome update this morning!
Posted by: InsiteFX - 04-10-2024, 11:19 PM - Replies (3)

Ok, I do not usually ask questions on here but this morning I got an update to Google Chrome,
Now when I go to Download the CodeIgniter 4 Development from GitHub it is saying that it has a
VIRUS!

Trojan:Script/Wacatac.H!ml

[Image: VBf0cUa]

I think the Windows Update may be at play here.

This is the CodeIgniter 4 file path were it says the virus is in.

UPDATED:

CodeIgniter 4.5.0

C:\xampp\htdocs\admin\app\Views\errors\html\error_exception.php


  problem: unable to load static path of .css, .js, image files with codeigniter4
Posted by: nguyenhaitruong - 04-10-2024, 10:13 PM - Replies (4)

Hello everybody!

I installed Codeigniter 4 on an apache2 server, centos 7 operating system. When accessing the website, I had trouble loading static files such as .css, .js, images.
Please help me resolve this issue!
application path structure:
/var/www/top100mu.com/public_html/public/
                                                                         /index.php
                                                                       /.htaccess
                                                                     /templates/
                                                                                   /style.css
 When accessing the style.css file path https://top100mu.com/templates/style.css , I receive a 404 error message:                                                                                  
                               404
Can't find a route for 'GET: templates/style.css'.

Apache Configuration File:
<VirtualHost *:80>
    ServerName top100mu.com
    DocumentRoot /var/www/top100mu.com/public_html/public
    DirectoryIndex index.php
    SetHandler "proxy:fcgi://127.0.0.1:9082
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
    AddHandler php82-fcgi .php
    Action php82-fcgi /cgi-bin/php82.fcgi
    <Directory "/var/www/top100mu.com/public_html/public">
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog /var/log/httpd/top100mu.com_error.log
    CustomLog /var/log/httpd/top100mu.com_access.log combined
</VirtualHost>


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Codeigniter Shield Bannin...
by kenjis
2 minutes ago
SQL server connection not...
by kenjis
24 minutes ago
Best way to create micros...
by kenjis
2 hours ago
How to use Codeigniter wi...
by kenjis
2 hours ago
Getting supportedLocales ...
by kcs
8 hours ago
Component help
by FlashMaster
Today, 01:41 AM
Show logo in email inbox
by WiParson
Today, 12:48 AM
CI 4.5.1 CSRF - The actio...
by jackvaughn03
Yesterday, 10:17 PM
Limiting Stack Trace Erro...
by byrallier
Yesterday, 02:21 PM
Bug with sessions CI 4.5....
by ALTITUDE_DEV
Yesterday, 01:36 PM

Forum Statistics
» Members: 85,226
» Latest member: dewi188
» Forum threads: 77,577
» Forum posts: 375,977

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB