Validate a URL with PHP

0

I have a big doubt about how I can validate a URL from PHP but that, in addition, it has https protocol or it is incorrect.

Based on this I could say if a URL is valid:

Code:

<?php
    // Variable to check
    $url = "http://www.w3schools.com/";

    // Remover los caracteres ilegales de la url
    $url = filter_var($url, FILTER_SANITIZE_URL);
    echo $url;
    // Validar url
    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
        echo("$url es una URL valida");
    } else {
        echo("$url no es una URL valida");
    }
    ?>

Now I just need to know if you have the https protocol.

    
asked by FRANKY QUINTERO 08.03.2017 в 05:26
source

3 answers

3

For this PHP already brings a native function, parse_url .

$url = "http://www.w3schools.com/";

$urlparts= parse_url($url);

$scheme = $urlparts['scheme'];

if ($scheme === 'https') {
    echo("$url es una URL valida");
} else {
    echo("$url no es una URL valida");
}
    
answered by 08.03.2017 / 13:57
source
1

In that case you should use the following


$urls = array('http://www.website.com', 'https://www.website.com', 'http://website.com', 'https://website.com', 'www.website.com', 'website.com');
foreach($urls as $url) {
    if (preg_match('#^(https?://|www\.)#i', $url) === 1){
        echo $url . ' matches' . "\n";
    } else {
        echo $url . ' fails' . "\n";
    }

Exit:

http://www.website.com matches
https://www.website.com matches
http://website.com matches
https://website.com matches
www.website.com matches
website.com fails
    
answered by 08.03.2017 в 06:04
0

If we want to check by PHP if we navigate through secure protocol or we would not use the following condition:


if (isset($_SERVER['HTTPS'])) {
    // Codigo a ejecutar si se navega bajo entorno seguro.
} else {
    // Codigo a ejecutar si NO se navega bajo entorno seguro.
}
    
answered by 08.03.2017 в 05:35