Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create new file (newfile.txt) using php

Tags:

php

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"

like image 581
KexAri Avatar asked Jul 09 '15 07:07

KexAri


People also ask

How do you create a file if it doesn't exist in PHP?

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).

How do I save a Notepad file as PHP?

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.

Which is the correct way to include a file text PHP in PHP code?

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.

How do you read or write a file on the server from PHP give example?

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.


1 Answers

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)

like image 74
Danilo Kobold Avatar answered Sep 30 '22 05:09

Danilo Kobold