Welcome Guest, Not a member yet? Register   Sign In
  Writing Good SQL Code
Posted by: InsiteFX - 07-31-2022, 12:47 PM - No Replies

Best Practices for Writing Good SQL Code


  Setting a dynamic default controller.
Posted by: Seed - 07-31-2022, 03:06 AM - No Replies

Hello,
I'm having troubles trying to make a unique installation of CodeIgniter for all my SVN deposits.
I'm using the latest version of CodeIgniter.
Here is how it is installed :
/home/libs_web/codeigniter/

Here is where my deposits are :
/home/web/xxxxx/ <- For that example, let's take /kpi/ for example (/home/web/kpi/).
Here is how I configured my /home/libs_web/codeigniter/application/config/routes.php :

PHP Code:
$ci_explodeScriptFilename explode('/'$_SERVER['SCRIPT_FILENAME']);
unset(
$ci_explodeScriptFilename[count($ci_explodeScriptFilename) - 1]);

$ci_defaultPath implode('/'$ci_explodeScriptFilename);

$route['default_controller'] = $ci_defaultPath.'/controllers/defaultController';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE

Doing so I do hope this work like that :
/home/web/kpi/ -> /home/web/kpi/controllers/defaultController.php
/home/web/example/ -> /home/web/example/controllers/defaultController.php

Here is how I configured my /home/web/kpi/index.php (for system/app) :

PHP Code:
$system_path '/home/libs_web/codeigniter/system';
$application_folder '/home/libs_web/codeigniter/application'

And here is how I developped my /home/web/kpi/controllers/defaultController.php :

PHP Code:
defined('BASEPATH') OR exit('404');

