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

Form validation field must be 6 char

$
0
0
There is a vay to set a validation rule to set a length of field fixed (f.e 6 )

I can do min_lenght and max_length but there is a way to do it only one time?

Hooks on controller methods

$
0
0
Hello,

I have been building RESTful API using CI 3 and I have came to a situation where there is a lot of duplicated code so I was thinking if it's possible to achieve something like a hook on a function inside a controller. As far as my knowledge gets we can add hooks on the controller itself but thats on the actual initialisation and destruction. What I want is to have a hook that is triggered before a call of a function inside the controller. 

Here is some example of my code

PHP Code:
    public function update($id)
    {
        if ($this->$this->exist($id)) {
            return;
        }
       //Do something

    }

    public function delete($id)
    {
        if ($this->$this->exist($id)) {
            return;
        }

         //Do something
    }

    public function add_image($id)
    {
        if ( ! $this->exist($id)) {
            return;
        }
        
        
// Do something
    }

    private function exist($id)
    {

        if ( ! $this->Example_model->exist($id)) {
            return false;
        }

        return true;
    

As you can see the private method 'exist' is duplicated couple of times.
I would like to make the code cleaner by extracting this functionality out of the function body so it can be re-used on multiple places.

Maybe there some other solution that are not related with Hooks and I love to hear about them.

I hope I have explained clear enough. 
Regards

Documentation in Arabic ?

$
0
0
Hello Everyone,
I'm Arabic Speaker member i was wondering if there's any Arabs here working on some kind of documentation for the framework
so i can join them or we can create a team to create a version of documentation in Arabic as a contribution to the project and the Arabic Community of PHP programmers Heart

how to catch db error

$
0
0
i have insert new row to table in same time  ( 10 users )

my primary key is determined from user input with in 3 groups

Blue
Yellow
Green

if user select Blue ID must be B001, B002
Yellow Y001, Y002


i have check to get last Id using query but sometimes getting error duplicate key
i want to catch db error so i can change ID and try to insert again

    try{
      $result = $this->db->insert($table,$data);
      echo $result;
      print  $result;
    }
    catch(Exception $e)
    {

       echo "Test Error"
        //get new ID

        // Insert data with new ID
    }

but now working

Is there any App online that using CodeIgniter 4

$
0
0
Hello everybody,

I used CodeIgniter 3 for couple of projects and I love it, and I always looking for best practice to do stuff better,

I would like to start use CodeIgniter 4  for my next application witch use more language than English, and I think CodeIgniter 4 has some change in this topic.. and I'm wondering what CodeIgniter 4 offer for using REST API

I would love if someone can share an app or a tutorial online that use CodeIgniter 4 and support multi languages, and how to use REST API with CodeIgniter 4


Thank you

session in view file

$
0
0
How to get session value in view file In CI4?

PHP-Casbin: An authorization library that supports ACL, RBAC, ABAC

Controller validator class

$
0
0
Hello  Smile

I searched for a similar topic but I didn't find any... so I hope it won't be redundant. I have an "issue" (or, at least, a comprehension issue) with the initialization of the variable $validator in the CodeIgniter\Controller class.

Let me explain:
- I extended the CodeIgniter\Validation\Validation class with additional methods:
PHP Code:
<?php namespace App\Libraries;

use 
CodeIgniter\Validation\Validation as CoreValidation;

class 
Validation extends CoreValidation
{

    public function __construct(\Config\Validation $config, \CodeIgniter\View\RendererInterface $view)
    {
        parent::__construct($config$view);
    }

    /** ... my custom code here **/

}

?>

- I rewrote the validation() method in the Config\Services class to instanciate my custom class (as written in the user guide):
PHP Code:
public static function validation(\Config\Validation $config nullbool $getShared true)
    {
        if ($getShared)
        {
            return static::getSharedInstance('validation'$config);
        }

        if (is_null($config))
        {
            $config config('Validation');
        }

        return new \App\Libraries\Validation($config, static::renderer());
    
,
- in my custom controller, I use the method validate() from the class CodeIgniter\Controller. For information, this method initializes the variable $validator:
PHP Code:
protected function validate($rules, array $messages = []): bool
    
{
        
$this->validator Services::validation();

        
// If you replace the $rules array with the name of the group
        
if (is_string($rules))
        {
            
$validation = new \Config\Validation();

            
// If the rule wasn't found in the \Config\Validation, we
            // should throw an exception so the developer can find it.
            
if (! isset($validation->$rules))
            {
                throw 
ValidationException::forRuleNotFound($rules);
            }

            
// If no error message is defined, use the error message in the Config\Validation file
            
if (! $messages)
            {
                
$errorName $rules '_errors';
                
$messages  $validation->$errorName ?? [];
            }

            
$rules $validation->$rules;
        }

        
$success $this->validator
            
->withRequest($this->request)
            ->
setRules($rules$messages)
            ->
run();

        return 
$success;
    } 

What I expect: the variable $validator is an instance of my custom Validation class.

What I get: the variable is an instance of CodeIgniter\Config\Services.

Knowing the philosophy of the framework and the extensibility it provides, it seems to be bug. If not, could it be clearly stated when CodeIgniter\Config\Services is preferred to App\Config\Services? At leas to know when we can rely on our custom extensions of CI.

If it is done on purpose, obviously, I'll rewrite the validate method in my custom Controller.

Regards and thank you!

Installing codeigniter

$
0
0
I have the /application directory with all of my CI application. Other than the application directory does anything need to installed to make a CI application run?

Redirection in a helper

$
0
0
Hello there,

With ci3, I usually created a helper with a function called "redirect_if_not_logged_in()" that I called at the top of some controllers.

The goal of that function was quite self-explanatory: it checked if the visitor was logged in and if not, redirected them to the login page.

Alas, when trying to do the same with ci4, things get a bit complicated. The "redirect()" function I used to use doesn't actually redirect, but returns an elusive RedirectResponse (completely missing from the doc, by the way).

The only thing I imagine myself doing for now is this:
PHP Code:
// in a helper:

if (!function_exists('redirectIfNotLoggedIn'))
{
    $session = \Config\Services::session();
    if ($session->get('loggedUser') === null)
    {
        return redirect('user/login');
    }
    return null;
}

// in a controller:

public function create()
{
    $redirection redirectIfNotLoggedIn();
    if ($redirection !== null)
    {
        return $redirection;
    }
    // ...


But sincerely, that's pretty much as much code to call the helper and use it than to simple copy-paste the code inside the controller.

How can I redirect FROM the helper?

Nice day to you all!

Community Auth: Cannot make it work with CI 3.1.11

$
0
0
Dear skunkbad,

I have intalled Community Auth on a fresh CI 3.1.11 following the instruciones in https://community-auth.com/.

I can see the login form but notihing happens when I write legitime or wrong credentilals; the form simply reloads.


If I click on "Can't access your account?" I get the following PHP error
PHP Code:
A PHP Error was encountered

Severity
Warning

Message
Cannot modify header information headers already sent by (output started at /home/app_iotopentech/app.iotopentech.io/application/controllers/Examples.php:401)

Filenamelibraries/Tokens.php

Line Number
242

Backtrace
:

File: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/libraries/Tokens.php
Line
242
Function: setcookie

File
: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/libraries/Tokens.php
Line
199
Function: save_tokens_cookie

File
: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/libraries/Tokens.php
Line
214
Function: generate_form_token

File
: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/helpers/MY_form_helper.php
Line
79
Function: token

File
: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/views/examples/recover_form.php
Line
109
Function: form_open

File
: /home/app_iotopentech/app.iotopentech.io/application/controllers/Examples.php
Line
403
Function: view

File
: /home/app_iotopentech/app.iotopentech.io/index.php
Line
315
Function: require_once 
[url=https://app.iotopentech.io/index.php/examples/recover][/url]

Besides, I have configured log threshold to 2, but nothing appears in the log file related to the credentials.
PHP Code:
DEBUG 2019-10-12 17:42:25 --> UTF-8 Support Enabled
DEBUG 
2019-10-12 17:42:25 --> Global POSTGET and COOKIE data sanitized
DEBUG 
2019-10-12 17:42:25 --> Config file loaded: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/config/db_tables.php
DEBUG 
2019-10-12 17:42:25 --> Config file loaded: /home/app_iotopentech/app.iotopentech.io/application/third_party/community_auth/config/authentication.php
DEBUG 
2019-10-12 17:42:25 --> Session"sess_save_path" is empty; using "session.save_path" value from php.ini.
DEBUG 2019-10-12 17:42:25 --> EncryptionAuto-configured driver 'openssl'.
DEBUG 2019-10-12 17:42:25 --> Total execution time0.0072 
Please could you help me?

Kind regards from Madrid.

Redirect rule in routes with multi-app setup

$
0
0
Hello, is it possible to redirect from routes to a specific URL? I have multi-app setup using single CI installation, a shared app and independent apps and I would like to make a redirect from one to another by calling specific "index.php" file fore that app.

So basically it would be full redirect and not only routing option to the controller. Of course, another option here is using filter to make redirect there. Just asking if it is possible to do in the router as well.

Code:
$routes->group('admin', function ($routes){
    $routes->addRedirect('/', 'specific.index.php'); // <- This doesn' work
    $routes->add('login', 'Login::index', ['namespace' => '\Admin\Controllers\Auth']);
});

Thank You in advance ^-^

Each user can set timezone

$
0
0
Exemple

Code:
date_default_timezone_set($user->timezone)

How do I do it in Codeigniter? I tried to put in the MY_Controller of Core, which is the main controller of my system. Only it does not work. It only works if I put in index.php or constants.php. But it can't be read from Model to get user data for what I want to do.

$.post() Method fails with decimal value in URL

$
0
0
This is driving my crazy.  This POST returns a 404 Not Found error when there is a decimal value in the URL:
Code:
http://localhost:8080/myController/myMethod/1/2019/123.45/

But this POST succeeds and returns 200 OK when I remove the decimal value:
Code:
http://localhost:8080/myController/myMethod/1/2019/12345/


I'm not sure if this is relevant, but I recently upgraded from CI 2.2.x to 3.1 and I never used to have this problem before.  I don't think I need to encode the value because decimals are used in URLs all the time.   

I hope someone can help me find the problem.

Shieldon Firewall - Web Application Firewall for CodeIgniter.


Tweaking a website

$
0
0
Hi,
I am looking for help for some tweaking job for a website. 
Presently, it is a one-time help; but time-to-time assistance for the same website would be needed as we grow.
Thanks in advance.
Neeraj

pagination getPrevious() & getNext

$
0
0
Hi,

I create a App/Views/Pagers/bootstrap_full.php file:

<?php $pager->setSurroundCount(2) ?>

<nav aria-label="Page navigation">
    <ul class="pagination">
    <?php if ($pager->hasPrevious()) : ?>
        <li class="page-item">
            <a href="<?= $pager->getFirst() ?>" aria-label="First" class="page-link"> 
                <i class="fas fa-angle-double-left"></i>
            </a>
        </li>
        <li class="page-item">
            <a href="<?= $pager->getPrevious() ?>" aria-label="Previous" class="page-link">
                <i class="fas fa-angle-left"></i>
            </a>
        </li>
    <?php endif ?>

    <?php foreach ($pager->links() as $link) : ?>
        <li <?= $link['active'] ? 'class="active page-item"' : 'class="page-item"' ?>>
            <a href="<?= $link['uri'] ?>" class="page-link">
                <?= $link['title'] ?>
            </a>
        </li>
    <?php endforeach ?>

    <?php if ($pager->hasNext()) : ?>
        <li class="page-item">
            <a href="<?= $pager->getNext() ?>" aria-label="Next" class="page-link">
                <i class="fas fa-angle-right"></i>
            </a>
        </li>
        <li class="page-item">
            <a href="<?= $pager->getLast() ?>" aria-label="Last" class="page-link">
                <i class="fas fa-angle-double-right"></i>
            </a>
        </li>
    <?php endif ?>
    </ul>
</nav>


but getPrevious() & getNext() links go to getFirst() & getLast() pages

I have some wrong?

thanks!

CeBIT AUSTRALIA 2019

$
0
0
CeBIT Australia is an event promoting all technology industries worldwide. The event is a focal point of all industries and businesses in the technology sector. CeBIT is the largest market place for promoting current and future technologies. The event involves professional businesses and exhibitors displaying their products and technologies to a room full of potential clients and buyers. The visitors also get training sessions and seminars to get to learn about the current technologies and gadgets used in various corners of the world. This is a must attend for all technology enthusiasts and businesses working to promote inventors and discovers worldwide.
A rebranded and reimagined CEBIT Australia has just launched the first section of their 2019 program with a focus on the key digital transformation issues that are facing businesses as they seek to innovate and grow.

A PHP Error was encountered Severity: Notice Message: Undefined index: Satker

$
0
0
I am very confused of this error messages. Please help me


Quote:A PHP Error was encountered
Severity: Notice
Message: Undefined index: Satker
Filename: controllers/Members.php
Line Number: 67
Backtrace:
File: C:\xampp\htdocs\nonameapp\application\controllers\Members.php
Line: 67
Function: _error_handler
File: C:\xampp\htdocs\nonameapp\index.php
Line: 315
Function: require_once




Quote:A Database Error Occurred
Error Number: 1048
Column 'satker' cannot be null
INSERT INTO `t_satker` (`kode`, `satker`, `created`, `modified`) VALUES ('asas', NULL, '2019-10-14 13:29:23', '2019-10-14 13:29:23')
Filename: C:/xampp/htdocs/nonameapp/system/database/DB_driver.php
Line Number: 691


This is my controller
Code:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Members extends CI_Controller {
   
    function __construct() {
        parent::__construct();
       
        // Load member model
        $this->load->model('member');
       
        // Load form validation library
        $this->load->library('form_validation');
       
        // Load file helper
        $this->load->helper('file');
    }
   
    public function index(){
        $data = array();
       
        // Get messages from the session
        if($this->session->userdata('success_msg')){
            $data['success_msg'] = $this->session->userdata('success_msg');
            $this->session->unset_userdata('success_msg');
        }
        if($this->session->userdata('error_msg')){
            $data['error_msg'] = $this->session->userdata('error_msg');
            $this->session->unset_userdata('error_msg');
        }
       
        // Get rows
        $data['members'] = $this->member->getRows();
       
        // Load the list page view
        $this->load->view('members/index', $data);
    }
   
    public function import(){
        $data = array();
        $memData = array();
       
        // If import request is submitted
        if($this->input->post('importSubmit')){
            // Form field validation rules
            $this->form_validation->set_rules('file', 'CSV file', 'callback_file_check');
           
            // Validate submitted form data
            if($this->form_validation->run() == true){
                $insertCount = $updateCount = $rowCount = $notAddCount = 0;
               
                // If file uploaded
                if(is_uploaded_file($_FILES['file']['tmp_name'])){
                    // Load CSV reader library
                    $this->load->library('CSVReader');
                   
                    // Parse data from CSV file
                    $csvData = $this->csvreader->parse_csv($_FILES['file']['tmp_name']);
                   
                    // Insert/update CSV data into database
                    if(!empty($csvData)){
                        foreach($csvData as $row){ $rowCount++;
                           
                            // Prepare data for DB insertion
                            $memData = array(
                                'kode' => $row['Kode'],
                                'satker' => $row['Satker'],
                            );
                           
                            // Check whether email already exists in the database
                            $con = array(
                                'where' => array(
                                   
                                ),
                                'returnType' => 'count'
                            );
                            $prevCount = $this->member->getRows($con);
                           
                            if($prevCount > 0){
                                // Update member data
                                $condition = array();
                                $update = $this->member->update($memData, $condition);
                               
                                if($update){
                                    $updateCount++;
                                }
                            }else{
                                // Insert member data
                                $insert = $this->member->insert($memData);
                               
                                if($insert){
                                    $insertCount++;
                                }
                            }
                        }
                       
                        // Status message with imported data count
                        $notAddCount = ($rowCount - ($insertCount + $updateCount));
                        $successMsg = 'Members imported successfully. Total Rows ('.$rowCount.') | Inserted ('.$insertCount.') | Updated ('.$updateCount.') | Not Inserted ('.$notAddCount.')';
                        $this->session->set_userdata('success_msg', $successMsg);
                    }
                }else{
                    $this->session->set_userdata('error_msg', 'Error on file upload, please try again.');
                }
            }else{
                $this->session->set_userdata('error_msg', 'Invalid file, please select only CSV file.');
            }
        }
        redirect('members');
    }
   
    /*
     * Callback function to check file value and type during validation
     */
    public function file_check($str){
        $allowed_mime_types = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
        if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != ""){
            $mime = get_mime_by_extension($_FILES['file']['name']);
            $fileAr = explode('.', $_FILES['file']['name']);
            $ext = end($fileAr);
            if(($ext == 'csv') && in_array($mime, $allowed_mime_types)){
                return true;
            }else{
                $this->form_validation->set_message('file_check', 'Please select only CSV file to upload.');
                return false;
            }
        }else{
            $this->form_validation->set_message('file_check', 'Please select a CSV file to upload.');
            return false;
        }
    }
}

And this is view
Code:
<div class="container">
    <h2>Members List</h2>
    
    <!-- Display status message -->
    <?php if(!empty($success_msg)){ ?>
    <div class="col-xs-12">
        <div class="alert alert-success"><?php echo $success_msg; ?></div>
    </div>
    <?php } ?>
   
    <?php if(!empty($error_msg)){ ?>
    <div class="col-xs-12">
        <div class="alert alert-danger"><?php echo $error_msg; ?></div>
    </div>
    <?php } ?>
    
    <div class="row">
        <!-- Import link -->
        <div class="col-md-12 head">
            <div class="float-right">
                <a href="javascript:void(0);" class="btn btn-success" onclick="formToggle('importFrm');"><i class="plus"></i> Import</a>
            </div>
        </div>
        
        <!-- File upload form -->
        <div class="col-md-12" id="importFrm" style="display: none;">
            <form action="<?php echo base_url('members/import'); ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT">
            </form>
        </div>
       
        <!-- Data list table -->
        <table class="table table-striped table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>#ID</th>
                    <th>Kode Satker</th>
                    <th>Nama Satker</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($members)){ foreach($members as $row){ ?>
                <tr>
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo $row['kode']; ?></td>
                    <td><?php echo $row['satker']; ?></td>
                </tr>
                <?php } }else{ ?>
                <tr><td colspan="5">No member(s) found...</td></tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function formToggle(ID){
    var element = document.getElementById(ID);
    if(element.style.display === "none"){
        element.style.display = "block";
    }else{
        element.style.display = "none";
    }
}
</script>

Listing of environmental variables?

$
0
0
Is there a list of environmental variables I can set that will be used in config files in the / config dir? Things such as url and database paths and userid's?
Viewing all 14075 articles
Browse latest View live