URL validation detect movie title - php

how can me detect movie title from url..
http://www.mysite.com/2430-Moonrise-Kingdom.aspx
http://www.mysite.com/2405-Dark-Shadows.aspx
http://www.mysite.com/2415-Madagascar-3-Europes-Most-Wanted.aspx
I need to convert utl from:
http://www.mysite.com/2405-Dark-Shadows.aspx
to: "Dark Shadows" or "Dark-Shadows"
my code is:
$regexUrl = "/\/[0-9]{2,4}\-[a-zA-Z0-9\-\.]+\.aspx\/?";
echo preg_match($regexUrl, $_SERVER["REQUEST_URI"]);

Something seems to go wrong with your pattern at the end. Try this (note the last few characters):
/\/[0-9]{2,4}\-[a-zA-Z0-9\-\.]+\.aspx/
You'll also want to add a group in order to more easily grab the part that is the title.
/\/[0-9]{2,4}\-([a-zA-Z0-9\-\.]+)\.aspx\/?
Finally, here's a simplified version that won't break if the number at the beginning has one or more than four digits, or if the title has strange characters (perhaps it's not an English-language film).
\/\d+-(.+)\.aspx$/

$url = 'http://www.mysite.com/2415-Madagascar-3-Europes-Most-Wanted.aspx';
$url = basename($url, '.aspx');
$url = substr($url, 1+strpos($url, '-'));
$url = strtr($url, '-', ' ');
echo $url;
But if this is your site you should rather use this:
$id = (int)basename($url);
and load the title from DB. So even when your URL gets corrupted you can still load proper page.

Related

How to get the ID from itunes url?

I need to get the item ID from the iTunes url and it used to work like this before itunes changed there url structure;
$musicid = 'https://itunes.apple.com/album/the-endless-bridge-single/id1146508518?uo=1&v0=9989';
$musicid=explode('/id',$musicid);
$musicid=explode('?',$musicid[1]);
echo $musicid[0];
But now iTunes has deleted the 'id' prefix in the url so the above code does not return the id anymore, does anyone know a solution?
old itunes url; https://itunes.apple.com/album/the-endless-bridge-single/id1146508518?uo=1&v0=9989
new itunes url; https://itunes.apple.com/album/the-endless-bridge-single/1146508518?uo=1&v0=9989
You would just explode on the fourth slash, grabbing the fifth segment.
Simply remove id from /id (so that you explode() on /), and check the sixth index instead of the second (with [5] instead of [1]):
<?php
$musicid = 'https://itunes.apple.com/album/the-endless-bridge-single/1146508518?uo=1&v0=9989';
$musicid = explode('/', $musicid);
$musicid = explode('?', $musicid[5]);
echo $musicid[0]; // 1146508518
This can be seen working here.
Hope this helps! :)
Use a regular expression:
<?php
$url = 'https://itunes.apple.com/album/the-endless-bridge-single/1146508518?uo=1&v0=9989';
preg_match('/album\/[^\/]+\/(\d+)\?/', $url, $matches);
var_dump($matches[1]);
Demo here: https://3v4l.org/tF9pS
Looks like you can simply use a combination of parse_url and basename, eg
$musicid = basename(parse_url($musicid, PHP_URL_PATH));
Demo ~ https://eval.in/895029

parse non encoded url

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.

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).

Url factory - google duplicate page- 301 redirect

I am new to this site hope my issue is asked the right way.
To avoid urls with lots of ?id=11 etc. etc. for SEO purposes I build an urls that allowed me to have those urls rebuild in this way:
http://www.example.com/blah-blah-blah-blah/
Now I changed some of these urls so I needed to 301 redirect the old ones to the new ones with .htaccess. Problem is that when I redirect one of these the ?id=(+ number) is added:
example: url to redirect /blah-blah-blah-blah/
example: url redirected to /blah-blah-blah-blah/?id=11
The function that does the job is this:
function _prepare_url_text($string)
{
//remove all characters that aren't a-z, 0-9, dash, underscore or space
$NOT_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = preg_replace($NOT_acceptable_characters_regex, '', $string);
//remove all leaidng and trailing spaces
$string = trim($string);
//change all dashed, underscores and psaces to dashe
$string = preg_replace('#[-_ ]+#', '-', $string);
//return the modified string
return $string;
}
//buld a link that contains Type a Name
function make_name_url($IDName, $ID)
{
// prepare le type name and acc name for inlcusion in URL
$clean_ID_name = _prepare_url_text($AccName);
//build the keyword reach url
$url = SITE_DOMAIN . '/blah-blah-blah-blah-' . $clean_ID_name . '-A' . $ID . '/';
//return the url
return $url;
}
The problem with all this is that Google thinks now that there are two copies of the same page. Could anyone help me understand what I can do to resolve this?
Add a canonical tag to your pages. This will stop duplicates.
https://support.google.com/webmasters/answer/139394?hl=en

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