In this URL: www.example.com/transaction/summary/10 I can get 10 by this:
$this->uri->segment(3);
But, along with some other GET params how can I get that value?
e.g.: www.example.com/transaction/summary?local_branch=1/10
PS: GET params could be more than 1.
If you still want to keep CI style than add segments:
URL:
www.example.com/transaction/summary/10/1/TEST
Segments:
$this->uri->segment(3); // 10
$this->uri->segment(4); // 1
$this->uri->segment(5); // TEST
Or if you want to use query string than you can add params in query string and get values by using $_GET:
www.example.com/transaction/summary/10/?local_branch=1&test=test
Ok, segments in Codeigniter are the content between slashs like mysite.com/page/page-name. To get the page-name value I get the second segment, or $this->uri->segment(1). To get the strings passed by query string ($_GET), you can simply use the $_GET['local_branch'] as in your example or in case of Codeigniter, as the #Tom answer: $this->input->get('local_branch').
In this case, you can to explode the values delimiting by /.
$localBranch = $_GET['local_branch'];
// Or
$localBranch = $this->input->get('local_branch');
// And split using the / as delimiter if is need.
$localBranch = explode('/', $localBranch);
// Output
// Array(0 => 1, 1 => 10)
This way many values can be passed in same query string.
To get these GET parameters you can just use:
$this->input->get('some_variable', TRUE);
As per the SO link here.
example.com/?some_variable=hey
Related
I am attempting to use the Airtable API to retrieve records from my data there - specifically, a list of URLs I have in column cells.
I wrote a function, get_airtable_records, to do the API call via curl and it works - returning results as a Json object. Specifically, I am pushing the URLs to an array, $article_urls.
The only problem is, Airtable limits the return of results to "pages" of a maximum 100 records, and my data contains more than that. The API accepts parameters maxRecords and pageSize but the more important one, pageSize, is still capped at 100.
What Airtable does also return is another Json value, offset, which is used in such cases for pagination. The offset is a record ID intended to be used as an input parameter (also called offset). You can use it to denote the starting record in a subsequent additional API call. I understand this.
What I don't understand is how to modify my code to account for the possibility of needing to poll Airtable again.
In other words, we should always do a starting run from scratch, when there is no offset value.
Then, if an offset value is present in returned results, we should go around again - until an offset value is not present.
Here is what I have.
// Make get request, store result in array
$articles = get_airtable_records($offset); // $offset won't exist at the start
// Prepare Article URLs list as an array
if (!isset($article_urls)) {
$article_urls = array();
}
// For each URL found in Airtable
foreach($articles['records'] as $record){
$url = $record['fields']['Published URL'];
// Add to our array list
if (!empty($url)) {
array_push($article_urls, $url);
}
}
// URL list after first pass:
echo '<pre>';
print_r($article_urls);
echo '</pre>';
// May hit a max of 100
// echo 'Offset: ' . $articles['offset'];
// Value like "itrJYSLx0RfslI80f/recEu6TiPTPCSDxg5" may exist.
// If so, go back to start, do get_airtable_records($offset) again and array_push
// Until, once more there is no "offset" value at end
I am speculating that some sort of while loop will be useful... ?
A couple of things are true...
In the first call, there will be no originating offset value needing to be passed, since it starts from record 0.
But that and subsequent passes may generate an offset value, which should be used to make another pass.
The final call will not generate an offset value, since it will have returned the final page of exhausted results, and there is no need to start again.
Thanks largely to #anthony's answer to a similar question here, I seem to have some working code...
// Prepare Article URLs list as an array
$article_urls = array();
// Call Airtable records in pages of 100 max
do {
// Offset is either inherited from last page's results, or is nothing
$offset = $articles['offset'] ?: "";
// Make get request, store result in array
$articles = get_airtable_records($offset);
// For each URL found in Airtable
foreach($articles['records'] as $record){
$url = $record['fields']['Published url'];
// Add to our array list
if (!empty($url)) {
array_push($article_urls, $url);
}
}
} while(!empty($articles['offset'])); // If there's an offset value (ie. starting record of next page), do again
// Output URL list for check
echo '<pre>';
print_r($article_urls);
echo '</pre>';
Explanation seems to be:
Use a do while loop.
At the start of this, set offset to be either the value inherited from the previous run, or nothing.
My get_airtable_records function was already limiting the presence or not of offset in the API call, with the following, which adds the offset query string to the URL for the next API call if one is present...
if (!empty($offset)) {
$q_offset = '&offset='.$offset;
}
I have tested this and it gave me all 137 results from two pages in to my $article_urls array. I haven't tested it with any more than two pages of results.
Recursive anonymous functions also work well for an auto paginator.
// http client
$client
// closure
$autoPaginate = function (int $offset) use (&$autoPaginate, $client) {
$response = $client->get('https://blah.com, [
'offset' => $offset,
'per_page' => 100,
]);
// do response business logic/work
// check your response meta or
// wherever the next page or offset is passed back
if (!$response->meta->next->offset) return;
return $autoPaginate($response->meta->next->offset);
};
$autoPaginate(0);
I am trying to pass the value to a function to get the following url:
search?channelIds=1,2,3&streamName=wew&page=0&size=10
code inside function:
$this->request->set("url","broadcasts/pubic/search");
$this->request->set_fields(array(
'channelIds'=>$channel_ids,
'streamName'=>$stream_name,
'page'=>$page,
'size'=>$size
));
$result = $this->request->send();
Here i pass the values in this format.How will give pass value for channelIds=1,2,3? i use http_build_query for url formation. $channel_ids=array("channelIds"=>1, "channelIds"=>2, "channelIds"=>3); $stream_name="wew"; $page=0; $size=10; $getlivebroadcast = $api-searchBroadcast($channel_ids,$stream_name,$page,$size);
How will i set the value?
You can use the urlencode function to encode the channel ids. Your function may look like:
$this->request->set("url","broadcasts/pubic/search");
$this->request->set_fields(array(
'channelIds'=>urlencode($channel_ids),
'streamName'=>$stream_name,
'page'=>$page,
'size'=>$size
));
$result = $this->request->send();
Encoded URL
www.example.com/apps/?bmFtZTE9QUhTRU4mbmFtZTI9TUFFREEmcGVyY2VudD02NQ
Decoded URL
www.example.com/apps/?name1=AHSEN&name2=MAEDA&percent=65
now i want to get params from encoded URL
ob_start();
$name1 = $_GET['name1'];
You probably have the decoded url somewhere in a variable. If you extract the query part from it (the part after the ?), you can feed that query string to the function parse_str.
If you use parse_str with just the query string as argument, it sets the appropriate variables automatically. For example
// whereever you get the query part of your decoded url from
$my_query_string = "name1=AHSEN&name2=MAEDA&percent=65";
// feed it into parse_str
parse_str($my_query_string);
would set the global variables
$name1
$name2
$percent
But I'd advise to make use of the second parameter that parse_str offers, because it provides you with better control. For that, provide parse_str with an array as second parameter. Then the function will set the variables from your query string as entries in that array, analogous to what you know from $_GET.
// whereever you get the query part of your decoded url from
$my_query_string = "name1=AHSEN&name2=MAEDA&percent=65";
// provide parse_str with the query string *and* an array you want the results in
parse_str($my_query_string, $query_vars);
echo $query_vars['name1']; // should print out "AHSEN"
UPDATE: To split your complete decoded url, you can use parse_url.
You can use the function urldecode.
This should get you started...
<?php
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("Value for parameter \"%s\" is \"%s\"<br/>\n",
urldecode($param[0]), urldecode($param[1]));
}
}
?>
I have two strings in PHP:
$Str1 = "/welcome/files/birthday.php?business_id=0";
$Str2 = "/welcome/index.php?page=birthday";
I have to get word birthday from this two string with a single function.
I need a function which returns birthday on both case.
example
function getBaseWord($word){
...
return $base_word;
}
getBaseWord('/welcome/files/birthday.php?business_id=0');
getBaseWord('/welcome/index.php?page=birthday');
both function call should return "birthday".
How can i do it.
If I correctly understand what you are trying to do then this should do what you need:
function getWord(){
return $_GET['page'];
}
or $_GET['business_id'];
I think $_GET is an associative array made from the GET request that was sent to the page. An associative array is one where you access something like ['name of the element'] instead of [1] or [2] or whatever.
So what you will need to do is get all of the actual GET variables extracted from the string:
//Seperate the URL and the GET Data
list($url,$querystring) = explode('?', $string, 2);
//Seperate the Variable name from its value
list($GETName, $GETValue) = explode("=", $querystring);
//Check to see if we have the right variable name
if($GETName == "page"){
//Return the value of that variable.
return $GETValue;
}
NOTE
This is very BASIC and will not accept more then one GET parameter. You will need to modify it if you plan on have more variables.
I have no idea what you are talking about but, you can cut the word "birthday" with str_replace and replace with another word, or you can find the position with stripos, I have no idea what we are trying to do here, so those are the only things come to my mind
This is a two part question. First how can I grab the last url value from a link when I dont know how deep the value is, for example how can I grab
the last value of sub_4 from the link example below using PHP? And second how can I grab the url value cat=3 and the last url value sub_4 using PHP?
I'm kind of new to PHP so a detailed step by step example would help me out a lot if its not too much trouble.
Thanks in advance!
Here is an example of a URL value.
http://www.example.com/categories/index.php?cat=3&sub_1=sub1&sub_2=sub2&sub_3=sub3&sub_4=sub4
All variables from the hook will be returned on $_GET. So if you want to get that value from the URL, just use:
$_GET['sub_4']
If you want to get a list of all of the possible values:
array_keys($_GET)
This will give you all of the variables.
UPDATE: I just reread your question. I think I better understand what you are looking for. Correct me if I am wrong, but you are not certain how to get the last element of the string? Is that right? So you could potentially have sub_5, sub_6, sub_7 etc. Here is how to get the last element from the string:
end($_GET);
$key = key($_GET);
$last_item = $_GET[$key];
$last_item will now have sub_4 (or what ever the last item is).
Extracting URL Parameters
Query parameters (anything in the URL with ?name or &name) are saved in the $_GET superglobal.
If sub is a hierarchy, you should probably just write it as such. For instance: ?sub=path/to/sub or ?sub=path:to:sub
From this you can explode() on your separator (/ or :) to get the different parts of the sub parameter. $sub_array = explode('/', $_GET['sub']);
You can then iterate over the array using a foreach or directly access the highest branch of the hierarchy using count():
$sub_array[count($sub_array-1)];
Building URL Parameters
If you have an array of subs that you want to use to generate a URL, you can use implode() to build your URL params. $sub_params = implode('/', $_GET['sub']);
You might construct that array by appending each sub to the $sub_array.
$sub_array[] = 'sub1';
$sub_array[] = 'sub2';
$sub_array[] = 'sub3';
etc.
Inspect the Data
If you get lost, use var_dump($_GET) or var_dump($variable) to see what's inside it.
Each cat=3 or sub_1 value can be retreived by $_GET['cat'] and $_GET['sub_1'] respectively. To elaborate, $_GET['NAME_OF_PROPERTY'] would look like php.net/index.php?NAME_OF_PROPERTY=whatever
It seems like both questions were on how to grab the value from the URL, so I hope that answers both.
In your example url http://www.example.com/categories/index.php?cat=3&sub_1=sub1&sub_2=sub2&sub_3=sub3&sub_4=sub4
echo $_GET['cat']; // 3
echo $_GET['sub_1']; // sub1
echo $_GET['sub_2']; // sub2
echo $_GET['sub_3']; // sub3
echo $_GET['sub_4']; // sub4
For the first part; you should use the $_GET[] array which contain every parameter passed in the url $_GET['cat'], $_GET['sub_1'].
For the second part, in your case you should try send an array in parameter like this :
http://www.example.com/categories/index.php?cat=3&sub[1]=sub1&sub[2]=sub2&sub[3]=sub3&sub[4]=sub4
And then use the $_GET['sub'][] array $_GET['sub'][1], $_GET['sub'][2], ...
Now you can determine the length of the array and know the last item in it.
This example is under the assumption you want to find the very first variable in the GET query, and the very last:
<?php
// Here, you separate all the variables
$parameters = explode("&", $_SERVER['QUERY_STRING']);
// Get the last key's index
$last_key_index = count($parameters)-1;
// Easy way for PHP 5.3
$first_key = strstr($parameters[0], "=", true);
$last_key = strstr($parameters[$last_key_index], "=", true);
// Bit longer otherwise
$first_key = substr($parameters[0], 0, strpos($parameters[0], "="));
$last_key = substr($parameters[$last_key_index], 0, strpos($parameters[$last_key_index], "="));
// Test it here
echo($first_key);
echo($last_key);
?>