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

Return error from service

$
0
0
HI , i create a service to send data to a zebra printer , first create a third_party: 

Code:
<?php
namespace App\ThirdParty;


class StampaEtichette{

private $print_data;

    public $error='';

    public function __construct($print_data)
    {
    $this->print_data = $print_data;

        $this->zpl();
    }


    public function zpl() :string {

        $ip_stampante =getenv('IP_STAMPANTE');
       
        log_message('debug', 'ip_stampante'.$ip_stampante);

        $fp = @pfsockopen($ip_stampante, 6101 ,$errno, $errstr);
       
        if(!$fp){
           
            $errore =  "$errstr ($errno)<br/>\n";

            log_message('error', 'Errore apertura socket : '.$errore);

            return $errore;
           
        }else{
           
            if(fputs($fp, $this->print_data)){
               
                fclose($fp);

                return 'stampato';
           
            }else{
           
                return 'Problemi Fput';
           
            }

           
           
        }
       
           
    }


}

<?php
namespace App\ThirdParty;


class StampaEtichette{

private $print_data;

    public $error='';

    public function __construct($print_data)
    {
    $this->print_data = $print_data;

        $this->zpl();
    }


    public function zpl() :string {

        $ip_stampante =getenv('IP_STAMPANTE');
       
        log_message('debug', 'ip_stampante'.$ip_stampante);

        $fp = @pfsockopen($ip_stampante, 6101 ,$errno, $errstr);
       
        if(!$fp){
           
            $errore =  "$errstr ($errno)<br/>\n";

            log_message('error', 'Errore apertura socket : '.$errore);

            return $errore;
           
        }else{
           
            if(fputs($fp, $this->print_data)){
               
                fclose($fp);

                return 'stampato';
           
            }else{
           
                return 'Problemi Fput';
           
            }

           
           
        }
       
           


    }






}
this is service  :

Code:
<?php

namespace Config;

use CodeIgniter\Config\BaseService;

use App\ThirdParty\StampaEtichette;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
   
      public static function StampaEtichette(string $print_data,$getShared = true)
      {
          if ($getShared) {
              return static::getSharedInstance('StampaEtichette',$print_data);
          }
   
          return new StampaEtichette($print_data);
      }
   
}
When the printer not print i would show the error by flashdata
Code:
<?php

namespace App\Controllers\User;

use App\Controllers\BaseController;
use App\Models\Doa_righe_sparateModel;
use App\Models\DoaModel;

class UserStampaEtichette extends BaseController
{


    public function stampa_id_righe_sparate($id)
    {

        $doa_righe_sparate_model  = new Doa_righe_sparateModel();

        $record = $doa_righe_sparate_model->find($id);

        $data_to_print = $doa_righe_sparate_model->data_to_print($id);

        //dd($data_to_print);

        $stampa =  service('StampaEtichette',$data_to_print);


        if($stampa=='stampato'){
           

            session()->setFlashdata('gestisciRecordOK', 'Stampa effettuata correttamente');

            return redirect()->to('/user_Doa_righe_sparate/codiciSparati/'.$record->id_doa);


        }else{

            $errore = $stampa;

            session()->setFlashdata('gestisciRecordBad', 'Problemi stampa :'. $errore);

            return redirect()->to('user_Doa_righe_sparate/codiciSparati/'.$record->id_doa);
        }     


    }



}
But the error is : 
Object of class App\ThirdParty\StampaEtichette could not be converted to string
Third party class return a string ... why have i  this error ?

[Email Service] the sender's name doesn't appear in Gmail

$
0
0
Strange sender of emali..
Quote:by @kenjis
If you do not see the same sender name, this may be due to your SMTPHost or your email client.

I'm experiencing the same issue where the sender's name doesn't appear in Gmail. Is it possible to override the setForm() method, or is there another solution we can try?

PHP 8.1: Enums

cannot insert data if field id exist in validationRules model

