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

[DATABASE] - Query Builder for LOCKING Query Select

$
0
0
I have many request at same time, with TRANSACTION make unique string increment like INVCLIENT2024070001 - 9999. Without LOCKING query select num row last format can be duplicate.

SUCCESS
PHP Code:
$resultKrediturCountData $this->db->query("SELECT COUNT(ad.debitor_no) AS debitor_count FROM askred_debitor ad WHERE ad.creditor_no = ? FOR SHARE", [$creditor_no]); 

FAILED (Duplicate)
PHP Code:
$this->db->select("COUNT(ad.debitor_no) AS debitor_count");
$this->db->from('askred_debitor ad');
$this->db->where("ad.creditor_no"$creditor_no);

$resultKrediturCountData $this->db->get(); 

Maybe this can build with query builder like :
PHP Code:
$this->db->select("COUNT(ad.debitor_no) AS debitor_count");
$this->db->from('askred_debitor ad');
$this->db->where("ad.creditor_no"$creditor_no);
$this->db->for("SHARE"); // or $this->db->for("UPDATE");

$resultKrediturCountData $this->db->get(); 

Reference LOCKING :
  1. https://dev.mysql.com/doc/refman/8.4/en/...reads.html
  2. https://www.postgresql.org/docs/current/...CKING-ROWS
  3. https://www.sqlite.org/lockingv3.html

mpdf in models

$
0
0
Hi,
funny enough, last year i made a tool with a 2023 beginning ci4 release in which i used mpdf a lot in models, worked like a charm
now i'm working on anothe tool with 2024 beginning release and if i do exactly the same thing in a model, that kind of thing
PHP Code:
$mpdf = new Mpdf(['mode' => 'utf-8']);
$mpdf->WriteHTML($html);
$this->response->setHeader("Content-Type""application/pdf");
$mpdf->OutputFile('./assets/files/' $filename); 
i get an error
You must set the database table to be used with your query
of course i have the necessay use \Mpdf\Mpdf; and two requests in the method, if i comment the mpdf part, everything works fine as, if i remember well model are made to deal with data... and files
just something more, if i put exactly the same code in the controller, everything goes well, the file is created and my queies in the model work fin too, only little caveat, even if after the mpdf code my controller method ends with a return view, it returns... an empty pdf to the browser completely ignoring my return view statement

so i wonder, what went wrong within a year Smile

eager to have your insights about all this

have a nice day

Hi again,

found out by myself, it does'nt like, at all... this line
PHP Code:
$this->response->setHeader("Content-Type""application/pdf"); 

commenting this line CI doesn't ask me for a datatable anymore... and it works fine in a model as in a librairy

thanks for those who took time to read my poor english Smile
have a nice day

Mastering Git: 30 Essential Commands Every Developer Should Know

moving ci4 app from localhost to onliine test server

$
0
0
Can anybody guide me how to duplicate my localhost development app to a remote  test server ?
Are there any HowTo's or guidelines?

I can not disable CSRF regenerate or randomize

$
0
0
Hello. I have a problem with concurrent Ajax requests.

As long as I perform one ajax at a time, there is no problem.
Sometimes, one ajax call starts before the previous one finalizes. The first ajax call replaces the csrf hash in the server but the second one reaches the server with the old csrf hash. Therefore it throws a 403 error.
My app requires concurrent ajax calls time to time. So, I can not avoid it.

My CSRF settings are;
App\Config\Security.php

PHP Code:
public string $csrfProtection 'session';
public 
bool $tokenRandomize false;
public 
bool $regenerate false;
public 
bool $redirect false;
public 
string $samesite 'Lax'

So, randomize and regenerate are false. But it doesn't change anything. csrf hash changes everytime. So, in case of a concurrent ajax call or if one ajax call fails for some reason, the browser can't get the correct csrf hash and therefore it blocks the ajax calls forever.

CI4 version is : 4.4.6

Am I missing something?

50 Best Websites for Web Design Inspiration and Ideas

