3
\$\begingroup\$

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

<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?>

<?php 

    if(sizeof($_POST))
    {
    file_put_contents;
    } else {
    echo "ERROR! Must be activated from Tampermonkey script!";
    exit();
    }

file_put_contents(
"content.html", 
"<strong> Updated last: " . $_POST['date'] . "</strong><br><br>"  .
//Please add more entries depending on how many accounts you have configured

"<strong>Account 1</strong><br>(" . $_POST['accountname1'] . ")" . "<br>CREDITS<br>" . $_POST['credits1'] . "<br>-<br>" . 
"<strong>Account 2</strong><br>(" . $_POST['accountname2'] . ")" . "<br>CREDITS<br>" . $_POST['credits2'] . "<br>-<br>" .
"<strong>Account 3</strong><br>(" . $_POST['accountname3'] . ")" . "<br>CREDITS<br>" . $_POST['credits3'] . "<br>-<br>" .
"<strong>Account 4</strong><br>(" . $_POST['accountname4'] . ")" . "<br>CREDITS<br>" . $_POST['credits4'] . "<br>-<br>" .
"<strong>Account 5</strong><br>(" . $_POST['accountname5'] . ")" . "<br>CREDITS<br>" . $_POST['credits5'] . "<br>-<br>" .
"<strong>Account 6</strong><br>(" . $_POST['accountname6'] . ")" . "<br>CREDITS<br>" . $_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 gives me:

" array(13) { ["date"]=> string(58) "Sun Dec 27 2015 11:28:53 GMT-0700 (Mountain Standard Time)" ["accountname1"]=> string(28) "*****@gmail.com" ["credits1"]=> string(3) "110" ["accountname2"]=> string(33) "*****@gmail.com" ["credits2"]=> string(3) "109" ["accountname3"]=> string(23) "*****@gmail.com" ["credits3"]=> string(3) "536" ["accountname4"]=> string(32) "*****@outlook.com" ["credits4"]=> string(3) "333" ["accountname5"]=> string(19) "*****@gmail.com" ["credits5"]=> string(3) "188" ["accountname6"]=> string(20) "*****@gmail.com" ["credits6"]=> string(2) "72" } "

What this does is post data from a web page to a PHP script on a server, then the script parses the data into an HTML file.

As it stands right now, the script requires me to add a new entry when I create a new account and add it to the page.

What I'd like is for my PHP page to generate the HTML code based on how many entries are in the post data.

\$\endgroup\$
2
  • \$\begingroup\$ Where's the rest of bprs? \$\endgroup\$ – Joseph Dec 28 '15 at 0:17
  • \$\begingroup\$ Woops. I fixed it. Should be complete now. \$\endgroup\$ – user1888932 Dec 28 '15 at 1:06
2
\$\begingroup\$

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:

<?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 />'));
}

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.

\$\endgroup\$
0
\$\begingroup\$

Alright. To simplify this I had to modify bprs a little bit:

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

Then I modified my PHP to accept that value and used that number to figure out how many entries should be written to my html file.

<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?>

<?php
if (sizeof($_POST)) {
    load_contents();
}
else {
    echo "ERROR! Must be activated from Tampermonkey script!";
    exit();
}
function load_contents()
{
    $accountnumber = $_POST['accountsnumber'];
    $str = '<strong>Updated last: ' . $_POST['date'] . '</strong><br /><br />';
    for ($i = 0; $i < $accountnumber; $i++) {
        $identer = $i + 1;
        $str.= '<strong>Account ' . $identer . '</strong><br />(' . $_POST['accountname' . $identer] . ')' . '<br />CREDITS<br />' . $_POST['credits' . $identer] . '<br />-<br />';
    }
    file_put_contents("content.html", rtrim($str, '<br />-<br />'));
}
?>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.