How to validate Vine URL and allow HTTP or HTTPS using PHP

274 Views Asked by At

How can this be changed to allow either HTTP or HTTPS for a Vine URL?

$vineURL = 'https://vine.co/v/';
$pos = stripos($url_input_value, $vineURL);

if ($pos === 0) {
    echo "The url '$url' is a vine URL";
}
else {
    echo "The url '$url' is not a vine URL";
}
3

There are 3 best solutions below

3
On BEST ANSWER

You can use the parse_url function, it breaks the URL into its components making it easier to match each component individually:

var_dump(parse_url("https://vine.co/v/"));
// array(3) {
//   ["scheme"]=>
//   string(4) "http"
//   ["host"]=>
//   string(7) "vine.co"
//   ["path"]=>
//   string(3) "/v/"
// }

You can then just check if scheme, host and path match:

function checkVineURL($url) {
    $urlpart = parse_url($url);
    if($urlpart["scheme"] === "http" || $urlpart["scheme"] === "https") {
        if($urlpart["host"] === "vine.co" || $urlpart["host"] === "www.vine.co") {
            if(strpos($urlpart["path"], "/v/") === 0) {
                return true;
            }
        }
    }
    return false;
}
checkVineURL("https://vine.co/v/");     // true
checkVineURL("http://vine.co/v/");      // true
checkVineURL("https://www.vine.co/v/"); // true
checkVineURL("http://www.vine.co/v/");  // true
checkVineURL("ftp://vine.co/v/");       // false
checkVineURL("http://vine1.co/v/");     // false
checkVineURL("http://vine.co/v1/");     // false
0
On

User RegEx like this

if (preg_match("/^http(s)?:\/\/(www\.)?vine\.co\/v\//", $url)) {
    echo "This is a vine URL";
} else {
    echo "This is not a vine URL";
}
2
On

Just take out the "https://" and change your if statement a bit... like this:

$vineURL = 'vine.co/v/';
if(stripos($user_input_value, $vineURL) !== false) {
    echo "This is a vine URL";
} else {
    echo "This is not a vine URL";
}