DevHunt, Best way to promote your Dev Tool or Open Source project

CodeIgniter v4.5.4 bug fix released


Using php 8.3

$
0
0
I have a number of legacy websites built on codeigniter 3, originally using php 7.4.33. I am now running wamp on local server with php 8.3 and getting errors - no surprises. Is there a straightforward approach to update codeigniter 3 code or a guidance website to help me make changes so it will run correctly with php 3.8?

CodeIgniter Web Application Blueprints

$
0
0
[Image: ci-book-rob-foster.png]

The book mentioned above was published in 2015 and written by Rob Foster. Is he in this forum?

Send success message to user after logout

$
0
0
PHP Code:
public function logout()
    {
        session()->set('user');
        session()->destroy();
        session()->setFlashdata('success''logout successful!');
        return redirect('/');
    

Goal: when the user logs out, the application displays the message "logout successful." Problem: How can the flash message be displayed while the session has already been destroyed?

sitemap question

$
0
0
I have a dynamic website designed with Codeigniter 3 and I am working on the sitemap part as a newbie.
I found the library sitemap-php from evert/sitemap-php but I can't make it run.
From now this is what I did, I put the Sitemap.php file into my library folder
In my controller I enter the following
PHP Code:
public function Sitemap(){
$this->load->library('Sitemap'); 
$sitemap = new Sitemap('https://www.mywebsite.com');
$sitemap->setPath('/public_html/Sitemap/'); // I created a folder Sitemap into my public folder
$sitemap->setFilename('sitemap');
$sitemap->addItem('/''1.0''daily''Today');
$sitemap->createSitemapIndex('https://www.mywebsite.com/sitemap/''Today');} 

Then when I go to https://www.mywebsite.com/sitemap/, I have an error 404.

Could you guide me to solve my issue.
Thanks

Codeigniter 3.2.0 problem with php 8.2

$
0
0
I have a legacy website originally using CI 3.2 but throwing errors with php 8.2, so I found the website https://github.com/pocketarc/codeigniter/ offering modified files. I have replaced the system files and then got an error:
 
Warning: include(C:\wamp64\www\SPS\application\views\errors\html\error_php.php): Failed to open stream: No such file or directory in C:\wamp64\www\SPS\system\core\Exceptions.php on line 281

From Google advice I then created a folder/file; views/errors/html/error_php.php with contents '<?php
echo "TEST";
?>'

but now the page just shows TEST - and perhaps it should. How can I now get back to normal? I don't understand why the Exceptions.php file is throwing an error at all.

Any advice gratefully received...

Neat way to have CI4 updated with composer

$
0
0
Hello guys, I usually start a project using composer to have the appstarter, and add libraries like phpmailler. I want to have my CI4 always updated so I come with this little script using composer that I think that could be very useful:
composer.json
Code:
{
    "name": "codeigniter4/appstarter",
    "description": "CodeIgniter4 starter app",
    "license": "MIT",
    "type": "project",
    "homepage": "https://codeigniter.com",
    "support":
    {
        "forum": "https://forum.codeigniter.com/",
        "source": "https://github.com/codeigniter4/CodeIgniter4",
        "slack": "https://codeigniterchat.slack.com"
    },
    "require":
    {
        "php": "^8.1",
        "codeigniter4/framework": "^4.0",
        "codeigniter4/translations": "*",
        "dompdf/dompdf": "^3.0",
        "phpmailer/phpmailer": "^6.9",
        "twbs/bootstrap": "^5.3"
    },
    "require-dev":
    {
        "fakerphp/faker": "^1.9",
        "mikey179/vfsstream": "^1.6",
        "phpunit/phpunit": "^10.5.16"
    },
    "autoload":
    {
        "psr-4":
        {
            "App\\": "app/",
            "Config\\": "app/Config"
        },
        "exclude-from-classmap":
        [
            "**/Database/Migrations/**"
        ]
    },
    "autoload-dev":
    {
        "psr-4":
        {
            "Tests\\Support\\": "tests/_support"
        }
    },
    "config":
    {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "scripts":
    {
        "test": "phpunit",
        "post-install-cmd":
        [
            "@updatebootstrap",
            "@updateci"
        ],
        "post-update-cmd":
        [
            "@updatebootstrap",
            "@updateci"
        ],
        "updatebootstrap":
        [
            "php updatebootstrap.php"
        ],
        "updateci":
        [
            "php updateci.php"
        ]
    }
}
updatebootstrap.php
PHP Code:
<?php

 
//Inicio copiar CSS do bootstrap
 
$arr_orig = ['vendor','twbs','bootstrap','dist','css'];
 
$origem joinDIRECTORY_SEPARATOR$arr_orig ) . DIRECTORY_SEPARATOR "*.*";

 
$arr_dest = ['public','css','bootstrap'];
 
$destino  joinDIRECTORY_SEPARATOR$arr_dest );
 
