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

Controller Filter Not Running

$
0
0
I am new to using filters so please forgive me if I am not understanding. Following the docs, I have the code below, but nothing happens when I visit that controller method (cases/index):

What am I missing? 

I am using version 4.4.4.


PHP Code:
App/Filters/AuthenticationFilter.php

[php]namespace App\Filters;
use 
CodeIgniter\Filters\FilterInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Config\Services;

class 
AuthenticationFilter implements FilterInterface {
    public function before(RequestInterface $request$arguments null) {
        $this->session Services::session();
        if (!$this->session->has('loggedin') || !$this->session->loggedin == true) {
            redirect('login');
        }
    }

    public function after(RequestInterface $requestResponseInterface $response) {
      
    
}  



App/Config/Filters,php

PHP Code:
[php]namespace Config;
use 
CodeIgniter\Config\BaseConfig;
use 
CodeIgniter\Filters\CSRF;
use 
CodeIgniter\Filters\DebugToolbar;
use 
CodeIgniter\Filters\Honeypot;
use 
CodeIgniter\Filters\InvalidChars;
use 
CodeIgniter\Filters\SecureHeaders;

class 
Filters extends BaseConfig
{
    /**
    * Configures aliases for Filter classes to
    * make reading things nicer and simpler.
    *
    * @var array<string, class-string|list<class-string>> [filter_name => classname]
    *                                                    or [filter_name => [classname1, classname2, ...]]
    */
    public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'authentication' => \App\Filters\AuthenticationFilter::class,
    ];

    /**
    * List of filter aliases that are always
    * applied before and after every request.
    *
    * @var array<string, array<string, array<string, string>>>|array<string, list<string>>
    */
    public array $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
            // 'invalidchars',
        ],
        'after' => [
            'toolbar',
            // 'honeypot',
            // 'secureheaders',
        ],
    ];

    /**
    * List of filter aliases that works on a
    * particular HTTP method (GET, POST, etc.).
    *
    * Example:
    * 'post' => ['foo', 'bar']
    *
    * If you use this, you should disable auto-routing because auto-routing
    * permits any HTTP method to access a controller. Accessing the controller
    * with a method you don't expect could bypass the filter.
    */
    public array $methods = [];

    /**
    * List of filter aliases that should run on any
    * before or after URI patterns.
    *
    * Example:
    * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
    */
    public array $filters = [
        'AuthenticationFilter' => ['before' => ['cases/index']]
    ];


Learn Markdown syntax to be ready to contribute to open source software.

Content Optimization Strategies - SEO Friendly URLs

Feature request: Run a process by id number - CI4/Queue

$
0
0
We queue the processes and make them work well with the help of cron job, but in some cases we may need to keep the cron job duration long, for example once an hour or once a day, and in some processes we may want the queued record to be processed directly.

To give an example for this;
  • Password reset e-mails or sms
  • Single-use code submissions (email and sms)

It would be nice if an id value is returned to us when we save it in the process queue and we can directly start the process according to the id value as a command.

Or

It would be very nice if we can add an additional method that we can run directly at the same time at the time of queuing the process, such as “->run()”.

If there is a different method that I do not know for the subject I mentioned, I would appreciate if you inform me.

_SESSION / ionauth not working

$
0
0
Hello

I have picked up the code for a website that used to be running.  First I could see the homepage but after I tried to register, I'm getting all kind of strange ionAuth or _SESSION related issues.
I am not a codeigniter expert.  I can see session files created under writabel/session, the database is connecting because I inserted part of a user.  I am running nginx and php7.4fpm and generally the website is up, but I don't understand why sessions and the rest are failing.


