parse non encoded url - php

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.

Related

Remove one querystring parameter from a URL with multiple querystring parameters

I would like to remove a querystring parameter from a url that may contain multiple. I have succeeded in doing this using str_replace so far like this:
$area_querystring = urlencode($_GET['area']);
str_replace('area=' . $area_querystring, '', $url);
preg_replace also works, like this:
preg_replace('~(\?|&)area=[^&]*~', '$1', $url)
Either works fine for most URLs. For example:
http://localhost:8000/country/tw/?area=Taipei%2C+Taiwan&fruit=bananas
Becomes:
http://localhost:8000/country/tw/?&fruit=bananas
However, if the querystring contains an apostrophe html entity, nothing happens at all. E.g.:
http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas
The %27 part of the url (an apostrophe) seems to be the cause.
To be clear, I don't wish to remove all of the URL after the last /, just the area querystring portion (the fruit=bananas part of the url should remain). Also, the area parameter does not always appear in the same place in the URL, sometimes it may appear after other querystring parameters e.g.
http://localhost:8000/country/tw/?lang=taiwanese&area=Taipei%2C+Taiwan&fruit=bananas
You can use the GET array and filter out the area key. Then rebuild the url with http_build_query. Like this:
$url = 'http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas';
$filtered = array_filter($_GET, function ($key) {
return $key !== 'area';
}, ARRAY_FILTER_USE_KEY);
$parsed = parse_url($url);
$query = http_build_query($filtered);
$result = $parsed['scheme'] . "://" . $parsed['host'] . $parsed['path'] . "?" . $query;
You probably don't need urlencode() -- I'm guessing your $url variable is not yet encoded, so if there are any characters like an apostrophe, there won't be a match.
So:
$area_querystring = $_GET['area'];
should do the trick! No URL encoding/decoding needed.

Get only folder name from url in php without any file name with extension

I want to get foldername without any file name from a url in php?
My url is http://w3schools.com/php/demo/learningphp.php?lid=1348
I only want to retrieve the http://w3schools.com/php/demo from the url?
How to do this? Please help.
Try this,
$URL = 'http://w3schools.com/php/demo/learningphp.php?lid=1348';
$URL_SEGMENTS = explode("/", $URL);
foreach($URL_SEGMENTS as $Segment){
echo $Segment;
}
explode() will separate the string with / and provide an array. So you will have all url segments in foreach loop and you use it or store it in string or array.
After your comment let me show the script which will return your desire url.
$Desired_URL = $URL_SEGMENTS[2].'/'.$URL_SEGMENTS[3].'/'.$URL_SEGMENTS[4];
echo $Desired_URL;
If the url is stored in $url:
$url = 'http://w3schools.com/php/demo/learningphp.php?lid=1348';
You can do a preg_replace like so:
print(preg_replace('/\/[^\/]*$/', '', $url));
http://w3schools.com/php/demo
That regex means to replace everything from a / and all characters that are not / ... [^/]* ... to the end of the string ... $ ... with an empty string. Just delete them.

if else on variable link input

