i'm trying to inject an extra param at the end of the query string of a url being passed as a value.
i have tried
<?PHP preg_replace('/(http:\/\/www.site.com)/i','$1',$_GET['url']."&EXTRA-PARAM");
but sometimes URL does not contain any query string. how can i make it start with ? instead of & if there is no query string presant
The preg_replace you have in your question has no effect:
preg_replace('/(http:\/\/www.site.com)/i','$1',$_GET['url']."&EXTRA-PARAM");
Whatever the last argument is, it will be returned by that preg_replace call. Either you don't have a match and nothing is replaced, or you have a match, but then you replace what you found with... what you found. So in both cases you get the same result.
$1 is a back-reference to http:\/\/www.site.com, so actually the quoted statement is equivalent to this:
preg_replace('/http:\/\/www.site.com/i','http:\/\/www.site.com',
$_GET['url']."&EXTRA-PARAM");
Your final value is always:
$_GET['url']."&EXTRA-PARAM"
So, you could just have used that, and skip the preg_replace.
What I answer here is how to better write that part ($_GET['url']."&EXTRA-PARAM"), i.e. the question: "inserting an extra param at the end of the URL".
This concatenation can lead to missing ?. Worse, it will not lead to a functional parameter if $_GET['url'] has a hash (#).
Here is a solution for that with preg_replace_callback. It takes into account that a given URL may or may not have:
a hash (#) component;
a question mark ?
some query after the ?
some & to separate query parts
The function accepts as second argument what needs to be added to the query part of the provided URL, which may be a string (must be URL encoded), or an associative array with items to add to the URL. This array will then be fed to the function http_build_query:
function addUrlQuery($url, $qry) {
if (!is_string($qry)) $qry = http_build_query($qry);
return preg_replace_callback("/^(.*?)(\?(.*?))?(#.*)?$/",
function ($matches) use ($qry) {
return $matches[1] . "?" .
(empty($matches[3]) ? "" : $matches[3] . "&") .
$qry .
(empty($matches[4]) ? "" : $matches[4]);
}, $url);
}
Example use:
$url = addUrlQuery($_GET['url'], "EXTRA-PARAM");
echo addUrlQuery("http://myserver.com?x#title", ["EXTRA-PARAM" => 1]);
echo addUrlQuery("http://myserver.com/" . $relative_url, "EXTRA-PARAM");
You can see the function run on several test cases on eval.in.
The problem with $_GET['url']
If you have a URL passed as a query argument to the current URL, like this:
http://myserver.com/index.php?url=http://test.com/index.php?a=1
Then you must realise this is not a good URL. Some characters need to be escaped. Certainly the ampersand (&) needs to be escaped. If you have this:
http://myserver.com/index.php?url=http://test.com/index.php?a=1&b=2
Ask yourself: is b a query parameter of the current URL, or of the URL passed as url argument?
The answer: it is a query parameter of the current URL. You would access it with $_GET['b']. And the value of $_GET['url'] is now just:
http://test.com/index.php?a=1
So... you need to escape & when you want b to be a query argument of the url parameter, and not of the current query:
http://myserver.com/index.php?url=http://test.com/index.php?a=1%26b=2
Note the %26: it is the code for &. Now if you look at $_GET['url'] you will get:
http://test.com/index.php?a=1&b=2
What if URL is provided without proper encoding?
In this case, you have to make assumptions. If you know for sure that the url parameter is the only parameter you will get on the current URL, then you can conclude that any other you get, really belong to the URL that is passed via that url parameter.
You would then take all the parameters from $_GET, except url, and add them (with the function above) to the value of $_GET['url'].
Related
I have a URL like this:
abc.com/my+string
When I get the parameter, it obviously it replaces the + with a space, so I get my string
I replaced the + in the url with %2B, then I use rawurldecode(), but the result is the same. Tried with urldecode() but I still can't get the plus sign in my variable, it's always an empty space.
Am I missing something, how do I get exactly my+string in PHP from the url abc.com/my%2Bstring ?
Thank you
In general, you don’t need to URL-decode GET parameter values manually, since PHP already does that for you, automatically. abc.com?var=my%2Bstring -> $_GET['var'] will contain my+string
The problem here was that URL rewriting was in play. As http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_b explains,
mod_rewrite has to unescape URLs before mapping them, so backreferences will be unescaped at the time they are applied.
So mod_rewrite has decoded my%2Bstring to my+string, and when you rewrite this as a query string parameter, you effectively get ?var=my+string. And when PHP applies automatic URL decoding on that value, the + will become a simple space.
The [B] flag exists to make mod_rewrite re-encode the value again.
Like this:
echo urldecode("abc.com/my%2Bstring"); // => abc.com/my+string
echo PHP_EOL;
echo rawurldecode("abc.com/my%2Bstring"); // => abc.com/my+string
Further if you want to get the actual my+string, you can utilize the powers of parse_url function which comes with PHP itself, although you have to provide a full URL into it.
Other way is just to explode the value by a / and get it like this:
$parts = explode('/', 'abc.com/my+string'); // => Array(2)
echo $parts[1] ?? 'not found'; // => string|not found
Also read the documentation on both: urldecode and rawurldecode.
Example here.
I have an URL like so:
http://local.mywebsite.com/index.php?p=edit_entry?id=3
and I want to retrieve only the p argument which value in this case above is "edit
_entry".
I have written:
$p = $_GET['p'];
echo $p;
But when I do so I get the value edit_entry?id=3
What should I do? I just want to retrieve edit_entry
That's an invalid URL. ? signifies the START of the query parameters, it's not a seperator BETWEEN parameters. You use & for that:
http://local.mywebsite.com/index.php?p=edit_entry&id=3
^---
Because the url should be:
http://local.mywebsite.com/index.php?p=edit_entry&id=3
^ ampersand
It should be & instead of ?
? is the delimiter which separates the URL from the PARAMETERS.
The parameters are separated by an ampersand &.
So you have to use index.php?param1=something¶m2=something&etc=etc
I am using $_SERVER["REQUEST_URI"] to get the current url. Then I am passing that url to another page via href.
echo "<a href='second.php?url=".$_SERVER["REQUEST_URI"]."'>Click here</a>";
//the url in this case is index.php?tit=most+wanted&id=23&c_id=11&ran=378834GSF844
Then on my second page when I do the below
$mc = $_GET['url'];
echo $mc;
I only get /index.php?tit=most+wanted
What happened to other three parameters? is it possible also to get rid of the slash on the front?
$_GET and $_POST are for single parameters only. $_SERVER['QUERY_STRING'] grabs the entire URL query.
Try to see the values of $_SERVER.
var_dump($_SERVER);
You can see the values and the suitable key you want.
I suggest you use $_SERVER["QUERY_STRING"] instead of $_SERVER["REQUEST_URI"].
About the results you have right now, its because of this character "&".
It acts as the delimiter and the next character from that point to the following character "=" will be the a key from $_GET variable and after that is the value.
i think these what you have right now:
$_GET["url"] = index.php?tit=most+wanted
$_GET["id"] = 23
$_GET["c_id"] = 11
$_GET["ran"] = 378834GSF844
Try using var_dump function to simply see the whole $_GET values.
var_dump($_GET);
I'm trying to put a script together for a client that needs to be able to accept a web address in a query string without it first being urlencoded. An example would be like this:
http://foo.com/script.php?url=www.amazon.co.uk/ESET-Smart-Security-User-Year/dp/B005NPFOBM/ref=sr_1_1?s=software&ie=UTF8&qid=1341685530&sr=1-1
However, when I echo out the contents of $_GET['url'] it gives me the following:
www.amazon.co.uk/ESET-Smart-Security-User-Year/dp/B005NPFOBM/ref=sr_1_1?s=software
So basically it seems to choke on the first ampersand - i'm guessing because it thinks that its another variable.
Aside form urlencoding, are there any tricks to getting this working? I could probably POST it from a form, but this defeats the idea of the script.
For this specific use case, you should use $_SERVER['QUERY_STRING'] instead. This will give you the full query string in one go, you can then split it yourself.
In your example, PHP is assuming that the & is the delimiter for the next GET variable.
you could ask the query parameters, and add them to the URL you received. List the remaining parameters in $_GET in the proper order, and add them add the end of $_GET['url'].
$_GET['url']
+ '&ie=' + $_GET['ie']
+ '&qid=' + $_GET['qid']
+ '&sr=' + $_GET['sr']
Be careful that you might get an extra parameter url someday.
http://foo.com/script.php?url=www.amazon.co.uk/ESET-Smart-Security-User-Year/dp/B005NPFOBM/ref=sr_1_1?s=software&ie=UTF8&qid=1341685530&sr=1-1&url=http://someAmazoneStuff
I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44
How can I always find & capture the value of the id which in this example is 2773?
I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.
Thanks
You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).
For example:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
print_r($vars); // see what's in there
// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));
// This will also work:
$id = intval($vars['id']);
echo "The id is $id\n";
See it in action.
You can use parse_str
You can use parse_url to parse URLs!
But you can use, to extract directly the numbers of ID variable:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;