dsmupo6631 2014-07-05 17:38
浏览 62
已采纳

PHP - 写入文件 - fwrite

I am PHP noob, but i am trying to learn it. I have handled some variables and obtaining variable from html form and I wanted to take a string that users types in form -here is code of the form on the page

<form method="POST" action="/php/write.php">
<input type="text" name="string"><input type="submit">
</form>

and in subfolder php I have file "write.php" and it looks like this

<?php
chmod(/write.txt, 0755);
$write == $_POST['string'];
$file = fopen("write.txt","w") or die("cant open file");
fwrite($file, $write);
fclose($file);
?>

I have tried to put into normal HTML file but didnt work too. The problem is, when I type in the form and press submit, it redirects me on write.php but nothing happens, "cant open file" isnt written nor some error and the file stays empty and no fwrite works for me. Could someone help me please?

  • 写回答

1条回答 默认 最新

  • douwen7905 2014-07-05 18:31
    关注

    A few problems with your code:

    chmod(/write.txt, 0755);
    

    The file name must be quoted, and it probably shouldn't be located in the root. The chmod() function only works on existing files. If your file already exists, this is not an error.

    $write == $_POST['string'];
    

    The == is the comparison operator. You want assignment =.

    You code should look something like this:

    $write = $_POST['string'];
    $file = fopen('write.txt','w') or die('cant open file');
    fwrite($file, $write);
    fclose($file);
    chmod('write.txt', 0755);
    

    (I prefer single-quoted strings when I don't need to have variables expanded inside.)


    Also, in a well-written program, you should:

    • check if $_POST['string'] actually exists before accessing it, using isset ($_POST['string']).
    • check the return values of fopen(), fwrite(), fclose() and chmod(), and deal with potential errors.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效