Question

Here's my code

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$url = $_POST['text'];
$parse = parse_url($url);
echo $parse['host'];
}
?>

I am using parse_url to get the host name to be outputted when somebody inputs the url, now if I try to enter some garbage input, it gives an error: "Undefined index: host" , I want to know how do we check whether its a valid url or just a string before echoing the output of parse_url function

Was it helpful?

Solution

You can check to see if host is defined:

echo isset($parse['host']) ? $parse['host'] : 'Invalid input';

Or, you can create a regex to check to see if the string you're passing to parse_url is correctly formatted. This is a bit harder, but can be done. See: Parse URL with Regex using PHP or PHP url validation + detection

OTHER TIPS

Use Regular Expression

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$url = $_POST['text'];

define('REGEX_URL','/http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/');

if(preg_match(REGEX_URL, $url, $url)) {
   echo "<a href=\"{$url[0]}\">{$url[0]}</a>";
} else {
   echo "<p>No Match Found</p>";
}
}
?>

parse_url() will return false if the variable could not be parsed as url. Checking the parse_url() result for !== false would let you know that the string has been successfully parsed by the function and thus is a valid url.

$parse = parse_url($url);
if($parse !== false)
{
    echo 'valid url';
    if(isset($parse['host'])) echo $parse['host'];
}

After that, it's up to you to figure out what exactly you mean with "valid url". PHP's parse_url function will be able to parse a string that's nothing more than e.g. just a path. Depending upon your given problem/context, you may feel that a "valid url" consists out of at least scheme+host, or in a different context, only a relative path (without host) might also be valid. Adding those checks in yourself - just checking if the key is present in the parsed array - could look like:

$parse = parse_url($url);
if($parse !== false)
{
    if(isset($parse['scheme']) && isset($parse['host']))
    {
        echo 'valid url';
        echo $parse['host'];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top