parse_str doesn't work when the question mark is present? - php

why I get error when I pass the string with something like 'form.php?', for instance,
parse_str('form.php?category=contacts');
echo $category;
I get this,
Notice: Undefined variable: category in C:\wamp\www\1hundred_2011_MVC\applications\CMS\category_manage.php on line xx
but,
parse_str('category=contacts');
echo $category;
I get what I want,
contacts
how can I fix it? I have to pass something like 'xxx.php?category=contacts' to get 'contacts' or something in the variable.
thanks.

The function parse_str only parses the query string, not the entire URL. Try using parse_url with the component set to PHP_URL_QUERY to extract the query string first, then use parse_str on that.
$url_query = parse_url('form.php?category=contacts', PHP_URL_QUERY);
parse_str($url_query, $output);
echo $output['category'];
Result:
contacts
See it at ideone.

parse_str will only accept query strings:
$q = 'foo?hello=world';
parse_str($q);
echo ${'foo?hello'}; // outputs 'world'
Strip the beginning of the URL first:
$q = 'foo?hello=world';
parse_str(substr($q, strpos($q, '?')+1);
echo $hello; // outputs 'world'
Consider using parse_str second argument to have the data in an array instead, to avoid overwriting local variables.

You may want to use urldecode plus return extracted variables like so:
... some helper class...
/**
* Return parsed serialized JQuery object as PHP array of extracted variables
*/
protected static function parseFields($encoded){
parse_str(urldecode($encoded));
unset($encoded);
return get_defined_vars();
}
Also, you may want to utilize the JQuery function "$.param(data)" for creating URL encoded string:
var encoded=$.param(fields);
and submit via AJAX/POST request to server to function parseFields().

Related

Access "complex" object attributes from string in PHP

I have an object and need to access an attribute from a string like this:
$string = 'items[0]->sellers[0]->commertialOffer->Price';
I've tried something like this but it doesn't work:
$myObject->{$string};
Any idea?
$items = '{"items":[{"sellers":[{"commertialOffer":{"Price":33}}]}]}';
$myObject = json_decode($items);
$string = 'items[0]->sellers[0]->commertialOffer->Price';
echo ($myObject->{'items'}[0]->{'sellers'}[0]->{'commertialOffer'}->{'Price'});
echo ($myObject->items[0]->sellers[0]->commertialOffer->Price);
As $myObject->items is an array you can`t access it like
$string = 'items[0]';
echo $myObject->{$string};
You can access that by using
$string = 'items';
echo $myObject->{$string}[0];
Are you passing the string between two functions ? If yes , then take 4 values and create the string like :-
$string = $value1.'|'.$value2.'|'.$value3.'|'.$value4 ;
Then explode the string and get back the 4 values .
You probably want to revise your problem because interpreting raw code from a string is often a bad idea. You could potentially use the eval function: see. Again, this is probably not a good idea: when is eval evil?

GET Request not working in WordPress

I'm trying to pull a string from my URL in WordPress, and create a function around it in the functions file.
The URL is:
"https://made-up-domain.com/?page_id=2/?variables=78685,66752"
My PHP is:
$string = $_GET("variables");
echo $string;
So I'm trying to return "78685,66752". Nothing happens. Is the first question mark a problem? Or what am I doing incorrectly? Thanks!
$_GET should be in the form
$string = $_GET["variables"];
and not
$string = $_GET("variables");
$_GET is not a function but an Array so correct way of reading it is
$string = $_GET['variables'];
You are also creating the query string all wrong, you should be using
?variables=123,456&page=1
Read more about $_GET here http://php.net/manual/en/reserved.variables.get.php
Your URL should be like:
https://made-up-domain.com/?page_id=2&variables=78685,66752
instead of:
https://made-up-domain.com/?page_id=2/?variables=78685,66752
& char is separating the queries in URL.
And you have syntax error. Use $string = $_GET["variables"]; because $_GET is a superglobal array, not a function.
Use $variables = explode(",", $string); separate values into an array if you want. Simplier way is $variables = explode(",", $_GET["variables"]);
You should format your href and get parameter like this
http://example.com/mypage.html?var1=value1&var2=value2&var3=value3
+ Edit your get method syntax
$string = $_GET['variables'];

String function to extract only ID from URL

I have this string:
solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1
How can I extract just the part of the id, just the value of the ID, the
80d28c22-68d9-11e3-af95-742f689f29f1
I tried the substring function of PHP, the problem is I'm still figuring out how to tell it that it's all the way till the end of the string.
This is what I have so far:
$_solutionID = substr($_currentURL, 17, ??);
try this:
$id = $_GET['id'];
That should work :)
You can retrieve that value from the GET superglobal array: $_GET['id']
You can use $_GET variable for your purpose:
echo $_GET['id'];
# => 80d28c22-68d9-11e3-af95-742f689f29f1
$_GET is a superglobal that is available anywhere in a PHP script, and can be used to check the values of query parameters in a URL, i.e. it stores an associative array of all query parameters of the current page URL.
Also, for reference, if you happen to issue a POST request and would like to find the data that was posted to that URL, you can use $_POST variable in exactly the same manner as the $_GET variable.
I suggest you to use parse_url to extract the query (after the '?') and a regex to extract the id after the 'id='.
$parts = parse_url('solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1');
$query = $parts['query'];
$matches = array();
if (preg_match('/id=([-0-9a-z]+)/', $query, $matches) {
return $matches[1];
}

PHP store function in array

i want to store function in array
send the array to another page
then execute it
i already read Can you store a function in a PHP array but still don't know what to do
here's what i try
control.php (it start here)
<?php
function getFirstFunction(){ echo "first function executed"; }
$data = array();
$data[0] = getFirstFunction();
$data[1] = function(){ echo "second function executed"; };
$data[2] = function(){ require_once "additional.php"; };
$data[3] = "my string";
header('Location: view.php?data='.$data);
?>
additional.php
<?php echo "additional included" ?>
view.php
<?php
if( isset($_GET['data']) ){
foreach( $_GET['data'] as $temp ){
if( is_callable($temp) ){
$temp;
}else{
"its not a function";
}
}
}
?>
my error =
Warning: Invalid argument supplied for foreach() in D:\Workspace\Web\latihanns\php\get\view.php on line 4
EDIT
thanks for notify that this code its dangerous.i'm not use this code in real live. i just try to learn store function in array then call it. then i just curious how if i call it on another page. i just simply curious... i make my code look clear and simple here because i afraid if i wrote complicated code, no one will be here or my post will closed as too localized...
If you want to pass anything than string into URL, only option is convert it to string form which is reversible to original types. PHP offers function called serialize() which converts anything to string. After that, you can call unserialize() to convert string back to original data. So you have to change one line in control.php to this:
header('Location: view.php?data='.serialize($data));
In file view.php you have to change one line to this:
foreach( unserialize($_GET['data']) as $temp ){
But you have to fix more things than this. If you have callable variable, you can't invoke function with $variable, but with $variable(). It is good to mention, that in PHP does not matter if you have real function (anonymous function, Closure etc.) in variable, or if variable is simple string with name of exists function.
However you have even another bug in control.php. Code $data[0] = getFirstFunction(); will not pass function getFirstFunction an make it callable, it just calls the function and put its return value to variable. You can define getFirstFunction as anonymouse function like function in $data[1] or just pass it as string like $data[0] = 'getFirstFunction' which will work.
At the end - as anyone mentioned here - IT IS VERY DANGEROUS ans you shouldn't use this on public server.

How to extract two variables from this string in PHP

I have a string like this :
oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc
How can I extract the two variables oauth_token and oauth_token_secret from the about string using PHP
NOTE: this is not coming from the URL( we can do that using $_GET)
Thank YOU
Use parse_str() for parsing query string parameters.
// Extract into current scope, access as if they were PHP variables
parse_str($str);
echo $oauth_token;
echo $oauth_token_secret;
// Extract into array
parse_str($str, $params);
echo $params['oauth_token'];
echo $params['oauth_token_secret'];
You may wish to urldecode() the variables after you've extracted them.
try this
$text = "oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc"
;
$i=explode('&',$text);
$j=explode('=',$i[0]);
$k=explode('=',$i[1]);
echo $j[0]."<br>";
echo $j[1]."<br>";
echo $k[0]."<br>";
echo $k[1]."<br>";
1, split the two parts of the $string,
$str_array = explode('&',$string);
2, get the part after the "=" sign, so for the oauth_token part:
$oauth_token_array = explode('=',$str_array[0]);
$oauth_token = $oauth_token_array[1];
EDIT: ignore this, it's definitely verbose. BoltClock's the solution.
The best way (most reusable) is to use a function which returns an array similar to $_GET.
edit There is already a function for this: http://www.php.net/manual/en/function.parse-str.php This will work with array get values too.
$values = array();
parse_str($query_strng, $values);
Quite an ugly function, why can't it just return the array of values. It either stuffs them into individual variables or you need to pass in a reference. Come on php, you can do better. /rant

Categories