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