$
0
0
I can't save data if I id exist in validationRules in the model. without id its run fine, why?
I add exception when get validationRules from the model, like 

$rules = $model->getValidationRules(['except' => ['id']]);

$data = $this->request->getPost(array_keys($rules));

if ($this->validateData($data, $rules)) {
     $payload = $this->validator->getValidated();
     $model->insert($payload);
}
 
no errors noticed, I followed the instructions from this link but it still didn't work:
https://codeigniter4.github.io/CodeIgnit...aceholders

Getting HTTP 404 when redirecting but reloading works.

$
0
0
Using CodeIgniter 4.5.3, after doing user identification (you know, creating a session variable and updating the database to register the login) I do a redirection to the index page this way:
PHP Code:
return redirect ()->to (''307); 
It always returns a HTTP 404 error, but reloading the page (i.e. [Ctrl]+[R]) loads it without any error.  Log doesn't show any message.

Accessing the index page directly (by putting the URL) doesn't fail.

Doing other redirections (for example, when the index page detects the user isn't identified it redirects to the login page using same code) works without any problem.

Anybody knows any reason for this behavior?

allowed memory size of bytes exhausted

$
0
0
Hi , ihaveinstalled codeigniter 4.4.3 on a NAS , if i leave in develope mode  it goes on error  allowed memory size of bytes exhausted simply showing an error validation , why ?

Support for psr/log:^2.0

$
0
0
TLDR; Version: If not too much trouble, I am hoping that future releases of codeigniter4/framework will support psr/log composer package version 2.X or 3.X.  Or if no additional headache, 1.X, 2.X or 3.X.
Longer Version:
I work as a software architect at my company and am currently in charge of upgrading our large 15+ year old PHP monolith application.  We are currently running PHP 8.0 and about to pull the trigger on updating to 8.1, with our 8.2 upgrade planned to release by Nov 2025.  During my testing I quickly discovered that codeigniter 3 and php 8.2 will never play well together.  So I started planning the migration to version 4, and unfortunately starting a new repo is not an option, as codeigniter driven stuff is only a portion of the entire monolith.  I had a successful POC branch running both CI 3 (3.1.13) and CI 4 (v4.4.8) in the same project, toggling which framework to load based on the request uri.  This will allow us to spend about a year porting features from CI 3 to CI 4.  My current concern is that we are stuck on psr/log:^2.0 in my project for the next several months until I upgrade multiple other heavy packages in order to allow us to upgrade to 3.X.  Codeigniter4/framework >= v4.5.0 requires psr/log:^3.0 in the composer.json file, and therefore does not support version 2.X.  I really don't want to have to downgrade psr/log to version 1.X to use the v4.4.8 release (since it only supports psr/log:^1.0) and I'm not sure about how long the 4.4.X branch will be supported/updated moving forward, plus there are only 2 releases < v4.5.0 without security vulnerabilities.

So what I am essentially asking is would it be possible to have codeigniter4/framework repo support psr/log 2.X AND 3.X (also if not too much trouble, 1.X to ease migration for your users from v4.4.8 to v4.5.X)? According to the changelog, the only difference between psr/log 2.X and 3.X was adding void return types to the traits and interfaces. Many vendors allow multiple versions for this package, with several allowing all 3 versions.  Would be great if this change could make it either into future v4.5.X releases, or v4.6.X releases if too late for v4.5.X.

Mike

21 Open Source LLM Projects to Become 10x AI Developer


Mastering the Fine Art of Web Development with PHP

Top 3 PHP Frameworks: Speed, Response Time, and Efficiency Compared

How do except in filters

$
0
0
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/

public array $filters = [
'isLoggedInPanel' => [
'before' => [ 'baclend/*' ],
'except' => [ 'baclend/login' ] // Add your excluded URLs here
]
];

Tell me please how can i add except for one url? not in globals
of course i can check url in isLoggedInPanel but i want do it in config file

How to use session()->close()?

$
0
0
Quote:Why are we telling you this? Because it is likely that after trying to find the reason for your performance issues, you may conclude that locking is the issue and therefore look into how to remove the locks …

DO NOT DO THAT! Removing locks would be wrong and it will cause you more problems!

Locking is not the issue, it is a solution. Your issue is that you still have the session open, while you’ve already processed it and therefore no longer need it. So, what you need is to close the session for the current request after you no longer need it.

Code:
<?php

$session->close();
https://www.codeigniter.com/user_guide/l...sions.html

in MyController.php
PHP Code:
class LearnSession extends BaseController
{
    public function index()
    {
        session()->set('brand''CodeIgniter4.5.3');
        session()->close();
        return redirect()->to('page2');
    }

public function 
page2()
    {
        d(session()->get());
    

result:

PHP Code:
session()->get() array (3)
⇄⧉__ci_last_regenerate => integer 1721278110
⇄_ci_previous_url 
=> string (27"http://localhost:8083/page2"
⇄brand => string (16"CodeIgniter4.5.3" 

What does session()->close() do? What does method close() mean? What is the difference between close () and remove()?

Print file on server

$
0
0
hi i have a view with 4 button to download 4 files . Is it possible to send file to printer (or open prompt to print) with the files ?

What's new in PHP 8.4

Session flock PHP timeout

$
0
0
Greetings guys,
I'm using codeigniter 4 for most of my projects and I am facing an Issue, sometimes, with the session data with the default FileHandler of codeigniter 4.
In codeigniter log i have this error sometimes:

CRITICAL - 2024-07-17 11:08:37 --> Maximum execution time of 240 seconds exceeded
in SYSTEMPATH\Session\Handlers\FileHandler.php on line 134.
1 [internal function]: CodeIgniter\Debug\Exceptions->shutdownHandler()

In apache log I have those:

 [php:error] [pid 7560:tid 2020] [client ::1:51108] PHP Fatal error:  Maximum execution time of 240 seconds exceeded in C:\\xampp\\htdocs\\Riepilogo_lavorazioni4\\vendor\\codeigniter4\\framework\\system\\Session\\Handlers\\FileHandler.php on line 134, referer: https://riepilogo_lavorazioni4.imbalplas...avorazioni

 [php:error] [pid 7560:tid 2020] [client ::1:51108] PHP Fatal error:  Uncaught ErrorException: Unknown: Cannot call session save handler in a recursive manner in Unknown:0\nStack trace:\n#0 [internal function]: CodeIgniter\\Debug\\Exceptions->errorHandler(2, 'Unknown: Cannot...', 'Unknown', 0)\n#1 {main}\n  thrown in Unknown on line 0, referer: https://riepilogo_lavorazioni4.imbalplas...avorazioni

I've checked in the FileHandler and on the line 134 there is the flock:

PHP Code:
if (flock($this->fileHandleLOCK_EX) === false) { 

I have the session preloaded in this way in the base controller:
PHP Code:
protected $session;
    

    
/**
    * Constructor.
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);

        // Preload any models, libraries, etc, here.
      
        $this
->session = \Config\Services::session();
        
      
    



And in most of my methods i check the user login in this way:

PHP Code:
public function getLista_lavorazioni($macchinario NULL)
    {
      if (!$this->session->has('user_login')) 
      {
        $this->session->setFlashdata("error_msg"'SESSIONE SCADUTA, ACCESSO NEGATO');
        throw new \CodeIgniter\Router\Exceptions\RedirectException(".");
      }


PHP VERSION IS: 8.1.12
Codeigniter version is: '4.3.5'
It seems codeigniter try to access a session file that is locked and go in timeout.
I have some ajax and long processes in some points and i check there too if the user is logged in or not. Maybe the problem is it?
Can you help me solve this? Thanks in advance

Combining multiple queries to get the result

$
0
0
Hello,
I would like to do some calculations but no success , how to convert this in simple and working query, most important variable is $sale_cost. What I would like to achieve is $sale_cost, I am also selecting $sale_cost in another query

Is there any shortcut to do all calculation in few working queries

Any help is very appreciated!

can you show me how match routes dont work in this case>

$
0
0
today i test matches routes in codeigniter 4.5.3 but it don't work, someone can show me?
routes
PHP Code:
$routes->match(['get','post'],'vnadmin/camera_category/addCate','\Modules\Admin\Cam\Controllers\CamController::addCate'); 

controller
PHP Code:
public function addCate(){
        //$this->mAuth->check();
        $data['Method'] = base_url('vnadmin/camera_category/addCate');
        $data['max_sort']=$this->m_cam->SelectMax('categories','sort')+1;
        $data['proshow_cate'] = $this->m_cam->getList('categories');
        $data['btn_name']='Thêm';
        $data['headerTitle'] = "Thêm danh mục cam";

        if($this->request->getMethod() == "post"){
            echo $this->request->getMethod();
            exit();
                $name $this->request->getPost('name');
                $parent $this->request->getPost('parent');
                $description $this->request->getPost('description');
                $keyword $this->request->getPost('keyword');
                //image goc
                
                $cate 
= [  'name'        => 'hoclai',
                            'slug'        => "hoc-lai",          
                
];

                $this->m_cam->Add('categories'$cate);
                return redirect()->to(base_url('/vnadmin/danh-muc-camera'));
        }
        echo view('admin/header'$data);
        echo view('admin/post_cam_cate_add'$data);
        echo view('admin/footer');
    

view
PHP Code:
<form class="form-horizontal" role="form" name ="form1" id="form1" method="post" action="<?php echo $Method; ?>" enctype="multipart/form-data" >
                        <input type="hidden" name="edit" value="<?=@$edit->id;?>">
                        <div class="form-group">
                            <label for="listcate" class="col-lg-2 control-label">Tên danh mục:</label>
                            <div class="col-lg-5">
                                <input type="text" class="form-control input-sm " name="name" value="<?=@$edit->name;?>" placeholder="Tên danh mục"  />
                            </div>
                            <div class="col-lg-1">
                                <label >
                                    <input type="checkbox" value="1" name="hot" <?php echo  @$edit->hot==1?'checked':'' ?>>
                                    <?php echo _title_cam_cate_hot?>
                                </label>
                                </div>
                                <div class="col-lg-1">
                                <label >
                                    <input type="checkbox" value="1" name="menu_hide" <?php echo  @$edit->menu_hide==1?'checked':'' ?>>
                                    <?php echo _title_cam_menu_hide?>
                                </label>
                                </div>
                                <div class="col-lg-1">
                                <label >
                                    <input type="checkbox" value="1" name="hide" <?php echo  @$edit->hide==1?'checked':'' ?>>
                                    <?php echo _title_cam_hide?>
                                </label>
                            </div>

                        </div>
                        <div class="form-group">
                            <label for="inputEmail1" class="col-lg-2 control-label">Danh mục cha:</label>
                            <div class="col-lg-5">
                                <select name="parent" class="form-control input-sm">
                                    <option value="0">root</option>
                                    <?php view_product_cate_select($proshow_cate,0,'', @$edit->parent_id);?>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-lg-2 control-label">Thứ tự:</label>
                            <div class="col-lg-2">
                                <input type="number" name="sort" class="form-control input-sm" value="<?php echo @$edit->order;?>" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail1" class="col-lg-2 control-label">Mô Tả:</label>
                            <div class="col-lg-5">
                            <textarea name="description" class="form-control" id="description" placeholder="Mô tả"><?=@$edit->description;?></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail1" class="col-lg-2 control-label">Keywords:</label>
                            <div class="col-lg-5">
                            <textarea name="keyword" class="form-control" id="keyword" placeholder="Mô tả"><?=@$edit->keyword;?></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail1" class="col-lg-2 control-label">Image:</label>
                            <div class="col-lg-5">
                            <input type="file" name="userfile" size="20" class="form-control" >
                            </div>
                        </div>
                        <div class="text-center">
                            <button type="submit" class="btn btn-success btn-sm" name="addcate"><i class="fa fa-check"></i> <?=$btn_name;?></button>
                        </div>
                    </form> 

this code can go to  page addCate but it dont get post data

of controllers, views and templates

$
0
0
I find it hard to explain my problem so i will write in a schematic way.
Rule is : One route -> one Controller::method -> one child template which is part of a parent template called by {% extends "default.twig" %}, when you use twig.
Ok, let's have a blog app, with a page binding :
- the list of posts or one post by his ID - route is 'blog' Controller is 'blog', method is 'index', data will be displayed in the child template
- list of categories - no route, data is displayed in the parent template
- list of last ten posts - no route, data is displayed in the parent template

in controller 'blog', method 'index', code will retrieve list of post, send it to template, but also retrieve list of categories, and list of ten last posts
Same in controller 'blog' method 'show', retrieve one post by his ID, list of categories, and list of ten last posts.
This is ugly and violate DRY rule.
What is the better way to do this ?

Thanks for help
Eric

Model best practices question

$
0
0
I'm building a REST API with four endpoints (I must say that I just started with CodeIgniter). One of them is to get data, and it receives two parameters id, and code via GET.
The issue is that the data is fetched from five different tables, all related (say table1, table2, ..., table5).
Here I have a doubt about what is the right way to build the solution:
Option 1: Create a model where I get the information from a SQL that joins all tables filtering on table1 where: (table1.id = id) AND (table1.code = code) AND (table1.status <> 'REJECTED') and have the controller call this model method. For example, in the controller I would have a method that contains something similar to the following:


PHP Code:
$dataModel = new DataModel();

// Retrieve data from all the tables with one SQL and JOINS
$data $dataModel->getData($id$code);

$responseData = [
    'column1' => data['column1'],
    'column2' => data['column2'],
    'column3' => data['column4'],
    ...
    'columnN' => data['columN']
]; 
Option 2: Create multiple models, one per table and from the controller call the methods that return me the information of each model. For example, in the controller I would have a method that contains something similar to the following:


PHP Code:
$table1Model = new Table1Model();
$table2Model = new Table2Model();
$table3Model = new Table3Model();
$table4Model = new Table4Model();
$table5Model = new Table5Model();

// Retrieve data from table1 table
$table1Data $table1Model->getData($id$code);

// Retrieve data from table2 table table1.idTable2 = table2.id
$table2Data $table2Model->getData($idTable2);

// Retrieve data from table3 table table table1.id = table3.idTable1
$table3Data $table3Model->getData($id);

// Retrieve data from table4 table table table2.id = table4.idTable2
$table4Data $table4Model->getData($idTable2);

// Retrieve data from table5 table table1.idTable5 = table5.id
$table5Data $table5Model->getData($idTable5);

$responseData = [
    'column1' => table1Data['table1Column1'],
    'column2' => table2Data['table2Column2'],
    'column3' => table3Data['table3Column4'],
    ...
    'columnN' => table5Data['table5ColumN']
]; 

The same query would be for an endpoint that needs to insert or update data in multiple tables.
What would be the best option? Is there a better one that I don't realize?

Any opinion/help is welcome!
Regards.

AVIF support

$
0
0
Hello CI team!

Following one of my previous GitHub pushes a few months ago, could you integrate and enable the AVIF image format in the framework?
It is worth noting that almost all browsers now support it, and more and more websites are adopting this practice to ensure optimal network performance.

AVIF is the next generation image format compared to WEBP. Here is the table from the Can I use website:
https://caniuse.com/avif


Thanks for reply =)
Florian
Viewing all 14343 articles
Browse latest View live


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