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

Advice for upgrading from v2 to v4?

$
0
0
Hi, I'm an experienced PHP developer, first time using CodeIgniter. I've taken on a site that is using v2.2.6 and one of the projects I need to do is upgrade it. Does anyone have some advice for things I should look out for? i.e. things that tripped you up when you've done upgrades yourself?
I guess starting questions are... should I go from v2 to v3 then v4, or is it better to jump straight to v4?
And, any gotchas that I should look out for that I might miss because I'm unfamiliar with CodeIgniter?
I'm expecting to spend lots of time looking at the error log as I try to get the upgraded site working, but any pointers will be gratefully received!
Thanks

CodeIgniter very long loading times under Xampp and Wamp server

$
0
0
Hello, I've recently been having very long loading times for my CodeIgniter pages. Even without database queries, it takes > 16 seconds to load a simple view. PHP memory_limit etc. is set to > 4 GB. I also have the problem with both Xampp and Wamp Server (Xampp currently installed). I'm slowly running out of ideas as to what else could be causing it. Do you have any ideas?

Quote:Bootstrap: 23.83 ms
Required Before Filters: 3.39 ms
Routing: 1.45 ms
Before Filters: 0.04 ms
Controller: 16,271.44 ms
> Controller Constructor: 2.69 ms
> View: sites/privacy.php: 16,265.88 ms
> View: layouts/main.php: 8,148.69 ms

I don't have any filters or anything like that active. Controller is very simple:

