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

validateDate string error message

$
0
0
In the controller, use

PHP Code:
$this->validateData($data'account'  => 'required|string|max_length[64]|min_length[3]'); 
but, account input value is 123, the validate not alert error message.
may i something wrong?!

PHP Version: 8.3.9
CI Version: 4.5.3

Fresh install won't run

$
0
0
Hey guys,

I did a fresh CI4 installation with composer.
Apache up and running, tested all locations and the return of index pages.
However, the CI index gives me:

Code:
systemDirectory . '/Boot.php'; exit(CodeIgniter\Boot::bootWeb($paths));


in the upper left corner on a blank screen.
What's going on?

Regards
Gee

PS: using 'php spark serve' returns the index perfectly

Ajax controller responding slow

$
0
0
I am experiencing that controller endpoint handling Ajax requests are responding very slow...
I've though mittigated this exit() just after handling the response to the client requesting the endpoint.

Code:
$this->output
                            ->set_content_type('application/json')
                            ->set_status_header(201);
                        echo json_encode(array(
                            'status' => 1,
                            'message' => 'ok',
                            'image' => $post['id'],
                            'jury_id' => $this->jury_id,
                        ),JSON_UNESCAPED_SLASHES);
                        exit();

If I don't do the exit() in the controller function, it seems that too much is taking place in the post processing functions.
Any better way to approach this?

I am still on CI3!!

Geir

How to enable webSocket in codeigniter 4?

$
0
0
Im still very new and interested in developing a web system with Ratchet webSocket. Any tutorials to learn?

Notification counter

$
0
0
Good morning everyone,

I have a small doubt on how to manage the notification count in the topbar.
I was thinking of adding the number of notifications to the session, and then, in the topbar view, displaying the total number, taken from the session.
now, since each page has its own controller, to avoid reporting the same code in every single controller, I was thinking of inserting the code that counts notifications in BaseController.php
in this way, each individual controller will already have its own notification count.

or is it better to not touch the BaseController.php controller and create a class, count, and call the class in every single controller and function?

I was thinking of putting the counting code here, and doing something like this, in BaseController.php:

Code:
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.
        if (auth()->loggedin()) {
            $session = session();
            if (!$session->has('total')) {
                $carrelloModel = new CarrelloModel();
                $total = $carrelloModel->contaProdotti(auth()->user()->id);
                $session->set('total', $total);
            }
        }
        // E.g.: $this->session = \Config\Services::session();
    }

Validation is_unique cannot be configured with dot_syntax

$
0
0
How do I check the array of values (mark)?
PHP Code:
        [
            '*.mark' => [
                'label' => 'App.link.mark',
                'rules' => 'required|is_unique[link.mark,mark,{mark}]',
            ],
            '*.url' => [
                'label' => 'App.link.url',
                'rules' => 'required|min_length[7]|max_length[255]',
            ],
        ]; 

How ignore updating insertId from a DBQuery event?

$
0
0
I have an event on DBQuery which inserts a log record into another table on most insert/update/delete queries.

Because of this, it appears that when I call a model's insert() or fetch the insertId from a query, it returns the id of the log record instead of the original record.

I was wondering if there was a solution or workaround to this?

Ci4: 4.1.9

Note: This thread appears to have had the same issue:

https://forum.codeigniter.com/showthread...pid=406593

resolve ajax failure in codeigniter 3 view page?

$
0
0
in codeigniter 3 view page i have following to edit comments :

