Cannot write a file to AWS EC2 instance - PHP

2019-03-03 21:02发布

问题:

I am trying to create and write a file to ec2 instance. I am getting the error below despite the folder that i am writing possessing all the permissions required.

 $handle = fopen("thumbnailFolder/testFile.txt", "r");  // line 4

 if($handle != false){
    echo 'File created!';
 }else{
    echo 'File create failed!';
 }

The 'thumbnailFolder' has the following permissions:

 drwxrwxrwx

Error message:

 fopen(thumbnailFolder/testFile.txt): failed to open stream: No such file or directory in /var/www/html/book_aws/my_server/folder/web/thumbnailTest.php on line 4

File create failed!

回答1:

As the error clearly say. System is failing to open the file which is not there.

$handle = fopen("thumbnailFolder/testFile.txt", "r");

Above code open files in read mode. if there is no files then throws an error.

If you want to open file to write then use try below code, this tries to open file and sets pointer at the begining if file is not there then creates the file in given name. for read and write use w+ instead of w

$handle = fopen("thumbnailFolder/testFile.txt", "w");

There are different modes with respect files. you can check below link for further details.

http://php.net/manual/en/function.fopen.php