inspect data (url variable) before inserting to mysql

0 votes
asked Mar 20, 2013 by user1932820

My php script is posting bad urls that ajax send to it. When I try to filter the url and cancel the insert into mysql, it doesn't work. What I want to do is verify the $link variable if it a link. If not, don't post data to mysql. Can i know what I did wrong and how to fix it? Thank you :) Here is my code

$con = mysql_connect("localhost","root","");
if (!$con) {
   die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $con);

$link = $_POST['new'];
$name = $_POST['name'];
$size = $_POST['size'];
$cat = $_POST['cat'];

// PHP 5.3.5-1ubuntu7.2
$link = mysql_real_escape_string($link);
$name = mysql_real_escape_string($name);
$size = mysql_real_escape_string($size);
$cat = mysql_real_escape_string($cat);

if (filter_var($link, FILTER_VALIDATE_URL)) {} else {
  echo "URL is NOT valid";
  mysql_close($con);
  exit();
}

$check = mysql_query("SELECT link FROM links WHERE  link = '{$link}';");

if (mysql_num_rows($check) == 0) {
    // insert

    $sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added.  Redirecting!";


    mysql_close($con);
}

2 Answers

0 votes
answered Mar 20, 2013 by kermit

Is this what you're trying to do? Perhaps you need a regex solution.

if (filter_var($link, FILTER_VALIDATE_URL)) {
    $check = mysql_query("SELECT link FROM links WHERE  link = '{$link}';");

    if (mysql_num_rows($check) == 0) {
        // insert

        $sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
        if (!mysql_query($sql,$con))
          {
          die('Error: ' . mysql_error());
          }
        echo "1 record added.  Redirecting!";


        mysql_close($con);
    }
} else {
  echo "URL is NOT valid";
  mysql_close($con);
  exit();
}
0 votes
answered Mar 20, 2013 by bitworking

try this one:

if(filter_var($link, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === false){
    echo "URL is NOT valid";
    mysql_close($con);
    exit();
}

Your are right xxxhxtxtp://example.com will pass as valid url.

Try it with preg_match instead.

if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $link)) {
    echo "URL is NOT valid";
    mysql_close($con);
    exit();
}

With this regex you need to have http(s) scheme. So you can search for another regex if that don't work for you.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...