phpmysqlwordpresssanitizationmysql-real-escape-string

Sanitizing URLs being inserted into a WordPress MySQL database


I am writing a plugin for Wordpress, where I have my own custom table to store the relevant data being pulled from a remote API. One of the elements I need to store is a URL, which is a TEXT field within my database.

Since I have seen numerous comments saying not to use standard mysql_ or mysqli_ functions in Wordpress plugins, I am wondering what is the best way to escape the URL before I insert it? Is using esc_url() sufficient enough or is there anything else I should do prior?

    case "Create":
    {
        $tag = $_POST['product_tag'];
        $name = $_POST['product_name'];
        $asin = $_POST['product_id'];

        $response = getPrice("com", $asin);

        $result = $wpdb->insert( $table_name, array(
            'tag' => $tag,
            'name' => $name,
            'asin' => $asin,
            'price' => $response['price'],
            'url' => esc_url($response['url'])
        ));

        if ($result !== FALSE)
            echo "Successfully inserted new Amazon Product.";
        else
            echo "An Error occurred.";

        break;
    }

Solution

  • Normally you'd just insert a URL as-is in your database and only be concerned with security issues when presenting it. This, of course, presumes you're doing things correctly like you are here where you've explicitly called the insert function with data sent in as an associative array.

    The real risk is when people bypass WPDB and insert things directly, and often badly by using string concatenation.

    You should call esc_url when displaying these values. As you may change what's an allowed URL from time to time, limiting them or opening them up as your needs change, it's best to keep them raw in the database and prepare them for display on a case-by-case basis.