KexAri
KexAri

Reputation: 3977

Cannot create new file (newfile.txt) using 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"

Upvotes: 5

Views: 6502

Answers (2)

Danilo Kobold
Danilo Kobold

Reputation: 2581

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)

Upvotes: 5

varunsinghal
varunsinghal

Reputation: 329

Change the permission of file before opening it to read or write.

<?php
//Name
$filename = "newfile.txt";
//change permission of file
chmod($filename,0777);
//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 );
?>

Upvotes: 2

Related Questions