neocotic
neocotic

Reputation: 2131

Possible security concerns with PHP

I'm working on a Google Chrome extension that provides import/export functionality and I ran in to some problems when trying to implement the Save As... button as I could not force the download of the dynamically created JSON string using JavaScript.

I originally came up with the following JavaScript solution;

$('#saveAsButton').live('click', function (event) {
    var str = JSON.stringify('{}');
    window.location = 'data:text/json;charset=utf8,' + encodeURIComponent(str);
});

However, I cannot suggest a file name or even extension to the user for them to save it as and it relies on the mock MIME text/json to always require a download.

In an attempt to solve this I'm planning on creating a single PHP script on my server which, when posted to, will simply force the download of the string provided. However, my PHP knowledge (especially regarding security) isn't fantastic so I was wondering if there are any (at least obvious) security concerns with the following code;

<?php

$category = strtolower(urldecode($_POST['category']));
$content = urldecode($_POST['content']);

switch ($category) {
    case 'json':
        $contentType = 'text/json; charset=utf-8';
        $fileExtension = 'json';
        break;
    default:
        $contentType = 'text/plain; charset=utf-8';
        $fileExtension = 'txt';
}

header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=export.' . $fileExtension);
header('Content-Type: ' . $contentType);

print $content;

?>

I've wrapped the Save As... button in a form element which will invoke this remote PHP code but I've modified the original listener to support "offline" mode.

$('#saveAsButton').live('click', function (event) {
    var str = JSON.stringify('{}'); // Simplified for purpose of example
    if (window.navigator.onLine) {
        $(this).parents('form').first().find('input[name="content"]').val(str);
    } else {
        // Fall back on "ugly" method
        window.location = 'data:text/json;charset=utf8,' + encodeURIComponent(str);
        event.preventDefault();
    }
});

All of the PHP and JavaScript works and I'm happy with the results so, as mentioned, I'm only really interested in any possible security vulnerabilities created by the PHP code.

Thanks in advance and I'll add further information if required.

Upvotes: 1

Views: 183

Answers (1)

Johan
Johan

Reputation: 1557

Well, the only 'risk' to your script I can see is that if somebody doesn't like you, they could request the link with a large 'content' over and over again, draining your bandwidth,

You could protect against that... to some extend anyway, but I do doubt if it's gonna be an issue.

To make it more difficult though, deflate or gzip it. Makes it faster with smaller packages.

Upvotes: 1

Related Questions