PHP Code:
public function privacy()
 {
    echo view('sites/privacy');


View contains simple html (static).

If I write a PHP script that performs certain database queries, it runs in a few milliseconds also local.

The site is extremely fast on the live system (Ubuntu server). So it must be something local. But I don't know what else I can check.

Unexpected json_encode format

$
0
0
Hi,
I am experiencing unexpected results when using json_encode on an array that has text values (with spaces) in my CI4 view.

I am using php 8 and CI 4.2.12

I believe I am encoding my array correctly
PHP Code:
<?php foreach($search_results as $result) : ?>
    <?= print_r(json_encode($result['notes']), true?>
<?php 
endforeach ?>
will output: 
PHP Code:
[{"note_id":"11","po_no":"1031","note":"this is a test of some notes, and a comma","perm":"0"}] 
This is how I expect the result !


However when I use the same encoding in my formatted view
PHP Code:
<?php foreach($search_results as $result) : ?>                        
    <tr class="modal_data" data-jnod="<?= session('job_prefix').$result['job_no'?><?= session('po_prefix').$result['po_no'?>" data-cln="<?= $result['client_name'?>" data-cls="<?= $result['client_site'?>" data-whl="<?= $result['wholesaler'?>" data-ptyp="<?= $result['purchase_type'?>" data-pds="<?= $result['purchase_desc'?>" data-amt="<?= number_format($result['amount'],2?>" data-notes="<?= json_encode($result['notes']) ?>" data-bs-toggle="modal" data-bs-target="#poModal">
        <td><?= session('job_prefix').$result['job_no'?><?= session('po_prefix').$result['po_no'?></td>
        <td><?= $result['client_name'?></td>
        <td><?= $result['client_site'?></td>
        <td><?= $result['wholesaler'?></td>
        <td><?= $result['purchase_type'?></td>
        <td><?= $result['purchase_desc'?></td>
        <td><?= $result['amount'?></td>
        </tr>
<?php endforeach ?>

The view reformats the JSON and does not respect the text string, placing ="" for every space in the string. Note: I experience exactly the same result is I encode the array in my Model or controller.

output: data-notes="[[{" note_id":"11","po_no":"1031","note":"this="" is="" a="" test="" of="" some="" notes,="" and="" comma","perm":"0"}]]"=""


Full output below:
Code:
<tr class="modal_data" data-jnod="DEM/J2804/1031" data-cln="GALLAGHER" data-cls="Ashford" data-whl="Cef" data-ptyp="materials" data-pds="Materials" data-amt="0.00" data-notes="[[{" note_id":"11","po_no":"1031","note":"this="" is="" a="" test="" of="" some="" notes,="" and="" comma","perm":"0"}]]"="" data-bs-toggle="modal" data-bs-target="#poModal">
        <td>DEM/J2804/1031</td>
        <td>GALLAGHER</td>
        <td>Ashford</td>
        <td>Cef</td>
        <td>materials</td>
        <td>Materials</td>
        <td>0.00</td>
</tr>
I have tried using JSON_FORCE_OBJECT and any other number of parameters, but get the same result.
I would be grateful if someone could point me in the right direction?

Thank you

[RedirectClass] toReferrer

$
0
0
In my project is is likely users will open multiple tabs but continue navigating on the original tab. In this case, using redirect()->back() produces unexpected behavior. Example

  • user opens /list/
  • user opens /list/item/1 in a new tab (in background)
  • user posts form on /list
  • controller handles form posts and does a
    Code:
    redirect()->back()

  • user is now redirected back to /list/item/1 since it is the last visited url in the session
The behaviour of
Code:
redirect()->back()
is well documented and I understand the choice to use the session for safety.

However, would there be enough of a use case to add  a
Code:
redirect()->toReferrer()

function to cover the case I just described? Of course, this would be not much more than a convenience function as the functionality can already be achieved with other functions from the framework.

I would be happy to open a PR.

CodeIgniter v4.5.3 bug fix released

post data from controller to view without display

$
0
0
i have a codeignite 3 project in which the view page composed of 2 parts:
1-the menu items which constantly placed in left part of page fully covering height of page and 30% of width; its displayed as a base for all other pages in 2nd part.
2-the view page for all items listed in menu in left part which cover the remaining right part of page. 
each page saved as blade template.
can i post a data from controller to menu page which is saved as base view for all pages?
i use following to fetch my required dataset from sql database in phpmyadmin:
PHP Code:
public function profil_yonetimi_get_board_of_sustainability_data() {
    $this->user_oturum_yetki_kontrol();
        $REPORT_ID $this->input->post('ID');

        $Aktif_ID=___ssl_decrypt($this->session->userdata('USER_AKTIF_PROFIL_OTURUMU'));
        $BoS_DB=$this->user_model->bos_data($Aktif_ID);

            $BOS1 $BoS_DB->profil_yonetimi_bos_members;
            $BOS2$BoS_DB->profil_yonetimi_bos_chief;
                ...

            $this->ICERIK_VERISI['BoS_DB'] = $BoS_DB;
           $this->blade->display('user/PROFIL/BASE/sol_menu'$this->ICERIK_VERISI);


but that does not work.
how can i post fetched data as defined in BoS_DB to menu list page part ?
here i dont need any display of this data on page, just retrive data for analysis purposes.

Undefined constant CodeIgniter\Router\Router::HTTP_METHODS

$
0
0
Hi guys,

Can someone tell me what this error means? I can see the constant is defined in Router.php.

Code:
CRITICAL - 2024-06-25 16:30:02 --> Error: Undefined constant CodeIgniter\Router\Router::HTTP_METHODS
in SYSTEMPATH\Router\DefinedRouteCollector.php on line 35.
1 SYSTEMPATH\Debug\Toolbar\Collectors\Routes.php(105): CodeIgniter\Router\DefinedRouteCollector->collect()
2 SYSTEMPATH\Debug\Toolbar\Collectors\BaseCollector.php(226): CodeIgniter\Debug\Toolbar\Collectors\Routes->display()
3 SYSTEMPATH\Debug\Toolbar.php(93): CodeIgniter\Debug\Toolbar\Collectors\BaseCollector->getAsArray()
4 SYSTEMPATH\Debug\Toolbar.php(370): CodeIgniter\Debug\Toolbar->run(1719304186.26961, 16.1719, Object(CodeIgniter\HTTP\IncomingRequest), Object(CodeIgniter\HTTP\Response))
5 SYSTEMPATH\Filters\DebugToolbar.php(43): CodeIgniter\Debug\Toolbar->prepare(Object(CodeIgniter\HTTP\IncomingRequest), Object(CodeIgniter\HTTP\Response))
6 SYSTEMPATH\Filters\Filters.php(211): CodeIgniter\Filters\DebugToolbar->after(Object(CodeIgniter\HTTP\IncomingRequest), Object(CodeIgniter\HTTP\Response), null)
7 SYSTEMPATH\CodeIgniter.php(522): CodeIgniter\Filters\Filters->run('update/install', 'after')
8 SYSTEMPATH\CodeIgniter.php(361): CodeIgniter\CodeIgniter->handleRequest(null, Object(Config\Cache), false)
9 FCPATH\index.php(79): CodeIgniter\CodeIgniter->run()

PHP Code:
class Router implements RouterInterface
{
    /**
    * List of allowed HTTP methods (and CLI for command line use).
    */
    public const HTTP_METHODS = [
        Method::GET,
        Method::HEAD,
        Method::POST,
        Method::PATCH,
        Method::PUT,
        Method::DELETE,
        Method::OPTIONS,
        Method::TRACE,
        Method::CONNECT,
        'CLI',
    ]; 

16 Killer Web Applications to Boost Your Workflow with AI


Why is there a index.php

$
0
0
Hi all,
I am new to CI for like half a year and working on my second project using it. I wonder about one thing:
My "normal" routing works well, domain.tld/page1 etc, Apache is set up to drop the index.php

CI3 and PHP8.1

$
0
0
Hello, guys.
I need your help.
I encounter the following error by default: 

Quote:A PHP Error was encountered Severity: 8192 Message: ctype_digit(): Argument of type int will be interpreted as string in the future Filename: postgre/postgre_driver.php Line Number: 98

Is overriding the only way to solve this issue? I have attempted to override it, but the custom class in the "application/core" directory is not being loaded, and the error is not resolved. Is it possible for the custom class in the "core" directory not to be loaded?
Of course, I have correctly set  "$config['subclass_prefix']" in "config/config.php".

Thanks in advance.

Codeigiter 4 Shield : Customize Registration Controller

$
0
0
Dear Php freaks,
I'm developing one application where i used codeigniter shiled package for authorization, everything works fine but i need to customize my registration controller.

I copied entire controller from shield to app/controlers folder like this as per documentation. 
Code:
<?php

namespace App\Controllers;

use CodeIgniter\Shield\Controllers\RegisterController as ShieldRegister;
use CodeIgniter\HTTP\RedirectResponse;
use App\Controllers\BaseController;
use CodeIgniter\Events\Events;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Exceptions\ValidationException;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Traits\Viewable;
use CodeIgniter\Shield\Validation\ValidationRules;
use Psr\Log\LoggerInterface;

class RegisterController extends ShieldRegister
{
    use Viewable;

    public function initController(
        RequestInterface $request,
        ResponseInterface $response,
        LoggerInterface $logger
    ): void {
        parent::initController(
            $request,
            $response,
            $logger
        );
    }

    /**
    * Displays the registration form.
    *
    * @return RedirectResponse|string
    */
    public function registerView()
    {
        if (auth()->loggedIn()) {
            return redirect()->to(config('Auth')->registerRedirect());
        }

        // Check if registration is allowed
        if (! setting('Auth.allowRegistration')) {
            return redirect()->back()->withInput()
                ->with('error', lang('Auth.registerDisabled'));
        }

        /** @var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // If an action has been defined, start it up.
        if ($authenticator->hasAction()) {
            return redirect()->route('auth-action-show');
        }

        return $this->view(setting('Auth.views')['register']);
    }

    /**
    * Attempts to register the user.
    */
    public function registerAction(): RedirectResponse
    {
        if (auth()->loggedIn()) {
            return redirect()->to(config('Auth')->registerRedirect());
        }

        // Check if registration is allowed
        if (! setting('Auth.allowRegistration')) {
            return redirect()->back()->withInput()
                ->with('error', lang('Auth.registerDisabled'));
        }

        $users = $this->getUserProvider();

        // Validate here first, since some things,
        // like the password, can only be validated properly here.
        $rules = $this->getValidationRules();

        if (! $this->validateData($this->request->getPost(), $rules, [], config('Auth')->DBGroup)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // Save the user
        $allowedPostFields = array_keys($rules);
        $user              = $this->getUserEntity();
        $user->fill($this->request->getPost($allowedPostFields));

        // Workaround for email only registration/login
        if ($user->username === null) {
            $user->username = null;
        }

        try {
            $users->save($user);
        } catch (ValidationException $e) {
            return redirect()->back()->withInput()->with('errors', $users->errors());
        }

        // To get the complete user object with ID, we need to get from the database
        $user = $users->findById($users->getInsertID());

        // Add to default group
        $users->addToDefaultGroup($user);

        Events::trigger('register', $user);

        /** @var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        $authenticator->startLogin($user);

        // If an action has been defined for register, start it up.
        $hasAction = $authenticator->startUpAction('register', $user);
        if ($hasAction) {
            return redirect()->route('auth-action-show');
        }

        // Set the user active
        $user->activate();

        $authenticator->completeLogin($user);

        // Success!
        return redirect()->to(config('Auth')->registerRedirect())
            ->with('message', lang('Auth.registerSuccess'));
    }

    /**
    * Returns the User provider
    */
    protected function getUserProvider(): UserModel
    {
        $provider = model(setting('Auth.userProvider'));

        assert($provider instanceof UserModel, 'Config Auth.userProvider is not a valid UserProvider.');

        return $provider;
    }

    /**
    * Returns the Entity class that should be used
    */
    protected function getUserEntity(): User
    {
        return new User();
    }

    /**
    * Returns the rules that should be used for validation.
    *
    * @return array<string, array<string, list<string>|string>>
    */
    protected function getValidationRules(): array
    {
        $rules = new ValidationRules();

        return $rules->getRegistrationRules();
    }
 

}
I also changed routes like this :

Code:
service('auth')->routes($routes, ['except' => ['register']]);

$routes->get('register', '\App\Controllers\RegisterController::registerView');
$routes->post('register', '\App\Controllers\RegisterController::registerView');


But when i access my registration page i can see that it works but when i click register button it does not produce any validation  errors like before. 

What actually i want to do ? :
I have added a extra field called "eid_number" in registration page and once the user submit the form, i will get eid number and get the employee id from employees_master table and attach to the user table so i can link the user with my employees table.

can someone show me how to run router group?

$
0
0
i test code in codeigniter 4.5.3
in my router
PHP Code:
$routes->group('api', ['namespace' => 'app\controllers\api'], function($routes)
 {
 
$routes->post("login""AuthController::login");
 
$routes->get("valid-access","AuthController::accessDenied");
 
$routes->post("register","AuthController::register");
 
$routes->get("profile","AuthController::profile", ["filter" => "apiauth"]);
 
$routes->get("logout","AuthController::logout");
 
$routes->post("add-project","ProjectController::addProject");
 
$routes->get("list-project","ProjectController::listProjects");
 
$routes->get("delete-project/(:num)","ProjectController::deleteProjects/$1");
 }); 
in my controller with app/controller/api
PHP Code:
<?php

namespace App\Controllers\Api;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\RESTful\ResourceController;
use 
CodeIgniter\Shield\Models\UserModal;
use 
CodeIgniter\Shield\Entities\User;

class 
AuthController extends ResourceController
{
    public function register(){
        $rule = [
            "username"  =>  "required|is_unique[user.username]",
            "email"    => "required|valid_email|is_unique[auth_identities.secret]",
            "password"  => "required"
        ];
        if(!$this->validate($rule)){

        }else{

        }
        $this->responseCreated($response);

    }
    public function login()
    {
        echo 'hello';
        exit();
        $rule = [
            "email"    => "required|is_valid",
            "password"  => "required"
        ];
        if(!$this->validate($rule)){
            $response = [
                "status" => false,
                "message" => $this->validator->getError(),
                "data"      => []
            ];
        }else{
            $credentials = [
                "email" => $this->request->getVar("email"),
                "password" => $this->request->getVar("password")
            ];
            $loginAttempt auth()->attempt($credentials);
            if(!$loginAttempt->isOK()){
                $response = [
                "status" => false,
                "message" => "Invalid Login Details",
                "data"      => []
            ];
            }else{
                $userObject= new UserModal();
                $userObject $userObject->findById(auth()->id));
                $token $userData->generateAccessToken("ThisismysecretKey");
                $au_token $token->raw_token;
                $response = [
                "status" => true,
                "message" => "User Logged in Successfully",
                    "data"      => [
                    "token"    => $au_token
                
];
                ];
            }
            return $this->responseCreated($response);
    }

    public function profile(){
        $userId auth()->id();
        $userObject= new UserModal();
        $userObject $userObject->findById($userId);    
        
return $this->responseCreated([
            "status" => true,
                "message" => "Profile Api Call",
                "data"      => []

        ]);

    }

    public function logout(){
        $session session();
    }

    public function accessDenied(){
        return $this->responseCreated([
            "status" => false,
                "message" => "invalid Access",
                "data"      => []

        ]);
    }


PHP Code:
+--------+-----------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+      
Method Route                       Name               Handler                                                            Before Filters After Filters |      
+--------+-----------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+      
GET    | /                           | »                  | \App\Controllers\Home::index                                       |                |               |      
GET    profile                     »                  | \App\Controllers\Home::profile                                     |                |               |      
GET    register                    »                  | \CodeIgniter\Shield\Controllers\RegisterController::registerView   |                |               |      
GET    login                       »                  | \CodeIgniter\Shield\Controllers\LoginController::loginView         |                |               |      
GET    login/magic-link            magic-link         | \CodeIgniter\Shield\Controllers\MagicLinkController::loginView     |                |               |      
GET    login/verify-magic-link     verify-magic-link  | \CodeIgniter\Shield\Controllers\MagicLinkController::verify        |                |               |      
GET    logout                      »                  | \CodeIgniter\Shield\Controllers\LoginController::logoutAction      |                |               |      
GET    auth/a/show                 auth-action-show   | \CodeIgniter\Shield\Controllers\ActionController::show             |                |               |      
GET    api/invalid-access          »                  | \App\Controllers\Api\AuthController::accessDenied                  |                |               |      
GET    api/profile                 »                  | \App\Controllers\Api\AuthController::profile                       apiauth        apiauth       |      
GET    api/logout                  »                  | \App\Controllers\Api\AuthController:: logout                       |                |               |      
GET    api/list-project            »                  | \App\Controllers\Api\ProjectController::listProjects               |                |               |      
GET    api/delete-project/([0-9]+) | »                  | \App\Controllers\Api\ProjectController::deleteProjects/$1          |                |               |      
POST   register                    »                  | \CodeIgniter\Shield\Controllers\RegisterController::registerAction |                |               |      
POST   login                       »                  | \CodeIgniter\Shield\Controllers\LoginController::loginAction       |                |               |      
POST   login/magic-link            »                  | \CodeIgniter\Shield\Controllers\MagicLinkController::loginAction   |                |               |      
POST   auth/a/handle               auth-action-handle | \CodeIgniter\Shield\Controllers\ActionController::handle           |                |               |      
POST   auth/a/verify               auth-action-verify | \CodeIgniter\Shield\Controllers\ActionController::verify           |                |               |      
POST   api/register                »                  | \App\Controllers\Api\AuthController::register                      |                |               |      
POST   api/login                   »                  | \App\Controllers\Api\AuthController::login                         |                |               |      
POST   api/add-project             »                  | \App\Controllers\Api\ProjectController::addProject                 |                |               |      
+--------+-----------------------------+--------------------+--------------------------------------------------------------------+----------------+---------------+      
                                                                                                                                                                         
Required Before Filtersforcehttpspagecache                                                                                                                           
 Required After Filters
pagecacheperformancetoolbar 

i try to test url localhost:8080/shield/api/login but dont work
can explain why router dont go to controller404

Sorry! Cannot seem to find the page you were looking for.

Codeigniter4 How to switch controller based on user auth group

$
0
0
Hello,


I have two view files: one for users and another for admins. Here is my current route:

PHP Code:
$routes->get('dashboard/index'' Dashboard::index'); 


I want to change the view file based on the user's group. If
Code:
auth()->user()->inGroup("admin")
, it should use the "dashboard/admin" view; otherwise, it should use the "dashboard/index" view.
How can I achieve this?

CodeIgniter 5 come out ?

$
0
0
Hi,

When the new version of CodeIgniter 5 will come out ?

Best Regard.

Catch exeption from database insert

$
0
0
Developing a web application, I'm using insert () to add registers to the database.  I'm using the optional parameter to return a boolean value so I can check if it succeeded.

The problem is that if I try to insert a new register with a yet existing key CodeIgniter catch the exception and shows the tracing information.  So I added a try..catch but it doesn't catch anything.

The code I use is:

PHP Code:
try
{
  $Result $this->insert ($Datafalse);
}
catch (\
Exception $Error)
{
  log_message ('error'$Error->getMessage ());
  $Result false;


I've tried several exception classes (including CodeIgniter\Database\Exception\DatabaseException) but nothing works, neither debug mode nor production mode: CI overrides my code.  finally does work though.

Why is CI overriding my try..catch blocks and how can I prevent it?

P.S: I've search both in forums and in the Internet but I've found only old threads (CI3 or CI2) or unrelated with my problem.

P.S.2: If you'll say that I should check data before insert (as I've read in some old threads), I shouldn't:  I want the database to check data integrity and just check if it succeeded.  That's why relational databases were invented for, aren't they?

Host a ReactJS landing page in same codeigniter App

$
0
0
Hi

I'm working with a CodeIgniter application and now need to integrate a landing page into it
The landing page is being developed in ReactJS and now I need to host it somewhere inside the codeigniter's folder structure.
After this, I must make the ReactJS app the "default view" loading. That landing will have a link to run the CodeIgniter app

Any ideas?
I guess I could put the ReactJS dist files in the root folder and move the codeigniter app to a subfolder, but what changes would imply doing so?

Thanks for any suggestion you may have

CLI error Session: Initialization under CLI aborted.

$
0
0
Hi,
I'm using PHP 8.2 and CI 4.4.1 I have a Controller to run only in CLI mode, but when I tri to run it, I did not receive any error message but the Controller did not execute, in the logs under writable I have the error DEBUG - 2024-06-27 15:38:53 --> Session: Initialization under CLI aborted. 
I'm using IonAuth also.
Any idea what I'm doing wrong?
Thank you!

Curl request

$
0
0
hi,

Code:
 i must do a request to booking , in their api this is the request :
[code]
        curl -X POST --user '<CLIENT_ID>:<CLIENT_SECRET>' -H 'Content-Type: application/x-www-form-urlencoded' 'https://dispatchapi-sandbox-qa.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials'
[\CODE]

how can i transform to use with codeingiter ?

this is my code :
[CODE]

    public function getToken(){


        $client_id       = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        $client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

        $apiURL = 'https://dispatchapi-sandbox-qa.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials';



        $client = \Config\Services::curlrequest();

        $response = $client->request('POST', $apiURL, [
            'user' => [$client_id,  $client_secret],
        ]);

        // Read response
        $code = $response->getStatusCode();
        $reason = $response->getReason();

        if($code == 200){ // Success

            // Read data
            $body = json_decode($response->getBody());


            dd($body);

            $first_name = $body->first_name;
            $last_name = $body->last_name;
            $email = $body->email;

            echo "first_name : ".$first_name."<br>";
            echo "last_name : ".$last_name."<br>";
            echo "email : ".$email."<br>";

        }else{
            echo "failed";
            die;
        }

    }
[/code]
But i have : 
22 : The requested URL returned error: 405

how can i transform ?

Session data lost/destroyed with an Ajax call

$
0
0
Hi
I've been working on a local virtualhost on my PC with a codeigniter app
I've made a route ("main"). In the associated controller, I set some session data and load a main_view

In the main_view, there's a button that makes an ajax (post) call to another route ("service")
The "Service" controller associated to this route just loads the session data set in "main" and returns it to the main_view as data response to the ajax call

The problem is that in my PC (locally set virtualhost) this works fine, but when working on a https://codeigniterapp.mysite.com this does not work
The main route loads, the session data is set, cookie is set and written with correct values, etc.
But when the ajax call is made to "service", the session data is empty and an empty array is returned to the view

I've tried moving from
Code:
public string $driver = FileHandler::class;
to
Code:
public string $driver = DatabaseHandler::class;

The cookies are saved to database etc. correctly, but this didn't change the behaviour. The session data keeps being returned empty in the ajax call

Any ideas or suggestions to solve this?
Thanks a lot

Help Needed with Implementing a Binary Search Algorithm in Python

$
0
0
Hi everyone,
I'm trying to implement a binary search algorithm in Python, but I'm running into some issues. My current implementation doesn't seem to return the correct index of the target element. Here's the code I have so far:

Code:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

# Test case
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
print(binary_search(arr, target))  # Expected output: 4
The code works fine for some test cases, but it fails for others. For example, if the array contains duplicate elements or if the target is not present, the function doesn't always behave as expected.
Can anyone help me identify what's going wrong and how I can fix the implementation to handle all cases correctly? Also, are there any edge cases I should consider?
Thanks in advance for your help!
Viewing all 14343 articles
Browse latest View live