Jump to content

Using Filter_Var and using FILTER_VALIDATE_URL returns false on a url?


Recommended Posts

I tried parsing through first


then even tried


and on both I get the following returned


post_url equals:
www.google.compost_title equals:
testpost_Threadybody equals:
Enter your posts...

URL equals: www.google.com

www.google.com is not a valid URL

Web page redirects after 2 seconds.

And here is the if statement that handles my filter for URLs

if(isset($_POST["submit"]) && !empty($_POST["url"]) && !empty($_POST["Title"])){
$URL = $conn -> real_escape_string($_POST["url"]) ;
$BodyText = $conn -> real_escape_string(nl2br($_POST["ThreadBody"])) ;
echo "<P>URL equals: " ; 
echo $URL ; 
echo "<P>" ; 
//Change to embed for youtube.

if (filter_var($URL, FILTER_VALIDATE_URL)) {
    echo("$URL is a valid URL");
	//Check if url is a youtube url 
	if (strpos($URL,'youtube') !== false) {
	    echo 'Youtube exists.';
	  $URL = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$URL);

	} else {
	    echo 'Youtube is not included .';
	   $URL = "<ahref ='" . $URL . "</a>" ;  

	$Title = $conn -> real_escape_string($_POST["Title"]) ;
	$User = $_SESSION['username'];
	 $sql = "INSERT INTO Threads (Title, Users, ThreadBody, url)
     VALUES ('$Title', '$User','$BodyText','$URL')";
     if (mysqli_query($conn, $sql)) {
        echo "New record has been added successfully !";
     } else {
        echo "Error: " . $sql . ":-" . mysqli_error($conn);

else {
    echo("$URL is not a valid URL");



Link to comment
Share on other sites

I'm not sure why the first URL isn't working. I built a quick test script and that address worked fine for me. I even tried adding the call real_escape_string(), which I thought might be modifying the URL, but everything worked fine.

The second "www.google.com" address didn't work for me. However, it worked fine once I added the protocol:


Side note: real_escape_string() is only designed to escape input for use in database queries. If you're looking to escape text for outputting to the screen, you'll want to look into htmlspecialchars() and htmlentities().

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.