I am starting to learn php, I want to create and write a simple text file. My code is as follows:
<?php
//Name
$filename = "newfile.txt";
//Pointer
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
//Write the data
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
When I run the script it returns the error: "Error opening new file", have no idea why it's doing this. I know the file doesn't exist yet, but from what I understand the option w should create a new file if it doesn't exist. Could someone give some pointers on what I might be doing wrong please?
EDIT:
It seems my permissions aren't set correctly on my APACHE server. I just tried this:
chown -R www-data:www-data /var/www/mysite
chmod -R og-r /var/www/mysite
Now I can't even access the directory and check the contents! In the terminal I just get "Permission denied"
PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
This is done by navigating to File > Save As... In Notepad, add . php to the end of the filename and enclose in double quotations. This ensures the file will not be converted into a basic text file by Notepad.
It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement. The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script.
Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function. Close the file with fclose() function.
chown -R www-data:www-data /var/www/mysite
chmod -R 755 /var/www/mysite
will give you access and allow you to write (and read)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With