Search code examples
securityprogramming-languages

Secure way to create a URL which takes input and stores to a database


Let's pretend that you had the task of creating a URL (e.g. a single web page) which receives input (e.g. GET and/or POST) and must clean and safely store that input to a database. In addition, it must be easy to send data to that URL from nearly any application, regardless of the language it's written in.

How would you get this task accomplished in a safe manner?

(I'm thinking of the Pit of Success, as opposed to easily throwing together a PHP script which leaves me wide open to SQL injection.)

EDIT: I've changed the title and some keywords in response to some answers. I was posting this question as a discussion of security and safety for those who may be new to web dev. I am not talking about securing all levels to a paranoid extent, just ensuring minimum security in the handling of user input. The answers I envisioned, in addition to security discussions, would be examples of code which accomplishes the stated task. I will provide my own answer (in PHP) as an example of what I mean.

Also, I am hoping this will become a community wiki.


Solution

  • As promised, here is an example of taking input and storing it in a mysql database in what I believe is a secure manner (at least, it is supposed to prevent SQL injection problems). Please correct me if I am wrong. (Note, the only input is from the msg variable, which could be from GET, POST, or a cookie.)

    <?php
    try {
        $db = new PDO('mysql:host=$hostUri;dbname=$dbName', $user, $pass, array(
            PDO::ATTR_PERSISTENT => true
        ));
        $s = $db->prepare("INSERT INTO $dbName.$tableName (message) VALUES (:msg)");
        $dbData = array(':msg' => $_REQUEST['msg']);
        $s->execute($dbData);
        print "Added to database";
    } catch (PDOException $e) {
        // Sensitive information can be displayed if this exception isn't handled
        //print "Error!: " . $e->getMessage() . "<br/>";
        die("PDO error");
    }
    ?>
    

    More information on PDO in PHP.

    This code could be called by simply including the variable in the URL (e.g. http://example.com/?msg=MyMessage) or by code (example below is in C#, thanks to this answer).

    using (var client = new System.Net.WebClient())
    {
        byte[] response = client.UploadValues(
            "http://example.com/", 
            new System.Collections.Specialized.NameValueCollection { { "msg", "MyMessage" }});
        Console.WriteLine(System.Text.Encoding.UTF8.GetString(response));
    }