//echo($origem);
 
if( DIRECTORY_SEPARATOR == '/')
 {
 
exec("cp -r " $origem " " $destino);
 }
 else
 {
 
exec("copy " $origem " " $destino);
 }
 
//Fim copiar CSS do bootstrap


 //Inicio copiar JS do bootstrap
 
$arr_orig = ['vendor','twbs','bootstrap','dist','js'];
 
$origem joinDIRECTORY_SEPARATOR$arr_orig ) . DIRECTORY_SEPARATOR "*.*";

 
$arr_dest = ['public','js','bootstrap'];
 
$destino  joinDIRECTORY_SEPARATOR$arr_dest );
 
//echo($origem);
 
if( DIRECTORY_SEPARATOR == '/' )
 {
 
exec("cp -r " $origem " " $destino);
 }
 else
 {
 
exec("copy " $origem " " $destino);
 }
 
//Fim copiar JS do bootstrap


?>
updateci.php
PHP Code:
<?php
//criar pasta para backup
if( ! is_dir('bknc') )
{
exec"mkdir bknc" );
}
else{
echo(
"ja existe a bknc" PHP_EOL);
}
//copiar ficheiros do ci
if( DIRECTORY_SEPARATOR == '/' )
{
exec('cp app/Config/App.php bknc/App.php');
exec('cp app/Controllers/BaseController.php bknc/BaseController.php');
exec('cp app/Config/Constants.php bknc/Constants.php');
exec('cp app/Config/Database.php bknc/Database.php');
exec('cp app/Config/Filters.php bknc/Filters.php');
exec('cp app/Config/Logger.php bknc/Logger.php');
exec('cp app/Config/Routes.php bknc/Routes.php');
exec('cp app/Config/Session.php bknc/Session.php');
exec('cp composer.json bknc/composer.json');
exec('cp -TR  vendor/codeigniter4/framework/ . ');
exec('cp -TR  vendor/codeigniter4/translations/Language ./app/Language/');
exec('chmod -R 775 writable/debugbar');
//inicio repor ficheiros de bknc
exec('cp bknc/App.php app/Config/App.php ');
exec('cp bknc/BaseController.php app/Controllers/BaseController.php ');
exec('cp bknc/Constants.php app/Config/Constants.php ');
exec('cp bknc/Database.php app/Config/Database.php ');
exec('cp bknc/Filters.php app/Config/Filters.php ');
exec('cp bknc/Logger.php app/Config/Logger.php ');
exec('cp bknc/Routes.php app/Config/Routes.php ');
exec('cp bknc/Session.php app/Config/Session.php ');
exec('cp bknc/composer.json composer.json ');
//fim repor ficheiros de bknc
exec('rm -rf bknc/*.*');
}
else
{
exec('copy app\\Config\\App.php bknc\\App.php /Y');
exec('copy app\\Controllers\\BaseController.php bknc\\BaseController.php /Y');
exec('copy app\\Config\\Constants.php bknc\\Constants.php /Y');
exec('copy app\\Config\\Database.php bknc\\Database.php /Y');
exec('copy app\\Config\\Filters.php bknc\\Filters.php /Y');
exec('copy app\\Config\\Logger.php bknc\\Logger.php /Y');
exec('copy app\\Config\\Routes.php bknc\\Routes.php /Y');
exec('copy app\\Config\\Session.php bknc\\Session.php /Y');
exec('copy composer.json bknc\\composer.json /Y');
exec('xcopy vendor\\codeigniter4\\framework\\ .  /S /Y');
exec('xcopy vendor\\codeigniter4\\translations\\Language\\. .\\app\\Language\\  /S /Y');
//repor ficheiros
exec('copy bknc\\App.php app\\Config\\App.php /Y');
exec('copy bknc\\BaseController.php app\\Controllers\\BaseController.php /Y');
exec('copy bknc\\Constants.php app\\Config\\Constants.php /Y');
exec('copy bknc\\Database.php app\\Config\\Database.php /Y');
exec('copy bknc\\Filters.php app\\Config\\Filters.php /Y');
exec('copy bknc\\Logger.php app\\Config\\Logger.php /Y');
exec('copy bknc\\Routes.php app\\Config\\Routes.php /Y');
exec('copy bknc\\Session.php app\\Config\\Session.php /Y');
exec('copy bknc\\composer.json composer.json /Y');
}
?>



