File_Submit File_Submit - 3 months ago 22
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 = 'http://advokatami.bg/ot/a/docs/test/test.txt';
$file = fopen($test,"a");
fwrite($file,$data);
fclose($file);


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.

Answer

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

$test = 'http://advokatami.bg/ot/a/docs/test/test.txt';

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

<?php
echo dirname(__FILE__);
die();

2) Upload it in ot folder.

3) execute file from browser http://advokatami.bg/ot/test.php

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

Comments