Codeigniter: URI segments - codeigniter

How do I create an if statement saying something like this?
Basically, how do you use the URI class to determine if there is a value in any segment?
$segment = value_of_any_segment;
if($segment == 1{
do stuff
}
I know this is pretty elementary, but I don't totally understand the URI class...

Your question is a little unclear to me, but I'll try to help. Are you wondering how to determine if a particular segment exists or if it contains a specific value?
As you are probably aware, you can use the URI class to access the specific URI segments. Using yoursite.com/blog/article/123 as an example, blog is the 1st segment, article is the 2nd segment, and 123 is the 3rd segment. You access each using $this->uri->segment(n)
You then can construct if statements like this:
// if segment 2 exists ("articles" in the above example), do stuff
if ($this->uri->segment(2)) {
// do stuff
}
// if segment 3 ("123" in the above example) is equal to some value, do stuff
if ($this->uri->segment(3) == $myValue) {
// do stuff
}
Hope that helps! Let me know if not and I can elaborate or provide additional information.
Edit:
If you need to determine if a particular string appears in any segment of the URI, you can do something like this:
// get the entire URI (using our example above, this is "/blog/article/123")
$myURI = $this->uri->uri_string()
// the string we want to check the URI for
$myString = "article";
// use strpos() to search the entire URI for $myString
// also, notice we're using the "!==" operator here; see note below
if (strpos($myURI, $myString) !== FALSE) {
// "article" exists in the URI
} else {
// "article" does not exist in the URI
}
A note regarding strpos() (from the PHP documentation):
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
I hope my edit helps. Let me know if I can elaborate.

Related

Codeigniter 4 - how to get the first row and the last row of a result

I am trying to get the first row and the last row of a query result. I see from Ci4's docs, there are two methods to help, namley, getFirstRow([$type = 'object']) and getLastRow([$type = 'object']) but I am having difficulty using them. Here is my method so far:
function getLoginFailCount($login_fail_ip, $max_login_attempts = 3, $within_seconds = 320){
$builder = $this->builder('login_fail');
$builder->where('login_fail_ip', $login_fail_ip);
$builder->orderBy('login_fail_created_at','DESC');
$query = $builder->get(3);
print_r($query->getFirstRow($query));
}
I get an error at getFirstRow as follows;
Argument 1 passed to CodeIgniter\Database\BaseResult::getFirstRow() must be
of the type string, object given
How can I get getFirstRow() to work? Doesn't this doc definition say I need to pass it an object? Why does the error say it my be of type string
Well in the documentation for getFirstRow() it states that you can use
$row = $query->getFirstRow() // which will give you an object
OR
$row = $query->getFirstRow(‘array’) // which will give you an Array
So your error message, which states...
Argument 1 passed to CodeIgniter\Database\BaseResult::getFirstRow()
must be of the type string, object given
Would make you look and say to yourself, I had better go and read the documentation. So you can either pass in nothing, or a String 'array'.
So now can you see why
$query->getFirstRow($query))
does not make any sense! Why would you pass in the $query object as parameter.
You may have misread the documentation. I see you stated getFirstRow([$type = 'object'])
You might have got a little confused by that...
[$type = 'object'] means that the $type is defaulted to be the string 'object' so the returned type is an object by default with No Parameter being passed in.
If you want it to return an array, then you would specify the string 'array'. So then the $type parameter would be set to the string 'array' and return an array instead of an object.
Does that help!

Construct routes(urls) with slugs separated by dash in laravel

I am about to make more SEO-friendly URLs on my page and want a pattern looking like this for my products:
www.example.com/product-category/a-pretty-long-seo-friendly-product-name-12
So what are we looking at here?
www.example.com/{slug1}/{slug2}-{id}
The only thing I will care about from the URL in my controller is the {id}. The rest two slugs are just of SEO purpose. So to my question. How can I get the 12 from a-pretty-long-seo-friendly-product-name-12?
I have tried www.mydomain.com/{slug}/{slug}-{id} and in my controller to try and get $id. Id does not work. I am not able to able to separate it from from a-pretty-long-seo-friendly-product-name. So in my controller no matter how I do I get {slug2} and {id} concatenated.
Coming from rails it is a piece of cake there but can't seem to figure out how to do that here in laravel.
EDIT:
I am sorry I formulated my question very unclear. I am looking for a way to do this in the routes file. Like in rails.
You're on the right track, but you can't really logically separate /{slug}-{id} if you're using dash-separated strings. To handle this, you can simply explode the chunks and select the last one:
// routes/web.php
Route::get('/{primarySlug}/{secondarySlugAndId}', [ExampleController::class, 'example']);
// ExampleController.php
public function example($primarySlug, $secondarySlugAndId){
$parts = collect(explode('-', $secondarySlugAndId));
$id = $parts->last();
$secondarySlug = $parts->slice(0, -1)->implode('-');
... // Do anything else you need to do
}
Given the URL example.com/primary-slug/secondary-slug-99, you would have the following variables:
dd($primarySlug, $secondarySlug, $id);
// "primary-slug"
// "secondary-slug"
// "99"
The only case this wouldn't work for is if your id had a dash in it, but that's another layer of complexity that I hope you don't have to handle.
Route::get('/test/{slug1}/{slug2}','IndexController#index');
public function index($slug1, $slug2)
{
$id_slug = last(explode('-',$slug2));
$second_slug = str_replace('-'.$id_slug,'',$slug2);
dd($slug1, $second_slug,$id_slug);
}