ErrorException
Trying to get property 'username' of non-object
APPPATH/Controllers/MyProfile.php at line 53
Code:
Code:
46      * 
47      * @access private
48      * @return void
49      */
50     private function getCommonData()
51     {
52         $this->data['breadcrumbs'] = $this->breadcrumb->buildAuto();
53         $this->data['username'] = $this->ionAuth->user()->row()->username;
54     }
55
56     /**

Understanding Local Storage in JavaScript

Question about upgrading to CI 4.5.5 from 4.5.4

$
0
0
I upgraded from 4.5.4 to 4.5.5 and only composer.json appears in the list of all modified files

Reading the chengelog I see: fix: update preload.php by @kenjis, but preload.php does not appear in the list of modified files.
Is it an oversight or did I not understand?

CSRF token for AJAX call in attached javascript file

$
0
0
I'm working in Codeigniter 4 with CSRF protection enabled. I have an AJAX call in an attached js file, and I can't figure out how to generate the CSRF token. Previously, I have done it in php files with embedded js, but in the attached js file I can't run php.

In the attached js file I have:

Code:
//makes a tooltip with description of analysis (header)
    $('.tbl-header').each(function () {
        makeHeaderInfo($(this))
    })

function makeHeaderInfo(header) {
        var analysis = header.hasClass('seed') ? 'Seedling ' + header.text().toLowerCase() : 'Sapling ' + header.text().toLowerCase();
        var posturl = baseURL + "forest_regen/getAnalysisDetails";
        var data = {};
        data['analysis'] = analysis;
//This is what I would do in a php file...
//      var csrfName = '<?= csrf_token() ?>';
//      var csrfHash = '<?= csrf_hash() ?>'; 
//      data[csrfName]=csrfHash;
        $.when($.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})).done(function (result) {
            var description = (result.fldDescription == null) ? 'No description for this analysis yet' : result.fldDescription
            header.children('.header-info').attr('title', description)
                    .tooltip({
                        trigger: 'click hover',
                        placement: 'top',
                        container: 'body'
                    })
        })
    };

I tried defining the variables in the php file which has this js file attached, but I get "csrfName is not defined." I'm not sure how to pass the variables to the js file?

Is there a way to generate the csrfName and csrfHash in javascript or jquery? Or another way to accomplish this?

Thank you!

Are there any Authorize.net tutorials?

$
0
0
I am trying to integrate the Authorize.net API into CI 4 and running into issues. Are there any good tutorials out there?

Has CI3 reached end of life?

$
0
0
What is the official status of CI3?
Are there any plans for future releases for eg. security issues or PHP compatibility?

How to handle "fatal errors" by displaying something "useful"

$
0
0
What is the recommended/intended way to die gracefully in a CI4 application?
Say I have requirements of the existence of a session variable or some other critical requirement. In any given function, I want to check for that being in place, and if not display something to the effect of "Uh Oh, that didn't work out...", possibly followed by some more details.
Would throwing an EmergencyError, AlertError, or CriticalError exception be the way to go? If so, how would I get to a specific view (like for 404 errors) where I can inform the user that something went tits-up? I'm assuming the framework has some default handling of these; and that's all swell and dandy in test/development, but in production, I'd rather display something "nice".

futurism.com. Human Developers Will Soon Be a Thing of the Past

SaaS Monitoring

$
0
0
Hi everyone,
are you using a monitoring software for your webservice?
Could you recommend one?
Best, Jan

validation not working

$
0
0
Hi, I'm a newbie and I want to ask you something about validation.
I just created some rules for form validation.

This is my Controller : 
Code:
public function create()
    {
        if (!$this->validate([
            'name' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Field Name is required.',
                ]
            ]
        ])) {
            $validation = $this->validation;
            session()->setFlashdata('fail', 'something wrong, Check your form input!');
            return redirect()->back()->withInput()->with('validation', $validation);
        } else {
            dd("OK");
        }
    }

This is my View : 
Code:
<form action="/Home/create" method="post" enctype="multipart/form-data">
   <?= csrf_field(); ?>
   <div class="mb-3">
       <label for="name" class="form-label">Nama</label>
       <input type="text" class="form-control <?= ($validation->hasError('name')) ? 'is-invalid' : ''; ?>" id="name" name="name" value="<?= old('name'); ?>" autofocus autocomplete="off">
       <div class="invalid-feedback">
           <?= $validation->getError('name'); ?>
       </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>


But when I tried to submit the form with the empty field and I dd($validation->getError('name')) the return is empty error data.

My PHP Version : 8.2.12
My CodeIgniter Version : 4.5.5

Please Help Me, Master.

Routes Error after upgrade to v4.5.5

$
0
0
Hi,
I have just upgraded to v4.5.5 and I am now getting errors I have never received before.

Code:
CRITICAL - 2024-09-17 14:15:42 --> GuzzleHttp\Exception\ConnectException: cURL error 6: getaddrinfo() thread failed to start (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://identity.xero.com/connect/token
[Method: POST, Route: quote_hook]

During the upgrade I noticed Config/Routes had been changed and Config/Routing had been added. As part of the upgrade I ensured by previous Routes settings ($routes->setDefaultNamespace('App\Controllers');$routes->setDefaultController('Home');$routes->setDefaultMethod('index');$routes->setTranslateURIDashes(false); $routes->set404Override(); were replicated in Routing.
Any assistance would be helpful?

10 Websites every Web developer Should at least look at

Compare database tables and models

$
0
0
Hello,

I would like to know if there is a way to check the current database tables and if the CI4 models implements all columns correctly.

My team and I are create, update many tables and we would like to do tests that check if our models linked to a table match its state (same number and same names for the columns).


Any help is welcome !

CI 3.1.13 Unable to locate the specified class: Session.php

$
0
0
So I've inherited an old CI 3 project running on PHP7.0

I've upgrade to the latest CI 3 version and I want to make the change to PHP7.4 so that I can keep upgrading to CI 4, then upgrade to PHP8 etc.

95% of the site works fine but on some pages, I just get a blank page saying "Unable to locate the specified class: Session.php"


These are my autoloaded libraries:

Code:
$autoload['libraries'] = array('database','session','lib_smarty','module','form','tank_auth','user_auth');


I've looked through the forum for topics with a similar problem but most were either unresolved and/or their solution didn't work for me.
I've already installed a fresh copy of CI 3.1.13.

If I remove all libraries from the autoload, I am greeted with the following error.

Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined property: Module::$session

Filename: core/Model.php

Line Number: 74

base_url() not working after upgrade

$
0
0
Hi,
I updated CI4 from 4.3.5 to 4.4.8.
Since I have a problem with base_url().

In the controller called by https://site.com, base_url() gives the correct information.
In the controller called by https://site.com/app/logs for example, base_url() falls in error " Unable to parse https://" :
Trace:



  1. SYSTEMPATH\HTTP\SiteURI.php : 120   —  CodeIgniter\HTTP\Exceptions\HTTPException::forUnableToParseURI ()

    Code:
    113        $uri = $this->baseURL . $indexPageRoutePath;
    114
    115        // applyParts
    116        // d($uri);
    117        $parts = parse_url($uri);
    118        // trace();exit;
    119        if ($parts === false) {
    120            throw HTTPException::forUnableToParseURI($uri);
    121        }
    122       
    123        $parts['query']    = $query;
    124        $parts['fragment'] = $fragment;
    125        // d($parts);exit;
    126        // d($this);
    127        $this->applyParts($parts);

  2. SYSTEMPATH\HTTP\SiteURI.php : 396   —  CodeIgniter\HTTP\SiteURI->__construct ()

    Code:
    389        $config            = clone config(App::class);
    390        $config->indexPage = '';
    391
    392        $host = $this->getHost();
    393        // d($relativePath);
    394        // d($config);
    395        // d($host);exit;
    396        $uri = new self($config, $relativePath, $host, $scheme);
    397
    398        // Support protocol-relative links
    399        if ($scheme === '') {
    400            return substr((string) $uri, strlen($uri->getScheme()) + 1);
    401        }
    402       
    403        return (string) $uri;

  3. SYSTEMPATH\Helpers\url_helper.php : 58   —  CodeIgniter\HTTP\SiteURI->baseUrl ()

    Code:
    51      */
    52    function base_url($relativePath = '', ?string $scheme = null): string
    53    {
    54        $currentURI = Services::request()->getUri();
    55        // d($currentURI);exit;
    56        assert($currentURI instanceof SiteURI);
    57
    58        return $currentURI->baseUrl($relativePath, $scheme);
    59    }
    60 }
    61
    62 if (! function_exists('current_url')) {
    63    /**
    64      * Returns the current full URL based on the Config\App settings and IncomingRequest.
    65      *

  4. APPPATH\Controllers\LogsController.php : 17   —   base_url()
  5. SYSTEMPATH\CodeIgniter.php : 943   —  App\Controllers\LogsController->index ()







Any idea ?


Thank you in advance

Error at RouteCollection

$
0
0
{
        $to = static fn (...$data) => service('renderer')
            ->setData(['segments' => $data], 'raw')
            ->render($view, $options);

        $routeOptions = $options ?? [];
        $routeOptions = array_merge($routeOptions, ['view' => $view]);

        $this->create(Method::GET, $from, $to, $routeOptions);

        return $this;
    }

My Terminal says that my "fn" is incorrect:
"Syntax error: unexpected token 'fn'"
Viewing all 14343 articles
Browse latest View live


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