首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cronjob: fwrite in php

Cronjob: fwrite in php
EN

Stack Overflow用户
提问于 2018-06-01 15:30:32
回答 2查看 403关注 0票数 0

我写了那封信:

代码语言:javascript
复制
*/1 * * * * /usr/bin/php /home/ec2-user/neu/test.php >> /home/ec2-user/neu/log.log 2>&1

我使用了代码示例(test.php):

代码语言:javascript
复制
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
  if (is_writable($filename)) {

// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
     echo "Cannot open file ($filename)";
     exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
}

echo "Success, wrote ($somecontent) to file ($filename)";

fclose($handle);

} else {
    echo "The file $filename is not writable";
 }
?>

但这不适用于任人唯亲。

在日志文件(log.log)中:

代码语言:javascript
复制
test.txt is not writable

许可:-rwxrwxrwx 1根根21 6月1日17:21 test.txt

然而,在终点站,它做到了:

代码语言:javascript
复制
php test.php

[root@ip-172-31-39-112 neu]# php test.php
Success, wrote (Add this to the file
) to file (test.txt)[root@ip-172-31-39-112 neu]#

我该怎么解决这个许可问题?

Thx

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-01 15:43:05

尝试在脚本的开头添加:

代码语言:javascript
复制
chdir("/home/ec2-user/neu");

或者使用文件的绝对路径。

cron作业可能从另一个目录执行,并且test.php文件不存在。

如果它仍然不工作,检查selinux配置,如果您的计算机已安装它。

票数 2
EN

Stack Overflow用户

发布于 2018-06-01 15:39:11

您可以在php中使用file_put_contents。

请参阅:

( a) contents.asp

( b) http://php.net/manual/en/function.file-put-contents.php

代码语言:javascript
复制
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
file_put_contents($filename,$somecontent, FILE_APPEND);
?>  

模式FILE_APPEND所能做的事情

如果文件文件名已经存在,则将数据追加到文件中,而不是覆盖它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50646768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档