dongyi7901 2013-09-11 20:54
浏览 36
已采纳

我用PHP调用的数据文件神秘地改变了。 用户是否覆盖了它?

I'm having a blast with PHP functionality, but I know very little about PHP security -- which, of course, is a major bad thing. I'm self-teaching myself this language but the resources are sometimes a little less cut-and-dried than is helpful.

I just made this dumb little site:

http://www.ineedaprompt.com/

You can see that right below the "Again!" button is a counter. It shows how many times the button has been clicked. Every time the button is clicked, my JS makes an Ajax call to a PHP file (counter.php) which updates this file:

http://www.ineedaprompt.com/counter.txt

Every 100ms, I use an Ajax call to update the value of that counter field with the contents of the counter file.

The counter was well over 100 recently, but then suddenly dropped back to 0 and started all over. How easy would it be for someone external to overwrite that counter.txt file? How can I prevent it?

Note: There's nothing in my .htaccess file having to do with PHP because I'm not sure what to put in there.

Pardon my ignorance and TMI, and thank you!

EDIT: You guys are wonderfully fast.

Here's the counter.php code:

<?php

$counter = file_get_contents("counter.txt");

$counter++;

file_put_contents("counter.txt", $counter);

?>

...and the code in my JS that activates on clicking the button:

$("#button").click(function(){
    $.ajax("counter.php");
});

...and the code in my JS that activates every 100ms:

window.setInterval(function(){
    $.get("counter.txt", function(result){
        $("#counter").html(result);
    });
}, 100);

The counter has no limit. It's literally just a text file with a single number in it.

  • 写回答

2条回答 默认 最新

  • dsf487787 2013-09-11 21:05
    关注

    You need to LOCK the file when writing data because The Operating System can't handle multiple read and write at same time, I used below in a site and now my problem solved also. I hope it help you and someone else.

    if( $fl = fopen("counter.txt", "r+") && flock( $fl ,  LOCK_EX ) )
    {
      //empty the file
      ftruncate($fl, 0); 
    
      //move file pointer to beginning
      fseek($fl, 0); 
      //write
      fwrite($fl, $content);
      fflush($fl);
      flock($fl, LOCK_UN); 
      fclose($fl); 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题