How to get params from encoded current URL? - php

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]));
}
}
?>

Related

Decode JSON post data

My php file receives a post from ajax call. The string received by the php file is as follows :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
I am trying unsuccessfully to decode this string then loop through the values in the array. I have tried the following :
$myarray =json_decode($_POST["userid"],true);
foreach ($myarray as $value) {
//do something with value
}
I am not sure whether the decode is the issue or my syntax to loop through the PHP array.
The POST data you'd want to manipulate is stored in $_POST['userid]
In case you're trying to access this comma separated user ids, you need to convert this to an array first using explode(). And then loop through these id's.
if (isset($_POST)) {
$user_ids = $_POST['userid']; // assssssss,camo,castor
$user_id_arr = explode(',', $user_ids); // Converts string to array Array (0 => assssssss, 1 => camo, 2 => castor)
foreach ($user_id_arr as $user_id) {
//Statements
}
}
$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. So when you decode with json_decode that will decode JSON string to Object/Array.
But in your scenario you have not passed JSON String to $_POST so it not looks decoding.
The string you have passed into your $_POST is not JSON, so json_decode will not work on some random comma seperated values.
You can either pass in real JSON, or just use the explode method of splitting these values:
// explode example
$users = "assssssss,camo,castor";
$usersarray = explode(",", $users);

json_decode on serialized form Symfony2

I submit my form by ajax, here what I gets in controller:
$request->getContent()
return
string 'comment[header]=vcvdfgdfg&comment[body]=dfgfdgdf&comment[_token]=nV0QYu82KWFb-wRIlIoY4MKM6-WUfeFoMidjBHfpupA' (length=120)
when I try
json_decode($request->getContent(), true) // it equal to null
What I am doing wron?
That's not a json string. If you want to parse that string and get an array you have to use the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Or, if you're using Symfony2 you can access them this way:
// $_GET parameters
$request->query->get('name');
// $_POST parameters
$request->request->get('name');

Explode string into foreach

I have the following GET parameters:
?data=prop_123&data=prop_124&data=prop_125&data=prop_126&data=prop_129&data=prop_127
I was wondering if anybody knew a quick method of getting each value into a foreach? Thanks!
This won't work, because all of your parameters have the same name, so only the value "prop_127" is going to be passed to your script. You can create this as an array instead, like this:
?data[]=prop_123&data[]=prop_124&data[]=prop_125&data[]=prop_126&data[]=prop_129&data[]=prop_127
And then you can use foreach() to loop through them like this:
foreach ( $_GET['data'] as $data ) {
// This loops once for each instance of data[] in your URL
}
If you have no control over the URL, you'd have to read it in manually with $_SERVER['QUERY_STRING'], then parse through it to pull the values out.
Each data will overwrite the previous in $_GET or with parse_str so something like this maybe:
$s = 'data=prop_123&data=prop_124&data=prop_125&data=prop_126&data=prop_129&data=prop_127';
$s = str_replace('=', '[]=', $s);
parse_str($s, $a);
foreach($a as $something) { }
If you are actually trying to put the vars in a GET request and can get them from $_GET, then use the form data[] in the query string and then just foreach over $_GET.
You can use the PHP function: parse_str
http://www.php.net/manual/en/function.parse-str.php

How to get my word from following string?

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

How to grab a value from a url with multiple values using PHP. [2 Part Question]

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);
?>

Categories