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

Problem saving binary data to a BLOB field in an SQLite3 database.

$
0
0
Hello,

I'm having a problem saving files to blob fields when using an SQLite3 database.
For some reason it only saves somewhere between 4kb and 8kb of data.

I'm trying this using the built in server (php spark serve which calls php's built in server) and I'm using Codeigniter 4.5.5 on php 8.3

In the migration I declared the blob field like this:
PHP Code:
'content' => [
    'type' => 'BLOB',
    'null' => true,
], 

I have created an entity called "File" using spark (no changes made to it).
I created a model called "FilesModel" using spark and the only changes I made are:
- set the return type to the entity mentioned above:
PHP Code:
protected $returnType      File::class; 
- set the allowed fields
PHP Code:
$allowedFields    = ["filename""content""mimetype""size"]; 

I'm saving the data after upload like this:
PHP Code:
$data = [
    ... other fields...
    'content' => file_get_contents(...temp file path...)
];

$savedFile = new \App\Entities\File();
$savedFile->fill($data);

$model = new FilesModel();
$model->save($savedFile); 

Saving data to a MySQL or MariaDB database works without any issues. Just SQLite3 seems to have a problem.
I know saving files in blob fields is not recomended, I know I could save the files as base64 encoded strings or to some block storage, but I don't have any choice in this mater.

Are there any additional configuration options that need to be set for SQLite3?

Laragon 7.0.0 Released.

Problem with Forum Website

$
0
0
I don't know if it is wanted by administrators, but the topic Netbeans Plugin and all the Archived Discussions cannot be turn as read. 
I always see them with bold folder icon. 
I also noticed that all the topics in that forums are with a filled heart. 
Clicking on gauge -> Mark all forums read has no effect.
Thank you

Validation Message on upload file