class 
defaultController extends CI_Controller {
 private 
$view "/home/web/kpi/views/";
 private 
$model "/home/web/kpi/models/";
 
 public function 
view($page 'home') {
        if(!file_exists($this->$view.$page.'.php')) {
 
show_404();
        }
 
 
$data = array();
 
 
$this->load->view('templates/header');
        $this->load->view($this->$view.$page);
        $this->load->view('templates/footer');
 }


But here is the result :

[Image: 1659261891-3628.png]

Also, editing the show_404() to make an echo, or just make an echo then exit on top of my defaultController, or on top of the default codeIgniter controller (welcome) doesn't change anything.
I wonder if my Controller is actually found by CodeIgniter.

I just started CodeIgniter, actually on that step : https://codeigniter.com/userguide3/tutor...pages.html
Maybe I just missed something ?


  Basic usage how-to for Shield authentication
Posted by: Tbronson - 07-30-2022, 08:22 PM - Replies (3)

I have Shield installed. Registration is working. 

Need simple instructions on how to implement for basic operation:

1. How do I set up user management: add, modify and delete accounts, assign and modify group?

2. How do I restrict access to individual pages and parts of pages?

Thanks!


  Codeigniter 4 Rest API - 301 Moved Permanently
Posted by: FreedomAce - 07-30-2022, 08:16 PM - Replies (1)

I have Codeigniter 4 web app that run REST API with firebase/php-jwt on Laragon 5.0.0210523 environment that run Apache-2.4.47, PHP-8.1.7, and MongoDB-4.0.28. I followed a tutorial and it works fine both server REST API and it REST client. After day work, i stop laragon server. In the next day i try run REST API server then tried then run the client but it failed and gave 301 moved permanently error, but i still can access it from postman.

REST API server side

composer.json

Code:
***
"require": {
        "php": "^7.4 || ^8.0",
        "codeigniter4/framework": "^4.0",
        "mongodb/mongodb": "^1.12",
        "firebase/php-jwt": "^6.3"
    },
***

.env file
Code:
***
JWT_SECRET_KEY = SomeThing$089
JWT_TIME_TO_LIVE = 3600

app.baseURL = 'http://ci4-api.localhost'
***

Route.php
PHP Code:
***
$routes->get('/''Home::index');

$routes->resource('api/users');

$routes->post('api/auth', [\App\Controllers\Api\Auth::class, 'index']);
*** 

JWT_Helper.php
PHP Code:
use App\Models\ModelUsers;
use 
Firebase\JWT\JWT;
use 
Firebase\JWT\Key;

/**
 * @throws Exception
 */
function getJWT($authHeader)
{
    if (is_null($authHeader)){
        throw new Exception("Authentication JWT failed");
    }
    return explode(" "$authHeader)[1];
}

function 
validateJWT($encodedToken)
{
    $key getenv('JWT_SECRET_KEY');
    $decodedToken JWT::decode($encodedToken, new Key($key'HS256'));
    $modelUsers = new ModelUsers();
    $modelUsers->get_email($decodedToken->email);
}

function 
createJWT($email): string
{
    $timeRequest time();
    $timeToken getenv('JWT_TIME_TO_LIVE');
    $timeExpired $timeRequest $timeToken;
    $payload = [
        'email' => $email,
        'iat' => $timeRequest,
        'exp' => $timeExpired,
    ];
    return JWT::encode($payloadgetenv('JWT_SECRET_KEY'), 'HS256');


FilterJWT.php
PHP Code:
namespace App\Filters;

use 
CodeIgniter\API\ResponseTrait;
use 
CodeIgniter\Filters\FilterInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Config\Services;
use 
Exception;

class 
FilterJWT implements FilterInterface
{
    use ResponseTrait;

    public function before(RequestInterface $request$arguments null)
    {
        $header $request->getServer('HTTP_AUTHORIZATION');
        try {
            helper('jwt');
            $encodedToken getJWT($header);
            validateJWT($encodedToken);
            return $request;
        } catch (Exception $ex) {
            return Services::response()->setJSON(
                [
                    'error' => $ex->getMessage(),
                ]
            )->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
        }
    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        // TODO: Implement after() method.
    }


Filters.php
PHP Code:
***
public 
$aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'auth' => FilterJWT::class,
    ];
public 
$filters = [
        'auth' => [
            'before' => [
                'api/users/*',
                'api/users'
            ]
        ]
    ];
*** 

ModelUsers.php
PHP Code:
namespace App\Models;

use 
App\Libraries\MongoDb;

class 
ModelUsers
{
    private $database 'ci4_api';
    private $collection 'user';
    private $conn;

    function __construct()
    {
        $mongodb = new MongoDb();
        $this->conn $mongodb->getConn();
    }

    function get_user_list() {
        try {

            $filter = [];
            $query = new \MongoDB\Driver\Query($filter);

            $result $this->conn->executeQuery($this->database'.' $this->collection$query);

            return $result->toArray();

        } catch (\MongoDB\Driver\Exception\RuntimeException $ex) {
            show_error('Error while fetching users: ' $ex->getMessage(), 500);
        }
    }
*** 

Auth.php
PHP Code:
namespace App\Controllers\Api;

use 
App\Controllers\BaseController;
use 
App\Models\ModelUsers;
use 
CodeIgniter\API\ResponseTrait;
use 
CodeIgniter\Validation\Validation;
use 
Config\Services;

class 
Auth extends BaseController
{
    use ResponseTrait;

    private ModelUsers $model;
    private Validation $validation;

    function __construct()
    {
        $this->model = new ModelUsers();
        $this->validation Services::validation();
    }

    public function index()
    {
        $email $this->request->getVar('email');
        $password $this->request->getVar('password');
        $password_hash password_hash($passwordPASSWORD_DEFAULT);

        $data1 = [
            'email' => $email,
            'password' => $password
        
];

        if (!$this->validation->run($data1'login')) {

            $errors $this->validation->getErrors();

            $response = [
                'status' => 201,
                'error' => null,
                'messages' => [
                    'errors' => [
                        $errors
                    
]
                ],
            ];

            return $this->respond($response);
        }

        $data1 $this->model->get_email($email);
        //return $this->respond($data1, 200);

        if (!$data1) {
            $response = [
                'status' => 201,
                'error' => null,
                'messages' => [
                    'error' => 'Data user atau password tidak ada1'
                ],
            ];

            return $this->respond($response200);
        }

        $password_user $data1->password;

        if (password_verify($password_hash$password_user) != 0){
            $response = [
                'status' => 201,
                'error' => null,
                'messages' => [
                    'error' => 'Data user atau password tidak ada2'
                ],
            ];

            return $this->respond($response200);
        }

        helper('jwt');
        $response = [
            'message' => 'Auth berhasil dilakukan',
            'data' => $data1,
            'access_token' => createJWT($email)
        ];

        return $this->respond($response200);
    }
*** 

users.php
PHP Code:
namespace App\Controllers\Api;

use 
App\Controllers\BaseController;
use 
App\Models\ModelUsers;
use 
CodeIgniter\API\ResponseTrait;
use 
CodeIgniter\HTTP\Response;
use 
CodeIgniter\Validation\Validation;
use 
Config\Services;

class 
Users extends BaseController
{
    use ResponseTrait;

    private ModelUsers $model;
    private Validation $validation;

    function __construct()
    {
        $this->model = new ModelUsers();
        $this->validation Services::validation();
    }

    public function index(): Response
    
{
        $data $this->model->get_user_list();
        $count count($data);

        if ($count <= 0) {
            $data = [
                'status' => 201,
                'error' => null,
                'message' => [
                    'success' => 'Tidak ada data daftar pegawai'
                ],
            ];

        }
        return $this->respond($data200);

    }
*** 

REST Client
.env file
Code:
***
app.baseURL = 'http://ci4-test.localhost'
***

Routes.php
PHP Code:
***
$routes->get('/rest', [\App\Controllers\Rest\RestClient::class, 'index']);
*** 

RestClient.php
PHP Code:
namespace App\Controllers\Rest;

use 
App\Controllers\BaseController;
use 
Config\Services;

class 
RestClient extends BaseController
{
    public function index()
    {
        $client Services::curlrequest();
        $token "someToken";
        $url "http://ci4-api.localhost/api/users/";
        $headers = [
            'Authorization' => 'Bearer ' $token,
        ];

        $response $client->request('GET'$url, ['headers' => $headers'http_errors' => false]);

        return $response->getBody();
    }


Postman
api auth
[Image: Postman-Api-Auth.png]

api all user list
[Image: Postman-Api-Users-List.png]

I have already tried some simple solution, like reload all laragon service like apache server and mongodb, restart the windows and tried find online, but it only suggest that the url is incorectly used like in this one https://stackoverflow.com/questions/5670...ermanently

Is there anyone have same issue or solution, thanks in advance.


  404 Not Found in a route with same name of namespace
Posted by: rodrigoguariento - 07-30-2022, 11:52 AM - Replies (2)

Does anyone know why I'm getting "404 Not Found" in this "admin" route? The route "/" works fine. When I change "admin" to "adm" works fine too. Remembering: the auto route is false. Thanks!
[Image: Untitled.png]


  Vagrantfile is unmaintained
Posted by: kenjis - 07-29-2022, 03:25 PM - No Replies

The Vagrantfile.dist is unmaintained for a long time.
See https://github.com/codeigniter4/CodeIgni...ssues/2453

If anybody is using it and wants to update,
contributions are welcome.


  Inaccuracy? Edit Entity attributes
Posted by: ozornick - 07-29-2022, 12:44 PM - Replies (6)

It's probably planned that way, but it doesn't seem right.
When the entity is received by the model, a class is created and the setAttributes() method is called (Set raw data array without any mutations)
For simple types, everything is fine. But for a date (or another class) there is a difference.

When I edit an entity, my attributes apply mutators.
Let's say I want to change my date of birth.


PHP Code:
        //  protected $dates = [ 'created_at',  'updated_at',  'date_birth'];
        $user->syncOriginal(); 
        
        
// hasChanged() > boolean false
        // toRawArray() > date_birth => string (10) "2008-02-06"
        $user->firstName $dto->firstName ?? $user->firstName;
        $user->dateBirth $dto->dateBirth ?? $user->dateBirth->format('Y-m-d');
        // ... other fields edit
        
        
// hasChanged() > boolean true
        // toRawArray() > date_birth => CodeIgniter\I18n\Time (6) 2000-10-13 00:00:00+04:00 MSD
        // BUT I did not change the date of birth - the mutator was applied  


I think this is incorrect behavior and you need to use the fill () method in the model or some other option.
Summary: The _original attributes will not match the changed _attributes, even if the string value is the same


Wink Redirect to Dashboard after Successful registration
Posted by: bleras - 07-29-2022, 08:20 AM - No Replies

Hello forum!!
Im dealing with a thing thats make my head blow.

I need to login automatically my users after they Register in my form.

i have this 2 functions to login and register.

public function ajax_login()
{
$email = post("email");
$password = post("password");
$remember = post("remember");
$this->user_manager_model->login($email, $password, $remember);
}

public function ajax_signup()
{
$fullname = post("fullname");
$email = post("email");
$password = post("password");
$timezone = post("timezone");
$confirm_password = post("confirm_password");
$terms = post("terms");

$this->user_manager_model->signup($fullname, $email, $password, $confirm_password, $timezone, $terms);

}


How i can do that? Thanks


  Support for stripping exif in ImageMagickHandler
Posted by: blurpy - 07-29-2022, 06:09 AM - No Replies

In CodeIgniter 3 I patched image_lib to strip exif when resizing using imagemagick.
Here:
https://github.com/bcit-ci/CodeIgniter/b...b.php#L872

PHP Code:
public function image_process_imagemagick($action 'resize')
{
...
  // Execute the command
  $cmd $this->library_path.' -quality '.$this->quality;
  $cmd .= " -strip "; <-- added this
... 
Now I need this when migrating to CodeIgniter 4. Could this be added as an optional feature in ImageMagickHandler?

Something along the lines of:

PHP Code:
$this->image->withFile($fullImagePath)
            ->resize($imageWidth$imageHeighttrue)
            ->stripExif()
            ->save($scaledImagePath70); 


  Print Web-page Without Displaying the Print Dialog Box
Posted by: andy_algo - 07-29-2022, 03:26 AM - No Replies

How to Print Web-page Without Displaying the Print Dialog Box using Codeigniter3?


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Manage Session folder
by captain-sensible
1 hour ago
Cache unable to write to ...
by captain-sensible
3 hours ago
checkbox value for Edit n...
by Ahmed Haroon
11 hours ago
Config\Paths different on...
by jetspeed
Yesterday, 08:42 PM
StreamResponse class
by kenjis
Yesterday, 08:04 PM
Wildcard Subdomains and H...
by rockinmusicgv
Yesterday, 06:26 PM
Session destroy randomly ...
by kenjis
Yesterday, 04:30 PM
supported locales (array)...
by rodrigoguariento
Yesterday, 02:30 PM
dropdown filter datatable...
by SubrataJ
Yesterday, 08:56 AM
SHIELD - Table name
by nfaiz
Yesterday, 07:48 AM

Forum Statistics
» Members: 40,097
» Latest member: thewokeindia
» Forum threads: 75,268
» Forum posts: 366,961

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB