我正在为我的项目尝试fopen
。它运行在Ubuntu与CodeIgniter PHP框架。结果如下:
A PHP Error was encountered
Severity: Warning
Message: fopen(testFile.txt): failed to open stream: Permission denied
Filename: controllers/home.php
Line Number: 10
can't open file
顺便说一下,这里是我的控制器代码:
public function create_file(){
$ourFileName = 'testFile.txt';
$ourFileHandle = fopen($ourFileName, 'r') or die ("can't open file");
fclose($ourFileHandle);
}
我看了那段代码,我想应该有一个打开文件的路径,对吗?如果是,我应该把路径放在哪里?因为,我遵循了本教程中的代码:http://www.tizag.com/phpT/filecreate.php.
让我困惑的一件事是,没有文件testFile.txt
,我想创建它,但如何给予创建它的权限。因为终端会写No such file or directory for the file
。我该怎么办?
我也试着在www
目录上运行chmod
。但是,它仍然不起作用。希望有人能帮助我处理这个问题。谢谢你…
有两种方法:
1.)使用sudo chmod -R 777/var/www命令将chmod www目录修改为777。这将递归地赋予所有子文件夹和文件权限。
2)。如果你在第一步之后创建了任何新的文件夹(或www目录下的项目),然后按照上面的操作:
=> Right click on your current project folder
=> Scroll to Properties
=> Scroll to permissions
=> Add permission for "Create and Delete files" for owner, group, others.
=> Now click on "Change permission for enclosed files"
=> Give appropriate permissions for files and folders there.
全部完成。现在fopen()不应该给出这个警告。
- 打开终端
- 进入testFile.txt 所在目录
- 类型:sudo chmod 755 testFile.txt(或使用777写入)
用terminal:
创建一个文件sudo touch testFile.txt
如果不存在,用php创建一个文件:
fopen('testFile.txt', 'w');
注意:如果你不是该文件夹的所有者,你不能写。
确保父文件夹/目录至少有755 chmod.
我认为您需要更改要打开的文件的权限。此外,您没有提到是否要读取或写入文件。一般来说,你可以像下面这样给文件赋予权限:
chmod 777 testFile.txt
如果你想要完整的www目录和它的内容递归地拥有所有权限,试试这个:
sudo chmod -R 777 www/
完成上述操作后,您应该能够打开文件,如下面的代码所示:
$handle = fopen("testFile.txt", "r"); // for reading
或
$handle = fopen("testFile.txt", "w"); // for writing
修改函数如下:
public function create_file(){
$ourFileName = 'testFile.txt';
$ourFileHandle = fopen($ourFileName, "w") or die ("can't open file");
fclose($ourFileHandle);
}