File_Submit File_Submit - 5 months ago 40
PHP Question

PHP cannot write to text file

I have the following code which I am using in WordPress/Woocommerce:

function generatePassword($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$pass = '';
for ($i = 0; $i < $length; $i++) {
$pass .= $characters[rand(0, $charactersLength - 1)];
return $pass;

$password = generatePassword();

$data = "\n" . $password . ',' . time();

$test = '';
$file = fopen($test,"a");

And it works except for the final part where it has to write to a file. Can you tell me what is wrong with the code? I tried changing the CHMOD, but no success.


You have to provide Web server path of actual file location path in your server instead of url.

$test = '';

Replace it by Server path

$test = '<location_of_your_webroot_folder_in_server>/ot/a/docs/test/test.txt';

Make sure test have permission for read and write publicly.

How can you check your folder path?

1) Make test.php file in ot folder with below code

echo dirname(__FILE__);

2) Upload it in ot folder.

3) execute file from browser

4) Copy path before \ot\.... and replace it on <location_of_your_webroot_folder_in_server>.