I hope that this could be helpful for yours projects

Cheers!

Shield: how to create user-permission level ?

$
0
0
Hey guys,
I would like to ask about how to create any custom user-permission using shield (I don't know the keywords Huh ).
For example: 
- I have a table for brands, say it's brand A, B, C, and so on.
- I want to set the exact user, let's say 'John' have access only for brand A and C. and throws forbidden access if tries to access the other brand.

Many thanks!

CURL file upload

$
0
0
Hi,
I am trying to upload images via and API using CI CURL Request class. However, Codeigniter errors "CodeIgniter\HTTP\Exceptions\HTTPException 22 : The requested URL returned error: 400" referring to line 'file=>$myfile'

PHP Code:
$image = \Config\Services::image();

$data['job_id'] = $this->request->getPost('job_id');
$imagefiles $this->request->getFiles();

$image_write_path $_SERVER['DOCUMENT_ROOT'].'/images/projects/task_no_'.$data['job_id'];

if (!
file_exists($image_write_path)) {
    mkdir($image_write_path0777true);
}

$client service('curlrequest', [
    'baseURI' => 'BASE OF API PATH',
]);


foreach(
$imagefiles['images'] as $img) {
    list($width$height) = getimagesize($img);
    $size=filesize($img);

    //save temporary file and move image (with original image name) to server filesystem
        if(! $img->hasMoved()) {
    $originalName $img->getClientName();
    $filename pathinfo($originalNamePATHINFO_FILENAME);

    $filepath WRITEPATH 'uploads/' $img->store();
    $new_file_put$image_write_path.'/'.$filename.'.png';
    $image_view_path base_url().'/images/projects/task_no_'.$data['job_id'].'/'.$filename.'.png';

    if( ! \Config\Services::image('imagick')
        ->withFile($filepath)
        ->convert(IMAGETYPE_PNG)
        ->save($new_file_put)) {
        unlink($filepath);
    }

    $myfile = new \CURLFile($image_view_path);

    $upload_image $client->post('API ENDPOINT',
        [
            'headers' => [
            'Content-Type: multipart',
            'Authorization' => ['***MYTOKEN***'],
            ],
            [
            'file' => $myfile
            
]
        ]
    );

    $response json_decode($body);
    log_message('notice''[SUCCESS] {file}-{line}, RESPONSE - '.print_r($responsetrue));
}; 

Above throw the HTTP errors!!

However, using native curl with  CI \CURLfile (at bottom) I do not get the error.
PHP Code:
$myfile = new \CURLFile($image_view_path); 

PHP Code:
foreach($imagefiles['images'] as $img) {
    list($width$height) = getimagesize($img);
    $size=filesize($img);

    //save temporary file and move image (with original image name) to server filesystem
        if(! $img->hasMoved()) {
    $originalName $img->getClientName();
    $filename pathinfo($originalNamePATHINFO_FILENAME);

    $filepath WRITEPATH 'uploads/' $img->store();
    $new_file_put$image_write_path.'/'.$filename.'.png';
    $image_view_path base_url().'/images/projects/task_no_'.$data['job_id'].'/'.$filename.'.png';

    if( ! \Config\Services::image('imagick')
        ->withFile($filepath)
        ->convert(IMAGETYPE_PNG)
        ->save($new_file_put)) {
        unlink($filepath);
    }

    $myfile = new \CURLFile($image_view_path);
    $curl curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => '/FULL/API/PATH',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file'=> $myfile),
        CURLOPT_HTTPHEADER => array(
        'Content-Type: multipart/form-data',
        'Authorization: ***MY TOKEN***'
    ),
));

$response curl_exec($curl);

curl_close($curl); 
 
log_message('notice''[SUCCESS] {file}-{line}, RESPONSE - '.print_r($responsetrue)); 

Above is successful.
Any help would be appreciated.

file->move returns 1 not a file

$
0
0
ci 4.5.1. I'm using as per the docs,
PHP Code:
$file=$file->move('todir','newname',true);
   
log_message('debug',$file->getSize());

   
the file is moved correctly.
   
according to the docs and line 153 of system/files/file.php$file->move(...) returns a File [return new self($destination)]
   
but $file->getSize() crashes  saying "Call to a member function getSize() on true" 
Many thanks, Bill

Calculate show points in SQL

$
0
0
Hi,

This query works now, but it needs to be more specific for the customer. I also looked to see if I can adjust the data in the (PHP) array, but I prefer to pull it out of the query so that sorting continues to work properly. I've been stuck on this part for a while now. SQL statements are not my specialty.

Now it shows the total points well, but what I want to achieve is the following:

    It must count the points of the national show (type 1) first, since an animal participates in a national show a maximum of 1 time per year.
    Then it must select the 3 highest points and then stop counting (LIMIT).

So when an animal has not yet participated in a national show, it takes the 3 highest scores and if one has participated, it still takes the 3 highest scores, but the national one must be above that.

(show_participants.participant_category = "1" is now static, but this is for testing. There are 10 categories)

Hope it's clear, thanks a lot in advance.

Code:
SELECT Sum(participant_match_points) AS participant_total_points,
      shows.show_type,
      show_types.type_name,
      animals.born,
      animals.registrationnumber,
      owners.ownernumber
FROM  show_participants
      INNER JOIN animals
              ON animals.registrationnumber =
                  show_participants.participant_animal
      INNER JOIN show_categories
              ON show_participants.participant_category =
                  show_categories.category_id
      INNER JOIN owners
              ON animals.registrationnumber = owners.registrationnumber
      INNER JOIN shows
              ON show_participants.participant_show = shows.show_id
      INNER JOIN show_types
              ON show_types.type_id = shows.show_type
WHERE  show_participants.participant_category = "1"
GROUP  BY show_participants.participant_animal
ORDER  BY participant_total_points DESC

[Image: 2c5b338acaa556e4296dae4f6a80f0131a2bfca7.png]

$validationRules is there a documentation with all the references we can use?

$
0
0
Hi, I always find myself browsing the web to find how to write validation rules. Is there a documentation somewhere I haven't yet found that might list all the available rules we can use depending on the database expected data format? Or can I find it within the code? (and maybe suggest/write a little addition in the documentation that could be useful for beginners and people like me?)
Thanks

(I found this from some versions ago that is a beginning https://www.codeigniter.com/userguide2/l...ereference but I think there is more to it and there might be some changes)

Help: How to integrate codeigniter with Sneat Free laravel?

Viewing all 14343 articles
Browse latest View live