Issue
I'm trying to use PHP to create a text file, but I keep getting the "can't open file" error. Can anyone tell me what I'm doing wrong?
chmod('text.txt', 0777);
$textFile = "text.txt";
$fileHandle = fopen($textFile, 'w') or die("can't open file");
$stringData = "Hello!";
fwrite($fileHandle, $stringData);
fclose($fileHandle);
Solution
You're not going to be able to chmod()
a file that doesn't exists. You must have write privileges on the parent folder in order to allow Apache
(if your running Apache, otherwise whichever user your allowing to write the file) as a user to write inside of that folder (whether it is the root, or a sub folder).
Additionally, you should do some error handling on your file writing:
<?php
if($fh = fopen('text.txt','w')){
$stringData = "Hello!";
fwrite($fh, $stringData,1024);
fclose($fh);
}
Hope this helps!
Answered By - Samuel Cook Answer Checked By - Dawn Plyler (WPSolving Volunteer)