1

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

Jenny Dcosta
  • 135
  • 1
  • 4
  • 11
  • use `preg_match()` instead or see this [example](http://php.net/manual/en/function.parse-url.php#93983) – xkeshav Nov 08 '11 at 06:08

3 Answers3

6

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

Community
  • 1
  • 1
nickb
  • 59,313
  • 13
  • 108
  • 143
1

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>";
}
}
?>
Hardik Raval
  • 1,948
  • 16
  • 29
1

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'];
    }
}
matthiasmullie
  • 2,063
  • 15
  • 17
  • 1
    It should be noted that prior to PHP5.3.3 `parse_url` will also trigger an `E_WARNING` when it returns `false` so you may need to suppress this with `@parse_url` in < PHP 5.3.3 –  Nov 07 '12 at 03:32