i am using http://www.asual.com/jquery/address/ plugin and trying to parse some url, this is what i got:
<script>$(function(){
$.address.init(function(event) {
// Initializes the plugin
$('a').address();
}).change(function(event) {
$('a').attr('href').replace(/^#/, '');
$.ajax({
url: 'items.php',
data:"data="+event.value,
success: function(data) {
$('div#content').html(data)
}
})
});
})</script>
then HTML:
link02
link03
then im calling item.php, wich for now only has
echo $_GET["data"];
so after the ajax request has complete it echoes :
/items.php?id=2
/items.php?id=3
how can i parse this so i get only the var values? it is better to do it on client side?
and also if my html href is something like link02
jQuery address will ignore the &var=jj
cheers
You can use parse_url() to get the query string and then parse_str to get the query string parsed into variables.
Example:
<?php
// this is your url
$url = 'items.php?id=2&var=jj';
// you ask parse_url to parse the url and return you only the query string from it
$queryString = parse_url($url, PHP_URL_QUERY);
// parse_str can extract the variables into the global space or can put them into an array
// NOTE: for simplicity no validation is performed but in production you should perform validation
$params = array();
parse_str($queryString, $params);
// you can access the values like thid
echo $params['id']; // will output 2
echo $params['var']; // will output 'jj'
// I prefer this way, because it eliminates the posibility of overwriting another global variable
// with the same name as one of the parameters in the url.
// or you can tell parse_str to extract the variables into the global space
parse_str($queryString);
// or if you want to use the global scope
echo $id; // will output 2
echo $var; // will output 'jj'
Related
there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.
I need to get the URL of a website, but how do we do this in PHP?
For example there's a URL www.example.com/page.php?var=value, the URL is dynamic, I need to get the var=value portion of the URL. The URL is some other website so cannot use $_SERVER[] variables.
I cannot parse the URL since parse_url() requires an URL to be specified and I don't know the what the value of var will be, I want to fetch the URL using PHP script and then parse it.
Is there any way we can do this in PHP?
parse_url will parse the URL and return its components.
Reference: http://php.net/manual/en/function.parse-url.php
<?php
$url = 'www.example.com/page.php?var=value';
$query_string = parse_url($url, PHP_URL_QUERY );
echo $query_string;
?>
Output:
var=value
With parse_url() and parse_str() you can get the parameters:
$url = "www.example.com/page.php?var=value";
$urlParts= parse_url($url); // Separates the url
parse_str($urlParts['query'], $parameters);// Get the part you actually need it and create a array
var_dump($parameters) // Your parameters
Update:
Replace the var_dump to:
foreach($parameters as $key => $value) {
echo $key." = ".$value."<br />";
}
Im trying to send a query string in url
for ex : url : localhost/myfile.php?number=8777,+9822,+9883
in myfile.php when i give echo the query string :
echo $_REQUEST['number'];
output :
8777,9822,9883
but the expected output is :
8777,+9822,+9883
How can i display + sign also.
UPDATE :
actually that url is web request from the android/ios device app,
im providing webservice in php,
so android/ios developers are sending request with a querystring contains + sign
so how can i handle this situation?
+ is reserved. PHP is correct in translating an unencoded + sign to a space.
You can use urlencode() urldecode() for this.
The + must be submitted in PHP as the encoded value: %2B
You should then use urlencode() function to create that url:
<?php
var_dump($_GET['number']);
echo 'http://localhost/myfile.php?number='.urlencode('8777,+9822,+9883');
EDIT
If this is url that you receiving and cannot do anything with that you can use for example:
echo substr($_SERVER['REQUEST_URI'],strpos($_SERVER['REQUEST_URI'],'=')+1);
and you will get
8777,+9822,+9883
Sorry, i dont know what you're trying to do, but here's a suggestion
// where base64_encode('8777,+9822,+9883') = ODc3NywrOTgyMiwrOTg4Mw
localhost/myfile.php?number=ODc3NywrOTgyMiwrOTg4Mw
// on myfile.php
echo base64_decode($_REQUEST['number']);
// this will output -> 8777,+9822,+9883
UPDATE ---------------------------
if you have no other choice , you can use this
<?php
// get URL query string
$params = $_SERVER['QUERY_STRING'];
// if you have $params = www.mydomain.com/myfile.php?number=9988,+9876,+8768
$temp = explode('=', $params);
echo $temp[1] .'<hr>';
// if you have $params = www.mydomain.com/myfile.php?number=9988,+9876,+8768&number2=123,+456,+789
$params2 = $_SERVER['QUERY_STRING'];
$temp3 = explode('&', $params2);
foreach($temp3 as $val){
$temp4 = explode('=', $val);
// # // $GET = $temp4[0]; // if you need the GET VALUES
$VALUE = $temp4[1];
echo $VALUE .'<br>';
}
?>
Hope this helps.... :)
I want remove a parameter from a URL:
$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
I am trying to get this result:
https://stackoverflow.com/?name=alaa&
https://stackoverflow.com/?&star=5
I am trying to do it using preg_replace, but I've no idea how it can be done.
$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);
Relying on regular expressions can screw things up sometimes..
You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.
Once you have that array, you can edit it as you wish and remove parameters.
Once, completed, use the http_build_url() function to rebuild the URL with the changes made.
Check the docs here..
Parse_Url Http_build_query()
EDIT
Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.
You can even use explode() with & as the delimeter to get this done.
I would recommend using a combination of parse_url() and http_build_query().
Handle it correctly! !
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}
A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page
parse_url() and parse_str() are buggy. Regular expressions can work but have the tendency to break. If you want to correctly deconstruct, make changes, and then reconstruct a URL, you should look at:
http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
ExtractURL() generates parse_url()-like output but does much more (and does it right). CondenseURL() takes an array from ExtractURL() and constructs a new URL from the information. Both functions are in the 'support/http.php' file.
Years later...
$_GET can be manipulated like any other array in PHP. Simply unset the key and create the http query using the http_build_query function.
// Populate _GET with sample data...
$_GET = array(
'value_a' => "A",
'key_to_remove' => "Don't delete me bro!",
'value_b' => "B"
);
// Should output everything...
// "value_a=A&key_to_remove=Don%27t+delete+me+bro%21&value_b=B"
echo "\n".http_build_query( $_GET );
// Remove the key from _GET...
unset( $_GET[ 'key_to_remove' ] );
// Should output everything else...
// "value_a=A&value_b=B"
echo "\n".http_build_query( $_GET );
This is working for me:
function removeParameterFromUrl($url, $key)
{
$parsed = parse_url($url);
$path = $parsed['path'];
unset($_GET[$key]);
if(!empty(http_build_query($_GET))){
return $path .'?'. http_build_query($_GET);
} else return $path;
}
First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.
Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.
In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package
The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.