Yii防止在刷新时从上传的文件中重新插入数据到数据库
I have an upload form, where I upload csv files and then insert all rows to the database. If I hit refresh, all content is inserted again and again into the database. What is the best prectice to prevent this?
Thanks a lot! BR
我有一个上传表单,我上传csv文件,然后将所有行插入数据库。 如果我点击刷新,则会将所有内容一次又一次地插入到数据库中。 防止这种情况的最佳方法是什么? p>
非常感谢! BR p> div>
The best way to prevent this behavior is to use a redirect to show the landing page. When a redirect is made the browser history records another url after the post action. in Yii you can achieve this by doing the following from the controller.
$this->redirect("../path/to/action");
You can add a hidden input element to the form which holds a unique ID:
<input type="hidden" name="random" value="4b3403665fea6">
If you store this value in the database you can make sure that no CSV file will be uploaded with the same unique ID (after refresh).
A unique ID can be generated with a built-in PHP function uniqid()