i want to write data accepted in a form to a text file. this is the code i am using.

$file=fopen("data.txt","a+");
fwrite($file," whatever i want written");
fclose($file);

but nothing is being written to the file.
the text files are in the same place as the php pages.
does anyone know why its not working?

heres the whole thing if u need it.

<?php

$val1= $_POST["val1"];
$val2=$_POST["val2"];

$file=fopen("idata.txt","a+");
fwrite($file,"whatever i want it to write ");
fclose($file);


switch($val1)
{
case 1:

$file=fopen("data.txt","a+");
fwrite($file,"whatever i want it to write");
fclose($file);
break;

case 2:

$file=fopen("data.txt","a+");
fwrite($file,"whatever i want it to write");
fclose($file);
break;

.
.
.


default:

$file=fopen("data.txt","a+");
fwrite($file,"whatever..");
fclose($file);
break;

}



?>

thanks

Dani AI

Generated

As hinted, file permissions and the actual path are the two most common causes when PHP appears to "not write" to a file. confirmed a permission fix solved the problem, but the checklist below helps isolate the issue reliably and offers a safer write pattern.

First, confirm which file PHP is trying to write to (relative paths can point somewhere unexpected). Use an absolute path or build one from the script directory so you know exactly where data lands. Also enable error reporting temporarily to see failures instead of silent errors.

A quick safe pattern: check writability, then append with an exclusive lock to avoid races.

$path = __DIR__ . '/data.txt';
if (!is_writable(dirname($path))) {
    error_log("Directory not writable: " . dirname($path));
}
file_put_contents($path, $text . PHP_EOL, FILE_APPEND | LOCK_EX);

Permission tips: prefer changing file ownership to the webserver user (for example chown www-data:www-data data.txt) and use conservative permissions such as 0644 or 0664. Avoid leaving files world-writable long-term. On SELinux systems, also check file contexts (ls -Z) and on hosts with open_basedir restrictions confirm the target path is allowed.

If writes still fail, inspect PHP/Apache/PHP-FPM error logs and use error_get_last() or logging to capture the low-level error. Relevant PHP docs: file_put_contents and is_writable.

Finally, once it works, remove debugging output and do minimal logging only. That keeps the app secure and avoids filling logs with form data.

Recommended Answers

All 2 Replies

check the file is writeable to the user php is running as, CHMOD,

no other thoughts

works! :P
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.