HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

PHP script for getting post data from Tampermonkey script

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptphptampermonkeygettingpostforfromdata

Problem

I'm trying to shorten this piece of my code into a loop:


 Updated last: " . $_POST['date'] . ""  .
//Please add more entries depending on how many accounts you have configured

"Account 1(" . $_POST['accountname1'] . ")" . "CREDITS" . $_POST['credits1'] . "-" . 
"Account 2(" . $_POST['accountname2'] . ")" . "CREDITS" . $_POST['credits2'] . "-" .
"Account 3(" . $_POST['accountname3'] . ")" . "CREDITS" . $_POST['credits3'] . "-" .
"Account 4(" . $_POST['accountname4'] . ")" . "CREDITS" . $_POST['credits4'] . "-" .
"Account 5(" . $_POST['accountname5'] . ")" . "CREDITS" . $_POST['credits5'] . "-" .
"Account 6(" . $_POST['accountname6'] . ")" . "CREDITS" . $_POST['credits6']); 

?>


Here's the JavaScript code I'm posting with:

function bprs() {

    {
        var rowCount = $('#accountsTable tr').length;
        var accountsCount = rowCount -1;                       
        var accounts = [];
        for (var n = 1; n <= accountsCount; n++) {
            accounts[n] = {                          
                name: $('#accountName' + n).text(),
                credits: $('#credits' + n).text()
            };
        }

        var date = new Date();
        var data = "date=" + date + 
            accounts.reduce(function (prev, account, n) {
                return prev + "&accountname" + n + "=" + account.name +
                    "&credits" + n + "=" + account.credits;
            }, '');

        $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
            options.async = true;
        });

        $.ajax({
            url: 'http://mysite.com/submit.php', // point to the php file here
            async:false,
            type: "POST",
            dataType: "json",
            data: data,
            success: function (result) {
                JSON.parse(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr);
            }
        });


Here's the post data my browser g

Solution

A somewhat better solution would be to take advantage of the fact that PHP auto-generates arrays from REQUEST data, if the fields are named correctly. Thus I propose changing the code posted by you to the following:

var date = new Date();
var data = "date=" + date +
           "&accountsnumber=" + accountsCount +
    accounts.reduce(function (prev, account, n) {
        // Note the use of square brackets here, they tell PHP to create an array.
        return prev + "&d[" + n + "][accountname]=" + account.name +
            "&d[" + n + "][credits]=" + account.credits;
    }, '');


As for the PHP code, it'll look like this:

Updated last: %s';
    $output = sprintf ($str, htmlspecialchars ($date->format ("Y-m-d")))

    // Create a string template to use with sprintf (), to make the code easier to read.
    $str = 'Account %1$d(%2$s)CREDITS%3$s--'));
}


As you can see I've added some basic protection against attackers as well, as the code posted by you is woefully insecure. Basically allowing whomever wants full access to your web-server, to do whatever they like!
Check out OWASP for more information.

Code Snippets

var date = new Date();
var data = "date=" + date +
           "&accountsnumber=" + accountsCount +
    accounts.reduce(function (prev, account, n) {
        // Note the use of square brackets here, they tell PHP to create an array.
        return prev + "&d[" + n + "][accountname]=" + account.name +
            "&d[" + n + "][credits]=" + account.credits;
    }, '');
<?php
// Renamed this to save_contents () as that is what we're actually doing.
function save_contents()
{
    // Use intval () here to ensure that we do indeed have an integer, and not some random injection code.
    $accountnumber = intval ($_POST['accountsnumber']);

    // Validate with DateTime to verify that this is indeed a valid date.
    $date = new DateTime ($_POST['date'], new DateTimeZone (DEFAULT_TIMEZONE));

    // Format the date, and use htmlspecialchars to ensure HTML-conformity of the output.
    $str = '<strong>Updated last: %s</strong><br /><br />';
    $output = sprintf ($str, htmlspecialchars ($date->format ("Y-m-d")))

    // Create a string template to use with sprintf (), to make the code easier to read.
    $str = '<strong>Account %1$d</strong><br />(%2$s)<br />CREDITS<br />%3$s<br />-<br /';

    for ($id = 1; $id <= $accountnumber; $id++) {            
        // Use htmlspecialchars to protect against XSS.
        $accName = htmlspecialchars ($_POST['d'][$id]['accountname']);
        $credits = htmlspecialchars ($_POST['d'][$id]['credits']);

        $output .= sprintf ($str, $id, $accName, $credits);
    }

    file_put_contents("content.html", rtrim ($output, '<br />-<br />'));
}

Context

StackExchange Code Review Q#115208, answer score: 2

Revisions (0)

No revisions yet.