user9151888
user9151888

Reputation: 155

Increase number in txt file via php not working

I have this PHP script:

file_put_contents($_GET["username"].".txt", $counter);
$counter = file_get_contents(strtolower($_GET["username"]).".txt") + 1;

This should increase the content of the text file by 1. But it doesn't edit the text file.

Why's that.

Upvotes: 1

Views: 65

Answers (2)

Shahrokhian
Shahrokhian

Reputation: 1114

your code is almost ok, if you just change the lines order, but I would recommend something like this :

$old = file_get_contents(strtolower($_GET["username"]).".txt");
if( !$old )
{
    $old = 0;
}
$new = $old + 1;
file_put_contents($_GET["username"].".txt", $new);

security point : Never pass user input directly into functions such as file_get_contents, use a validation and escape certain characters and preferably use a whitelist

for example, to allow only letters and numbers :

if( !ctype_alnum( $_GET['username'] ) )
{
   die( 'invalid ...' );
}

Upvotes: 1

Ivanov
Ivanov

Reputation: 91

You need to write to the file after increasing the counter. So first get the value then write it.

$counter = file_get_contents(strtolower($_GET["username"]).".txt") + 1;
file_put_contents($_GET["username"].".txt", $counter);

Upvotes: 1

Related Questions