Andrew Andrew - 10 months ago 44
PHP Question

PHP - Write to file isn't working

I am trying to develop a website which uses PHP to write to a text file. I have made a text document called 'newfile.txt' at the right file path and I have run the code in Google Chrome. The file just isn't written to and I can't find any code online which is different to mine. It does not produce an error message either. What have I done wrong?

<!DOCTYPE html>

$myfile = fopen("C:\Users\Andrew\Documents\newfile.txt", "w") or die("Unableto open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);



The \ character in PHP is like C, C++, Java, where it denotes an escape, like in \n. So to denote a literal \ you must either:

(1) Double it: \\ (2) (For file paths) Reverse it: /

So either:

fopen("C:\\Users\\Andrew\\Documents\\newfile.txt", "w")


fopen("C:/Users/Andrew/Documents/newfile.txt", "w")