Get segment from url CodeIgniter but not first

I know i can get all segments from url like this
Lets say i have this example link
www.example.com/de/products.html
Using url_helper like this:
$data['url'] = $this->uri->uri_string();
I will get value like this
de/products
But i dont need first segment de, only products, the problem is that
i dont know how many segments it will be, i only need to remove the first
Is there possible to forget first segment with url helper in CI?
Try like this...
Use the php's explode() function to make the url string as array.Then apply array's array_shift() function which always removes the first element from array.
Code is looks like as below
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
//print_r($arr);
Then use the php's implode() method to get the URI without first segment.Hope it will works...
$uri=implode('/',$arr);
echo $uri;
There is no URL helper in the CI to forget the first segment. However you can easily make a custom one and put #Hikmat's answer below it in the application/helpers/MY_url_helper.php in the Core folder.
e.g.
function my_forget_first_segment() {
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
$uri=implode('/',$arr);
return $uri;
}
Before Edit answer.
You need to try this
$second_segment = $this->uri->segment(2);
From Codeigniter documentation -
$this->uri->segment(n);
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news
2. local
3. metro
4. crime_is_up
The optional second parameter defaults to NULL and allows you to set the return value of this method when the requested URI segment is missing. For example, this would tell the method to return the number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);
example:
<?php
$data=$this->uri->segment(2);
$val=explode('.', $data);
echo $val[0];
?>

Format Output of Placeholder

I am creating a dynamic list of placeholders, some of the values held in these place holders are decimal numbers that are supposed to represent money.
What I'm wondering is if there is a way I can format them to display as such?
Something like [[+MoneyField:formatmoney]]
I see http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/customizing-content/input-and-output-filters-(output-modifiers) but I do not see a way to do this here.
You most definitely can, under the header "Creating a Custom Output Modifier" on the link you posted it's described how you can place a snippet name as a output modifier. This snippet will recieve the [[+MoneyField]] value in a variable called $input.
So you'd have to create this custom snippet which could be as simple as
return '$'.number_format($input);
Another version of doing this is calling the snippet directly instead of as an output modifier like so:
[[your_custom_money_format_snippet ? input=`[[+MoneyField]]`]]
I'm not sure if theres any difference between the two in this case. Obviously you can pass any value into the number format snippet when calling it as a snippet instead of an output modifier. And i'm sure theres a microsecond of performance difference in the two but i'm afraid i don't know which one would win. ;)
Update:
Actually found the exact example you want to implement on this link;
http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/customizing-content/input-and-output-filters-%28output-modifiers%29/custom-output-filter-examples
Snippet:
<?php
$number = floatval($input);
$optionsXpld = #explode('&', $options);
$optionsArray = array();
foreach ($optionsXpld as $xpld) {
$params = #explode('=', $xpld);
array_walk($params, create_function('&$v', '$v = trim($v);'));
if (isset($params[1])) {
$optionsArray[$params[0]] = $params[1];
} else {
$optionsArray[$params[0]] = '';
}
}
$decimals = isset($optionsArray['decimals']) ? $optionsArray['decimals'] : null;
$dec_point = isset($optionsArray['dec_point']) ? $optionsArray['dec_point'] : null;
$thousands_sep = isset($optionsArray['thousands_sep']) ? $optionsArray['thousands_sep'] : null;
$output = number_format($number, $decimals, $dec_point, $thousands_sep);
return $output;
Used as output modifier:
[[+price:numberformat=`&decimals=2&dec_point=,&thousands_sep=.`]]

Best practice in handling invalid parameter CodeIgniter

Let's say I have a method at Controller named
book($chapter,$page);
where $chapter and $page must be integer. To access the method, the URI will look like
book/chapter/page
For example,
book/1/1
If user try to access the URI without passing all parameter, or wrong parameter, like
book/1/
or
book/abcxyz/1
I can do some if else statements to handle, like
if(!empty($page)){
//process
}else{
//redirect
}
My question is, is there any best practice to handle those invalid parameters passed by user? My ultimate goal is to redirect to the main page whenever there is an invalid parameter? How can I achieve this?
Using the CodeIgniter routing in config/routes.php is pretty useful here, something like this:
$route['book/(:num)/(:num)'] = "book/$1/$2";
$route['book/(:any)'] = "error";
$route['book'] = "error";
Should catch everything. You can have pretty much any regular expressions in the routes, so can validate that the parameters are numeric, start with a lowercase letter, etc..
The best logic here seems to be adding the default values:
book($chapter = 1, $page = 1);
and then checking if they are numeric
So it automatically opens the 1st page of the 1st chapter if there are parameter missing or non-numeric.

Resources