Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a text file with PHP?

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);
like image 933
hayleyelisa Avatar asked Dec 21 '22 06:12

hayleyelisa


1 Answers

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!

like image 97
Samuel Cook Avatar answered Dec 29 '22 14:12

Samuel Cook