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'];
Related
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?
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];
}
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().
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
Is it possible to sanitize all input sent by one method in PHP by simply doing
$var = mysql_real_escape_string($_POST);
and then access elements of $var as I would have of $_POST ?
I don't think you can call mysql_real_escape_string on an array.
But this would work
$cleanData = array_map('mysql_real_escape_string', $_POST);
array_map works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result.
Like superUntitled, I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array_map to achieve the same result.
As a side note, I would recommend using a function to sanitize your results:
function escape($txt) {
if (get_magic_quotes_gpc())
$txt = stripslashes($txt);
if (!is_numeric($txt))
$txt = "'" . mysql_real_escape_string($txt) . "'";
return $txt;
}
this function will remove html tags from anything you pass to it
function strip_html(&$a){
if(is_array($a)){
foreach($a as $k=>$v){
$a[$k]=preg_replace('/<[^<]+?>/','',$v);
}
}else{
$a=preg_replace('/<[^<]+?>/','',$a);
}
return;
}
What I find handy is to encapsulate the request data (Post, Get, Cookie etc) in to an Object and then to add a filter method which u can pass an array of function names to. This way you can use it like this:
$array = array('trim','mysql_real_escape_string');
$request->filter($array);
Body of the method works using a loop an array_map like in Mark's example. I wouldn't run the mysql_real_escape_string over my entire $_POST though, only on the necessary fields ( the ones that are getting queried or inserted )
#Shadow:
Array_Map will work with single dimension array but it wont work with multi-dimension arrays.
So, this will work.
$cleanData = array_map('mysql_real_escape_string', $_POST);
but if that $_POST array were to have another array, like this:
$array = $_POST['myArray']['secondArray'];
If you have an array such as above, array map will throw an error when you try to run a function that only takes a String as an argument, because it wont be handle to an array when its expecting just a string.
The solution provided on the below page is much more handy, and does it recursively for every element inside the array.
PHP -Sanitize values of a array