$
0
0
Hi master, 
I have some functions to upload invoice images
This is my rules : 
PHP Code:
public function upload ()
{
   if (!$this->validate([
     'invoice' => [
     'rules'  =>    'uploaded[invoice]|is_image[invoice]|mime_in[invoice,image/jpg,image/jpeg,image/png]|max_size[invoice,2048]',
     'errors' => [
       'is_image' => 'Invoice must be pictures.',
       'mime_in'  => 'Invoice must be jpg/jpeg/png.',
       'max_size' => 'Invoice must be jpg/jpeg/png.',
       'uploaded' => 'Invoice must be uploaded.'
      ]
   ]
 ])) {
    $validation $this->validation;
    session()->setFlashdata('fail''something wrong, please check your input form!');
    return redirect()->back()->withInput()->with('validation'$validation);
  } else {
    echo "OK";
 
 }


This is my view : 
PHP Code:
<form action="/Management/upload" method="post" enctype="multipart/form-data">
<?= 
csrf_field() ?>
   <label for="invoice" class="form-label">Invoice</label>
   <input type="file" class="form-control <?= ($validation->hasError('invoice')) ? 'is-invalid' ''?>" id="invoice" name="invoice">
   <div class="invalid-feedback">
      <?= $validation->getError('invoice'); ?>
   </div>
</form> 

This is my controllers :
PHP Code:
public function invoice ()
{
  $data = [
    'code' => $entertaintCode,
    'company' => $this->CompanyModel->findAll(),
    'entertaint' => $cekEntertaint,
    'validation' => $this->validation
  
];
  return view('management/invoice'$data);


When I tried to upload files such as PDF or anything else except images, validation worked but there was no error message on my input file.

Rules validation

$
0
0
'id' => [
    'label' => ' ',
    'rules' => 'required|is_natural_no_zero|validMyOwn[]'
]


When i validate form, if id is empty, anyway validMyOwn validation is executing, how prevent it?

pass data fom view to inlcuded views and back

$
0
0
Hello,

i try to create a kind of templateset,

in my controller i call the mainpage like this
"
$data['view_page']= $page;  //here is the main-content-filename for example "login" (.php)
$data['view_data']= $dataP; //Some data
echo view('templates/v1/create_page', $data);
"

in the "create_page" i include a lot of single files to seperate the different parts like this
"
    $data['data']=$view_data;                  //pass some data from controller to subfiles !?

    $this->include($view_page,$data);  //here i include my main-content-file for example "login"

  //from this mainfile i need access to the $data vars in the following files, but all my tries failed. Is it possible? How?

  $this->include('templates/v1/head',$data);
  $this->include('templates/v1/header',$data);
  $this->include('templates/v1/sidebar_left',$data);

"

main-content-file for example "login"
"
  //The following $data i need in the mainpage AND also included files like head, header etc. (as shown on top)
$data['view_template']=array(  'val1'  =>  'default', 'val2'=>''...);

$this->section('title') ?>Some content here <?= $this->endSection() ?>
"
 
Hope i could explain what i want to do?

Prevent direct access to views without logging in

$
0
0
Hello,
My document management system app requires the user to log in, following which they can search, edit etc records.  It came as a bit of a shock to discover that it's possible to bypass the login by adding the route (as per the routes.php file) to the URL (eg, https://ci-dms:<port>/category-add).  
I've now added the following to the top of each function in every controller in order to redirect to the login page if the session variable 'isLoggedIn' isn't set and it seems to work, but is this the best way?  Each controller has numerous functions meaning I've had to duplicate the code at the top of each one, which isn't ideal, but I've had no success with putting the code in a separate function and trying a function call from another function within the controller, which would seem a logical way to go.
Could I do it as a helper file, or is there some syntax for calling a function that I've missed?
Code:
public function index()
    {
    if(! isset($_SESSION['isLoggedIn'])) {
    return redirect()->to(site_url('/login'));
}
...
}

Many thanks

PHP 8.4.2. This is a bug fix release.

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

Session data lost after route redirect

$
0
0
PHP: 8.3.14 — CodeIgniter: 4.5.1 


PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\BaseConfig;
use 
CodeIgniter\Session\Handlers\BaseHandler;
use 
CodeIgniter\Session\Handlers\FileHandler;

class 
Session extends BaseConfig
{
    /**
    * --------------------------------------------------------------------------
    * Session Driver
    * --------------------------------------------------------------------------
    *
    * The session storage driver to use:
    * - `CodeIgniter\Session\Handlers\FileHandler`
    * - `CodeIgniter\Session\Handlers\DatabaseHandler`
    * - `CodeIgniter\Session\Handlers\MemcachedHandler`
    * - `CodeIgniter\Session\Handlers\RedisHandler`
    *
    * @var class-string<BaseHandler>
    */
    public string $driver FileHandler::class;

    /**
    * --------------------------------------------------------------------------
    * Session Cookie Name
    * --------------------------------------------------------------------------
    *
    * The session cookie name, must contain only [0-9a-z_-] characters
    */
    public string $cookieName 'ci_session';

    /**
    * --------------------------------------------------------------------------
    * Session Expiration
    * --------------------------------------------------------------------------
    *
    * The number of SECONDS you want the session to last.
    * Setting to 0 (zero) means expire when the browser is closed.
    */
    public int $expiration 43200;

    /**
    * --------------------------------------------------------------------------
    * Session Save Path
    * --------------------------------------------------------------------------
    *
    * The location to save sessions to and is driver dependent.
    *
    * For the 'files' driver, it's a path to a writable directory.
    * WARNING: Only absolute paths are supported!
    *
    * For the 'database' driver, it's a table name.
    * Please read up the manual for the format with other session drivers.
    *
    * IMPORTANT: You are REQUIRED to set a valid save path!
    */
    public string $savePath WRITEPATH 'session';

    /**
    * --------------------------------------------------------------------------
    * Session Match IP
    * --------------------------------------------------------------------------
    *
    * Whether to match the user's IP address when reading the session data.
    *
    * WARNING: If you're using the database driver, don't forget to update
    *          your session table's PRIMARY KEY when changing this setting.
    */
    public bool $matchIP false;

    /**
    * --------------------------------------------------------------------------
    * Session Time to Update
    * --------------------------------------------------------------------------
    *
    * How many seconds between CI regenerating the session ID.
    */
    public int $timeToUpdate 300;

    /**
    * --------------------------------------------------------------------------
    * Session Regenerate Destroy
    * --------------------------------------------------------------------------
    *
    * Whether to destroy session data associated with the old session ID
    * when auto-regenerating the session ID. When set to FALSE, the data
    * will be later deleted by the garbage collector.
    */
    public bool $regenerateDestroy false;

    /**
    * --------------------------------------------------------------------------
    * Session Database Group
    * --------------------------------------------------------------------------
    *
    * DB Group for the database session.
    */
    public ?string $DBGroup null;


Cookies Set.
PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\BaseConfig;
use 
DateTimeInterface;

class 
Cookie extends BaseConfig
{
    /**
    * --------------------------------------------------------------------------
    * Cookie Prefix
    * --------------------------------------------------------------------------
    *
    * Set a cookie name prefix if you need to avoid collisions.
    */
    public string $prefix '';

    /**
    * --------------------------------------------------------------------------
    * Cookie Expires Timestamp
    * --------------------------------------------------------------------------
    *
    * Default expires timestamp for cookies. Setting this to `0` will mean the
    * cookie will not have the `Expires` attribute and will behave as a session
    * cookie.
    *
    * @var DateTimeInterface|int|string
    */
    public $expires 0;

    /**
    * --------------------------------------------------------------------------
    * Cookie Path
    * --------------------------------------------------------------------------
    *
    * Typically will be a forward slash.
    */
    public string $path '/';

    /**
    * --------------------------------------------------------------------------
    * Cookie Domain
    * --------------------------------------------------------------------------
    *
    * Set to `.your-domain.com` for site-wide cookies.
    */
    public string $domain '';

    /**
    * --------------------------------------------------------------------------
    * Cookie Secure
    * --------------------------------------------------------------------------
    *
    * Cookie will only be set if a secure HTTPS connection exists.
    */
    public bool $secure false;

    /**
    * --------------------------------------------------------------------------
    * Cookie HTTPOnly
    * --------------------------------------------------------------------------
    *
    * Cookie will only be accessible via HTTP(S) (no JavaScript).
    */
    public bool $httponly true;

    /**
    * --------------------------------------------------------------------------
    * Cookie SameSite
    * --------------------------------------------------------------------------
    *
    * Configure cookie SameSite setting. Allowed values are:
    * - None
    * - Lax
    * - Strict
    * - ''
    *
    * Alternatively, you can use the constant names:
    * - `Cookie::SAMESITE_NONE`
    * - `Cookie::SAMESITE_LAX`
    * - `Cookie::SAMESITE_STRICT`
    *
    * Defaults to `Lax` for compatibility with modern browsers. Setting `''`
    * (empty string) means default SameSite attribute set by browsers (`Lax`)
    * will be set on cookies. If set to `None`, `$secure` must also be set.
    *
    * @phpstan-var 'None'|'Lax'|'Strict'|''
    */
    public string $samesite 'Lax';

    /**
    * --------------------------------------------------------------------------
    * Cookie Raw
    * --------------------------------------------------------------------------
    *
    * This flag allows setting a "raw" cookie, i.e., its name and value are
    * not URL encoded using `rawurlencode()`.
    *
    * If this is set to `true`, cookie names should be compliant of RFC 2616's
    * list of allowed characters.
    *
    * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
    * @see https://tools.ietf.org/html/rfc2616#section-2.2
    */
    public bool $raw false;


my login authentication does not work because after storing the data in the session and redirecting to another page I simply lose the logged in user data

works on another server and local server.


tried patch System/Session/Session.php

and add session_start() at public_html/index.php

Flashdata dont work either.

Request getPost error

$
0
0
I'm struggling trying to make Ajax Datatable working fine in CI4 ...and honestly I'm a bit lost.
The Javascript code call the method getRegister in Civils controller, the method starts with:
Code:
public function getRegister()
    {
        $request = service('request');
        $postData = $request->getPost();
        $dtpostData = $postData['data'];
        $response = array();

        ## Read value
        $draw = $dtpostData['draw'];
        $start = $dtpostData['start'];
        $rowperpage = $dtpostData['length'];
        $columnIndex = $dtpostData['order'][0]['column'];
        $columnName = $dtpostData['columns'][$columnIndex]['data'];
        $columnSortOrder = $dtpostData['order'][0]['dir'];
        $searchValue = $dtpostData['search']['value'];
        ...
        ...

The code above return the following error:
Code:
line:31
message:"Undefined array key \"data\""

What's wrong? I have no idea how to fix it.
Thanks a lot for any hint

Protected method in controller

$
0
0
In CI3 I was able to set private o protected method in controller, for example:

Code:
    private function _human_filesize($bytes, $decimals = 2)
    {
        $factor = floor((strlen($bytes) - 1) / 3);
        if ($factor > 0) $sz = 'KMGT';
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor - 1] . 'B';
    }
then I could call the private function within the same controller with:

Code:
    $this->_human_filesize($size);

Can we do the same in CI4? ...Sorry I'm a bit lost about this point reading the online guide

Shield "Can't find a route for 'POST: login'. "

$
0
0
Hi,

i've installed ci4 with shield.

At first i want to create a own login view for that i've create a copy of the "loginController.php" from the "vendor/codeigniter4/shield/src/controllers/" with the dirst fnction "loginView()" (its the only part wich call the "views") all other i think i can ignore an let it as original it is.

"amespace App\Controllers\Shield;

use CodeIgniter\Shield\Controllers\LoginController as ShieldLogin;
use CodeIgniter\HTTP\RedirectResponse;


class LoginController extends ShieldLogin
{
public function loginView()
{
if (auth()->loggedIn()) {
return redirect()->to(config('Auth')->loginRedirect());
}

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();

// If an action has been defined, start it up.
if ($authenticator->hasAction()) {
return redirect()->route('auth-action-show');
}

//Render page (i've change a bit the way to echo and render the views)
$this->template(setting('Auth.views')['login'], array(), array('title'=>'4U.tools - Login'), array('mode'=>'fullpage'));
}
}"

Also in my "app/Config/Routes.php", i've added this
"use CodeIgniter\Router\RouteCollection;

/**
* @var RouteCollection $routes
*/
$routes->get('/', 'Home::index');

//service('auth')->routes($routes);
service('auth')->routes($routes, ['except' => ['login']]);

//Authentification by shield
$routes->get('login', '\App\Controllers\Shield\LoginController::loginView');"

Now on mydomain.tld/login is see my own view.

If i submit the form i get the "404 Can't find a route for 'POST: login'. " error message.

I think i have to change more as i already done. Have i add each of the following parts also to my "app/Config/Routes.php"?
If so, is there a way to make it easier, with less code?


+--------+----------------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+
| Method | Route | Name | Handler | Before Filters | After Filters |
+--------+----------------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+
| GET | {locale}/register | register | \CodeIgniter\Shield\Controllers\RegisterController::registerView | | toolbar |
| GET | {locale}/login | login | \CodeIgniter\Shield\Controllers\LoginController::loginView | | toolbar |
| GET | {locale}/login/magic-link | magic-link | \CodeIgniter\Shield\Controllers\MagicLinkController::loginView | | toolbar |
| GET | {locale}/login/verify-magic-link | verify-magic-link | \CodeIgniter\Shield\Controllers\MagicLinkController::verify | | toolbar |
| GET | {locale}/logout | logout | \CodeIgniter\Shield\Controllers\LoginController::logoutAction | | toolbar |
| GET | {locale}/auth/a/show | auth-action-show | \CodeIgniter\Shield\Controllers\ActionController:Confusedhow | | toolbar |
| POST | {locale}/register | register | \CodeIgniter\Shield\Controllers\RegisterController::registerAction | | toolbar |
| POST | {locale}/login | » | \CodeIgniter\Shield\Controllers\LoginController::loginAction | | toolbar |
| POST | {locale}/login/magic-link | » | \CodeIgniter\Shield\Controllers\MagicLinkController::loginAction | | toolbar |
| POST | {locale}/auth/a/handle | auth-action-handle | \CodeIgniter\Shield\Controllers\ActionController::handle | | toolbar |
| POST | {locale}/auth/a/verify | auth-action-verify | \CodeIgniter\Shield\Controllers\ActionController::verify | | toolbar |
+--------+----------------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+

How to use view() for Authentication Actions?

$
0
0
Hi,

i want to customize the view/layout for each view-file.

For that in my case i have to change the controllers to change the original way to render the viewfiles from 
"$this->view(setting('Auth.views')['register']);"
to
"$this->template(setting('Auth.views')['register'], array(), array('title'=>'mytext - '.lang('Auth.register')), array('mode'=>'fullpage')); "

For the "normal" pages lik login or register all is fine.

For the special auth-actions for example "email_activate_show" i coulnd find the part where the view file is called to render. At the moment i cannot use my "template" function to render the view.

At the moment only the content of the "email_activate_show" will show but i want to chang this to my own function but i dont now where is the part for that.

Where i find the part for this or how i can render the auth-action view files in the same way like all others?

I see the ActionController and here this part
" public function show()
    {
        return $this->action->show();
    }"

My try to override/extend the actioncontroller in the same way like the login oder registrationcontroller doesnt work
"namespace App\Controllers\Shield;
use CodeIgniter\Shield\Controllers\RegisterController as ShieldAction;
use CodeIgniter\HTTP\RedirectResponse;


/**
* Class RegisterController
*
* Handles displaying registration form,
* and handling actual registration flow.
*/
//class RegisterController extends BaseController
class ActionController extends ShieldAction
{
    /**
    * Shows the initial screen to the user to start the flow.
    * This might be asking for the user's email to reset a password,
    * or asking for a cell-number for a 2FA.
    *
    * @return Response|string
    */
    public function show()
    {
        return $this->template( $this->action->show(), array(), array('title'=>'mytext - '.lang('Auth.register')), array('mode'=>'fullpage')); 
        //return $this->action->show();
    }

}"
(Hope it's clear what i mean - sorry if its not)



https://shield.codeigniter.com/reference...h_actions/

Protect helpers and setup db connection for helpers

$
0
0
Hi,

in ci3 i see this line at top of my helpers
"if ( ! defined('BASEPATH')) exit('No direct script access allowed');"

is it recommend to use it in ci4 too?

By the way, do i need to initialise the db-connection on every helper function again, or is there a better way to support db connection in the helper functions i need?

"my_helperfunction($this){
$db = \Config\Database::connect();
..
}

my_helperfunction_next($this){
$db = \Config\Database::connect();
..
}

..."

How to Build a Website to Control Music on TTGO Display for an Alarm Player?

$
0
0
Hi everyone,

I’m planning to build a series of alarm music players that can change songs via a website. I’m using the TTGO Display board for this project. However, I’m not sure how to set up the website for managing the songs.

Does anyone have a solution or advice on how to design and connect a website to control the TTGO Display? Any recommendations on frameworks, libraries, or examples would be greatly appreciated.

Thank you in advance for your input!

Handling Session Expiry in CodeIgniter 4 with Shield

$
0
0
Hi,

I'm using CodeIgniter 4 with Shield. In my project, there’s a web and a mobile side, and I check if a user is actively logged in through a table called user_limit_check (to prevent unauthorized access or usage). I use the App\Filters\AuthFilter.php file and its before method to run some validation steps before every request—whether it’s during login or while the app is being used. If everything checks out, the user can continue using the app; if not, I log them out with auth()->logout(), redirect them to the \login page, and show a message using flashdata. So far, everything works fine.

The problem starts when the user's session expires automatically. They get redirected to the login screen, but when they try to log in again, my validation in the before method runs and throws an error saying: "This user already has an active session." This blocks them from logging back in. (I’m planning to handle this part differently later.)

What I’m trying to figure out is: which function runs when the user's session expires? I need to find that function so I can add a query to clear their record when the session ends. I’ve spent a whole day trying to figure it out but couldn’t find anything. Maybe it’s something simple that I’m overlooking, but I just can’t seem to get it. I’d really appreciate it if you could help.

Thanks in advance!

Any help in this matter would be greatly appreciated.

$
0
0
Hello,

I would like to inquire if it is possible to make CodeIgniter compatible with Nginx and VestaCP. I am experiencing an issue where many users encounter the "404 Not Found" error. Therefore, I would like to directly request assistance from developers and coders to consider providing support for this platform within the CodeIgniter framework. Modifying the website configuration files without causing disruptions to all the websites can be a complex task, and having built-in support would greatly alleviate this challenge.

Thank you for your attention, and any help in this matter would be greatly appreciated.

Merry Christmas

$
0
0
Merry Christmas Everyone
and have a
Happy New Years 2025

Call to undefined method CodeIgniter\Shield\Models\UserModel::users_get_by_id

$
0
0
HI.

i tried to create my first own modell and controller,

in "Controller/My/Dashboard"
"
Code:
namespace App\Controllers\My;
use App\Controllers\BaseController;

//Load needed Models
use App\Models\Model;

class Dashboard extends BaseController
{

    //Load Models, Helpers etc.
    public function __construct()
        {
            $this->UsersModel = model('UserModel');
            //$this->someModel = model('Some_model');
        }
   
    public function index()
    {

        //Get ID of loggedin user
        $user = auth()->user();

        //get all datas from user-table
        $data['user'] = $this->UsersModel->users_get_by_id(user_id());

        echO"<pre>";
        var_dump($user);
        die("Stopp");
    }
}
"

in my model App/Models/UserModel.php


Code:
namespace App\Models;

use CodeIgniter\Model;

//use CodeIgniter\Database\Exceptions\DataException;

/**
* @phpstan-consistent-constructor
*/
class UsersModel extends Model
{
    //DB Connection - default is globalDB
    protected $DBGroup = 'globalDB';

    /**
    * Called during initialization. Appends
    * our custom field to the module's model.
    */
    protected function initialize()
    {
        //Mdoell DB-Table
        protected $table = 'users';
        $this->table = $this->tables['users'];

        //Modell DB-Tables primary key
        protected $primaryKey    = 'id';
...
  }


  public function users_get_by_id(int $id)
    {
        return $this->find($id);     
    }
}


If i enter the "my/dashboard" page, i revieved this error: "Call to undefined method CodeIgniter\Shield\Models\UserModel::users_get_by_id "

I wondering about the path, why "Shield"?
In the NAmespaces of the Controller and the Modell i told "App" Path?

What i do wrong?

Sorry i find the problem,

Shield has a model called "user Model", in my dashboard I called this "usersModel" instead of my own - I forgot the "s", that's all

Now i have new problem: "Type of App\Models\UsersModel::$allowEmptyInserts must be bool (as in class CodeIgniter\BaseModel) " what it means? What i have to do?

for them moment i comment out the line "$allowEmptyInserts" that all, but i think it will be better to understand what $allowEmptyInserts is for ;-)

Creation of dynamic property DEPRECATED

$
0
0
To create a multilanguages web site I've added into the initController method in BaseController file the following code that causes a warning in log :
Severity Message
info Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
warning [DEPRECATED] Creation of dynamic property App\Controllers\Home::$session is deprecated in APPPATH\Controllers\BaseController.php on line 68

What's wrong and how to fix it? Thanks

Code:
    if (session_status() == PHP_SESSION_NONE) {
        $this->session = \Config\Services::session();
    } 
Viewing all 14343 articles
Browse latest View live


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