I have a method of pulling Youtube video data from API links. I use Wordpress and ran into a snag.
In order to pull the thumbnail, views, uploader and video title I need the user to input the 11 character code at the end of watch?v=_______. This is documented with specific instructions for the user, but what if they ignore it and paste the whole url?
// the url 'code' the user should input.
_gXp4hdd2pk
// the wrong way, when the user pastes the whole url.
https://www.youtube.com/watch?v=_gXp4hdd2pk
If the user accidentally pastes the entire URL and not the 11 character code then is there a way I can use PHP to grab either the code or whats at the end of this url (11 characters after 'watch?v='?
Here is my PHP code to pull the data:
// $url is the code at the end of 'watch?v=' that the user inputs
$url = get_post_meta ($post->ID, 'youtube_url', $single = true);
// $code is a variable for placing the $url in a youtube link so I can output it to an API link
$code = 'http://www.youtube.com/watch?v=' . $url;
// $code is called at the end of this oembed code, allowing me to decode json data and pull elements from json to echo in my html
// echoed output returns json file. example: http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=_gXp4hdd2pk
$json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($code));
Im looking for something like...
"if user inputs code, use this block of code, else if user inputs whole url use a different block of code, else throw error."
Or... if they use the whole URL can PHP only use a specific section of that url...?
EDIT: Thank you for all the answers! I am new to PHP, so thank you all for your patience. It is difficult for graphic designers to learn PHP, even reading the PHP manual can give us headaches. All of your answers were great and the ones ive tested have worked. Thank you so much :)
Try this,
$code = 'https://www.youtube.com/watch?v=_gXp4hdd2pk';
if (filter_var($code, FILTER_VALIDATE_URL) == TRUE) {
// if `$code` is valid url
$code_arr = explode('?v=', $code);
$query_str = explode('&', $code_arr[1]);
$new_code = $query_str[0];
} else {
// if `$code` is not a valid url like '_gXp4hdd2pk'
$new_code = $code;
}
echo $new_code;
Here's a simple option for you to do, unless you want to use regex like Nisse Engström's Answer.
Using the function parse_url() you could do something like this:
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
now $video_id would return:
_gXp4hdd2pk
from the $url supplied in the above code.
I suggest you read the parse_url() documentation to ensure you understand and grasp it all :-)
Update
for your comment.
You'd use something like this to make sure the parsed value is a valid URL:
// this will check if valid url
if (filter_var($code, FILTER_VALIDATE_URL)) {
// its valid as it returned true
// so run the code
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
} else {
// they must have posted the video code as the if check returned false.
$video_id = $url;
}
Just try as follows ..
$url =" https://www.youtube.com/watch?v=_gXp4hdd2pk";
$url= explode('?v=', $url);
$endofurl = end($url);
echo $endofurl;
Replace $url variable with input .
I instruct my users to copy and paste the whole youtube url.
Then, I do this:
$video_url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk'; // this is from user input
$parsed_url = parse_url($video_url);
parse_str($parsed_url['query'], $query);
$vidID = isset($query['v']) ? $query['v'] : NULL;
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID; // this is used for the Api
$m = array();
if (preg_match ('#^(https?://www.youtube.com/watch\\?v=)?(.+)$#', $url, $m)) {
$code = $m[2];
} else {
/* No match */
}
The code uses a Regular Expression to match the user input (the subject) against a pattern. The pattern is enclosed in a pair of delimiters (#) of your choice. The rest of the pattern works like this:
^ matches the beginning of the string.
(...) creates a subpattern.
? matches 0 or 1 of the preceeding character or subpattern.
https? matches "http" or "https".
\? matches "?".
(.+) matches 1 or more arbitrary charactes. The . matches any character (except newline). + matches 1 or more of the preceeding character or subpattern.
$ matches the end of the string.
In other words, optionally match an http or https base URL, followed by the video code.
The matches are then written to $m. $m[0] contains the entire string, $m[1] contains the first subpattern (base URL) and $m[2] contains the second subpattern (code).

php preg_match get everything after match in string

Looking for how to get the complete string in a URI, after the away?to=
My code:
if (isset($_SERVER[REQUEST_URI])) {
$goto = $_SERVER[REQUEST_URI];
}
if (preg_match("/to=(.+)/", $goto, $goto_url)) {
$link = "<a href='{$goto_url[1]}' target='_blank'>{$goto_url[1]}</a>";
The original link is:
https://domain.com/away?to=http://www.zdf.de/ZDFmediathek#/beitrag/video/2162504/Verschw%C3%B6rung-gegen-die-Freiheit-%281%29
.. but my code is cutting the string after the away?to= to only
http://www.zdf.de/ZDFmediathek
You know the fix for this preg_match function to allow really every character following the away?to= ??
UPDATE:
Found out, that $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING'] is already cutting the original URL. Do you know why and how to prevent that?
try use (.*) to get all after to=
$str = 'away?to=dfkhgkjdshfgkhldsflkgh';
preg_match("/to=(.*)/", $str, $goto_url);
echo $goto_url[1]; //dfkhgkjdshfgkhldsflkgh
Instead of extracting the URL with regex from the request URI you can just get it from the $_GET array:
$link = "<a href='{$_GET['to']}' target='_blank'>{$_GET['to']}</a>";

How to use python/PHP to remove redundancy in URL link?

Many website add tags to url link for tracking purpose, such as
http://www.washingtonpost.com/blogs/answer-sheet/post/report-we-still-dont-know-much-about-charter-schools/2012/01/13/gIQAxMIeyP_blog.html?wprss=linkset&tid=sm_twitter_washingtonpost
If we remove the appendix "?wprss=linkset&tid=sm_twitter_washingtonpost", would still go to same page.
Is there any general approach could remove those redundancy element? Any comment would be helpful.
Thanks!
To remove query, fragment parts from URL
In Python using urlparse:
import urlparse
url = urlparse.urlsplit(URL) # parse url
print urlparse.urlunsplit(url[:3]+('','')) # remove query, fragment parts
Or a more lightweight approach but it might be less universal:
print URL.partition('?')[0]
According to rfc 3986 URI can be parsed using the regular expression:
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
Therefore if there is no fragment identifier (the last part in the above regex) or the query component is present (the 2nd to last part) then URL.partition('?')[0] should work, otherwise answers that split an url on '?' would fail e.g.,
http://example.com/path#here-?-ereh
but urlparse answer still works.
To check whether you can access page via URL
In Python:
import urllib2
try:
resp = urllib2.urlopen(URL)
except IOError, e:
print "error: can't open %s, reason: %s" % (URL, e)
else:
print "success, status code: %s, info:\n%s" % (resp.code, resp.info()),
resp.read() could be used to read the contents of the page.
To remove query string in URL :
<?php
$url = 'http://www.washingtonpost.com/blogs/answer-sheet/post/report-we-still-dont-know-much-about-charter-schools/2012/01/13/gIQAxMIeyP_blog.html?wprss=linkset&tid=sm_twitter_washingtonpost';
$url = explode('?',$url);
$url = $url[0];
//check output
echo $url;
?>
To check URL valid or not:
You can use PHP function get_headers($url). Example:
<?php
//$url_o = 'http://www.washingtonpost.com/blogs/answer-sheet/post/report-we-still-dont-know-much-about-charter-schools/2012/01/13/gIQAxMIeyP_blog.html?wprss=linkset&tid=sm_twitter_washingtonpost';
$url_o = 'http://mobile.nytimes.com/article?a=893626&f=21';
$url = explode('?',$url_o);
$url = $url[0];
$header = get_headers($url);
if(strpos($header[0],'Not Found'))
{
$url = $url_o;
}
//check output
echo $url;
?>
You can use a regular expression:
$yourUrl = preg_replace("/[?].*/","",$yourUrl);
Which meanss: "replace the question mark and everything afterwards with an empty string".
You can make a URL parser that will cut everything from "?" and on
<?php
$pos = strpos($yourUrl, '?'); //First, find the index of "?"
//Then, cut all the chars after the "?" and a append to a new URL string://
$newUrl = substr($yourUrl, 0, -1*(strlen($yourUrl)-((int)$pos)));
echo ($newUrl);
?>

Categories