开发者

Checking for existing URLs before being added to database

I'm trying to test if for existing URLs in a user form field and need a little guidance. I am a placement student and told the place I'm working for I'm not great with PHP and here I am working with PHP.

This is looking like the best I've tried thus far:

    $file = [url];
    $file_headers = @get_headers($file);
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
         $exists = false;
    }
    else {
         $exists = true;
    }


    if ($_POST[code] == '') {
        header("Location: index.php"); 
        exit;
    }
    else if ($exists == false){
        print("URL is not valid");

    } 
    else {

        $query = "INSERT INTO redirects
        SET code = '$_POST[code]',
        url  = '$_POST[url]',
        requester = '$_POST[requester]',
        date = '$_POST[iw_start]',
        webperson = '$_POST[webperson]',
        active = '$_POST[active]'";

        my开发者_高级运维sql_query ($query, $link);

    }

?>

Am I on the right path?

*BEFORE YOU ANSWER: THE SQL QUERY IS NOT MINE. PLEASE KEEP THAT IN MIND.


You should use CURL to test the existing url.

From How can one check to see if a remote file exists using PHP?:

$ch = curl_init($_POST[url]);

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode > 400 -> not found, $retcode = 200, found.
curl_close($ch);

Then, for your database, you should add an unique constraint in order to avoid adding duplicate urls.

Now, as mentionned in the comments, what you did is vulnerable to SQL Injection. A user can post malicious data through the form and, for example, delete all the entry in your database. You must secure the input data (POST/GET) that you receive from your users, always.


If you read the manual, get_headers returns false on failure so I would also check that before checking the HTTP status code.

Also you haven't escaped any of your variables in your SQL query.


Try replacing your query with this:

$query = "INSERT INTO redirects
        SET code = '" . mysql_real_escape_string($_POST['code']) . "',
        url  = '" . mysql_real_escape_string($_POST['url']) . "',
        requester = '" . mysql_real_escape_string($_POST['requester']) . "',
        date = '" . mysql_real_escape_string($_POST['iw_start']) . "',
        webperson = '" . mysql_real_escape_string($_POST['webperson']) . "',
        active = '" . mysql_real_escape_string($_POST['active']) . "'";


Maybe try using a regex pattern to determine if it is a valid URL first?

$valid = "/^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}/";

if (preg_match($valid, $file)) { echo "OK" };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