PHP Code:
function toggleEdit(commentId) {
    
    console
.log("Toggling edit for comment ID:"commentId);
    var commentText document.getElementById('comment-' commentId);
    var editTextarea document.getElementById('edit-comment-' commentId);
    var button document.getElementById('edit-save-button-' commentId);

    if (editTextarea.style.display === 'none') {
        // Switch to edit mode
        console.log("Switching to edit mode");
        commentText.style.display 'none';
        editTextarea.style.display 'block';
        button.textContent 'Save';
    } else {
        // Save the edited comment
        console.log("Saving edited comment");
        var editedComment editTextarea.value;
        console.log(" edited comment is:",editTextarea.value);
        console.log(" controller method:",'<?=$user_base_url?>/profil/save_comment');

        $.ajax({

            url'<?=$user_base_url?>/profil/save_comment',//+ new Date().getTime(),
            type'POST',
            data: {
                idcommentId,
                commenteditedComment
            
},
            success: function(response) {
                console.log("AJAX call successful");
                console.log(response);
                if (response.success) {
                    console.log("Comment saved successfully");
                    // Update the displayed comment and switch back to view mode
                    commentText.innerHTML editedComment.replace(/\n/g'<br>');
                    commentText.style.display 'block';
                    editTextarea.style.display 'none';
                    button.textContent 'Edit';
                } else {
                    console.error("Error saving comment: "response);
                    alert('Error saving comment.');
                }
            },
            error: function(xhrstatuserror) {
                console.error("AJAX call failed:"statuserror);
                alert('AJAX call failed.');
            }
        });
    }

here i want to add a part that users are adding their comments for page content with ability to edit the comments.

but ajax failed to activated while get_csrf_token/?_=1720512009436 is retrived successfully when i check.

how should i resolve that?

PageController for GETs + DataPointController for POSTs?

$
0
0
I'm new CI and the MVC pattern. I'm making a simple app to track my nicotine intake by storing usage into a database and displaying that data in the form of charts (using Chart.js)

Without getting too detailed, I have this in my app/Config/Routes.php:

PHP Code:
$routes->get('/new''PageController::newDataForm', ['filter' => ['authfilter''csrf']]);
$routes->post('/new''DataPointController::newDataEndpoint', ['filter' => ['authfilter''csrf']]);
// eg: GET   PageController::updateDataForm
//     POST  DataPointController:updateDataEndpoint
//     GET   PageController::deleteDataForm
//     POST  DataPointController:deleteDataEndpoint
// $routes->post('/api/new', 'APIController::newDataEndpoint'); // TODO: will be used for version 2 of the app: a Svelte/Solid.js/etc frontend which makes RESTful calls to CI API endpoints 


I currently house my HTML forms inside PageController as xxxxxxxForm(). The forms POST to DataPointController::xxxxxxEndpoint(), where it interacts with a DataPointModel to add the data into the DB.


Is the above practice considered abnormal or bad? Should I rewrite the code to have all my HTML-related code and Database-inserting-code housed within PageController (and get rid of DataPointController)? 
When I originally created this app, it seemed to make sense to me because the HTML forms are all in a "PageController" and the database stuff is all in a "DataPointController".... but now I'm not so sure. The problem I perceive now is when invalid data gets POSTed, I have to `return` from DataPointController using `return (new PageController())->newDataForm()` instead of `$this->newDataForm()`.
I have a feeling that this is inefficient and/or using more memory than necessary since its creating a new instance of PageController from within DataPointController.

Thoughts? Recommendations?

Codeigniter URI like https://codeigniter.com/' error exception

$
0
0
This is a weary sample like https://codeigniter.com/' if I add slash plus quote '
Code:
https://codeigniter.com/'
it throws an exception why ??? Oooops

it should show 404 not that that is bad

just copy this CI 
Code:
https://codeigniter.com/'
as it and paste it into your browser and you will see

Free illustrations for websites

DBPrefix causing double prefixes

$
0
0
I use version 4.4.7, but the same problem occurs in version 4.5.2. And database is postgres
When I set the environment variable database.default.DBPrefix = foo.
if I call the model repeatedly (like foreach), the 'from' clause in the SQL statement will show double prefixes.

PHP Code:
$tutorModel model(TutorModel::class);

foreach (
$result as $key => $value) {

     $result[$key]->tutors $tutorModel->select("name")
                                      ->join('course_tutors','course_tutors.tutor_id=tutors.id')
                                      ->where('course_id',$value->course_id)
                                      ->orderBy('order','asc')
                                      ->findAll();


And it will return server error because  cross-database references are not implemented: "select name from foo.foo.tutors where..."

Is there a workaround?

Is there a way to create a symbolic link within the public folder?

$
0
0
Hi,
I am working on an application that will enable admin users to upload images to be used inside posts. Is there a way to tell the application that for example the public/images folder is not inside the public folder but let's say /home/user/myproject/sharedassets/images which is the server's path (the codeigniter application being inside the folder myproject) ? 
Thanks for your help

"updated_at" field filled during an insert operation

$
0
0
the updated_at field filled during an insert operation, not only created_at field. Even though I only intend to insert into the database. is it normal?

thanks.

best practice

$
0
0
Hi i have a question ,
i must write two function to print label from 2 controller , it's better to create model (without db table) or ?

Codeigniter Tasks do not work with cronjob

$
0
0
Hi, I have a question.
Firstly, this package work fine if we run manually from terminal. but when i implement it in cron its like php spark bla:bla do nothing. I can not reproduce any errors in cron.
my command in cron: * * * * * cd /Applications/MAMP/htdocs/projects/cosmos && touch taskstarting.php && php spark tasks:run && touch taskstopping.php >> /dev/null 2>&1
I can see taskstarting.php inside my project. but, I can not see taskstopping.php inside my project that indicated php spark do nothing in cron.
Let me know how to achieve this, Thanks in advance.

Reallow the use of Sessions in Config Files

$
0
0
Prior to version 4.5 of Codeigniter, it was possible to open the session and check for some Session Variables inside the Config Files.
This was helpfull for change the CI Enviroment for some users ( e.g. as Admin it was possible to have the Debugbar while all other users dont got it)
After 4.5 this is not possible anymore without creating an own Boot.php, this is caused by a changed Boot Order in the Function BootWeb.

Non Working Version:
PHP Code:
public static function bootWeb(Paths $paths): int
    
{
        static::definePathConstants($paths);
        if (! defined('APP_NAMESPACE')) {
            static::loadConstants();
        }
        static::checkMissingExtensions();

        static::loadDotEnv($paths);
        static::defineEnvironment();
        static::loadEnvironmentBootstrap($paths);

        static::loadCommonFunctions();
        static::loadAutoloader();
        static::setExceptionHandler();
        static::initializeKint();

        $configCacheEnabled class_exists(Optimize::class)
            && (new Optimize())->configCacheEnabled;
        if ($configCacheEnabled) {
            $factoriesCache = static::loadConfigCache();
        }

        static::autoloadHelpers();

        $app = static::initializeCodeIgniter();
        static::runCodeIgniter($app);

        if ($configCacheEnabled) {
            static::saveConfigCache($factoriesCache);
        }

        // Exits the application, setting the exit code for CLI-based
        // applications that might be watching.
        return EXIT_SUCCESS;
    





It could be fixed by change the Boot Order to the following:

PHP Code:
public static function bootWeb(Paths $paths): int
    
{
        static::definePathConstants($paths);
        if (! defined('APP_NAMESPACE')) {
            static::loadConstants();
        }
        static::checkMissingExtensions();

        static::loadDotEnv($paths);
        static::defineEnvironment();
        
        
static::loadCommonFunctions();
        static::loadAutoloader();
        static::setExceptionHandler();
        static::loadEnvironmentBootstrap($paths);
        static::initializeKint();

        $configCacheEnabled class_exists(Optimize::class)
            && (new Optimize())->configCacheEnabled;
        if ($configCacheEnabled) {
            $factoriesCache = static::loadConfigCache();
        }

        static::autoloadHelpers();

        $app = static::initializeCodeIgniter();
        
        
static::runCodeIgniter($app);

        if ($configCacheEnabled) {
            static::saveConfigCache($factoriesCache);
        }

        // Exits the application, setting the exit code for CLI-based
        // applications that might be watching.
        return EXIT_SUCCESS;
    

JavaScript Fetch returns an error when in development mode.

$
0
0
I want to test my API call using CI4. In development mode, I encountered errors in the browser console. How can I fix this?

.env
PHP Code:
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------

CI_ENVIRONMENT development 

Controller: TesApi.php
PHP Code:
public function tesApi()
    {
        $data = ['id' => 1];
        return json_encode($data);
    

View: tesapi.php
PHP Code:
<body>
    Api test using fetch when in development mode
    
<script>
    fetch('tesapi')
        .then(response => response.json())
        .then(json => console.log(json));
    </script>
</
body

Error in browser console:
Code:
Uncaught (in promise) SyntaxError: Unexpected token '<', "<script cl"... is not valid JSON

Code:
<script class="kint-rich-script">void 0===window.kintShared&&(window.kintShared=function(){"use strict";var e={dedupe:function(e,n){return[].forEach.call(document.querySelectorAll(e),function(e){e!==(n=n&&n.ownerDocument.contains(n)?n:e)&&e.parentNode.removeChild(e)}),n},runOnce:function(e){"complete"===document.readyState?e():window.addEventListener("load",e)}};return window.addEventListener("click",function(e){var n;e.target.classList.contains("kint-ide-link")&&((n=new XMLHttpRequest).open("GET",e.target.href),n.send(null),e.preventDefault())}),e}());
void 0===window.kintRich&&(window.kintRich=function(){"use strict";var l....

Allow Toolbar for HTML response only?

Filter Customization for disallowed characters

$
0
0
Hello everyone. There was a problem with customizing the filter for disallowed characters. If I understand correctly, the exception is triggered before the standard filters are applied. 

PHP Code:
public function before(RequestInterface $request$arguments null)
    {
        $uri $request->getUri()->getPath();

        if ( ! preg_match('/^[' config(App::class)->permittedURIChars ']+$/i'$uri)) {
            if ($request->getUri()->getSegment(1) === 'api') {
                return Services::response()->setStatusCode(404);
            }

            return redirect()->to('/page-404');
        }
    

in App/Config/Filters
PHP Code:
public array $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
            // 'invalidchars',
            'uri'
        ],
        'after'  => [
            // 'honeypot',
            // 'secureheaders',
        ],
    ]; 

The code of my filter is shown below. How to solve this problem correctly without violating the logic of the framework?
Viewing all 14343 articles
Browse latest View live


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