Home > Software design >  Codeigniter 4 Handle Request URI Segment If the URL is empty
Codeigniter 4 Handle Request URI Segment If the URL is empty

Time:10-04

I am using Codeigniter 4 framework and I have a function for getting the URI segment like

    $bahasa = $request->uri->getSegment(1);
    $url = $request->uri->getSegment(2);
    $content = $request->uri->getSegment(3);

the code is working if the URL most like: http://localhost:8080/segment1/segment2/segment3 but if I put the URL like http://localhost:8080/segment1/ the code is an error, the error is CodeIgniter\HTTP\Exceptions\HTTPException Request URI segment is out of range: 2

CodePudding user response:

Just use isset function to check either the segment is exists or not. Like bellow:

$url = isset( $request->uri->getSegment(2) ) ? $request->uri->getSegment(2) : '';

That's it!

CodePudding user response:

you can use this to check availability of your segement request

if($request->uri->getSegment(2) || $request->uri->getSegment(3)){
//response if the request is available
}else{
//response if the request is not available
}

if you still confuse you can read this documentation : https://codeigniter.com/user_guide/libraries/uri.html#creating-uri-instances

  • Related