Johnny Johnny - 7 months ago 21
PHP Question

PHP - writing into a file - 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?

Answer

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.