我正在建立一个网站,让用户发布文本到不同的输入框,但我的问题是,当你刷新页面或别人去的页面上,他们将无法看到另一个人发布的文本。所以我基本上想知道你如何保持文本在页面上,直到有人在输入框中新的帖子。下面是我的php代码:
$name = $_POST["name"];
echo $name;
谢谢。
您需要一种存储机制,最好是您选择的SQL数据库。
您可以使用$_SESSION
来保持数据的持久性,但是如果您希望其他人能够看到其他用户发布的内容,那么您唯一的选择就是使用SQL数据库。
但即使如此,如果你想建立一种聊天框,其中更改更新而不刷新页面,那么你将需要查看websockets—
在PHP中,Ratchet是将(有效地)为页面提供这种功能的应用程序。
但是,如果您不关心新更改是否实时更新,并且如果您懒得使用SQL,则可以将内容存储到文件中:
<?php
$oldDataChunk = json_decode(file_get_contents('/your/cache/file/that/php/can/write/to.json'));
// get the file with all the old data. This file wont exist the first time you run it.
if($_POST){
// if there is more data POSTED, add it to what you already have -
//EDIT:
// The strip_tags function will prevent xss -- put there could be an advanced way to circumvent it ---
// use with caution - !
$oldDataChunk[] = strip_tags($_POST); // adds the new POST data to the old data
file_put_contents('/your/cache/file/that/php/can/write/to', json_encode($oldDataChunk), FILE_APPEND); //saves the data in json format for easy retrieval.
}
print_r($oldDataChunk);
/**
Outputs:
Array ( [0] => Array( [name] => "Posted Name", [data] => "Some data that was posted" ),
[1] => Array( [name] => "Earlier posted name", [data] => "Etc etc etc " ) .....
*/
如果你正在做一些小而轻的事情,上面没有什么问题,但是一个真正的应用程序会使用一些SQL数据库来存储,而不仅仅是一个文件。