繁体   English   中英

file_put_contents仅创建文件,不写入文件

[英]file_put_contents only creates file, don't write to it

我有一个函数,该函数必须创建一个文件并将其写入,但它只做第一件事。 文件权限为0777

我的代码:

function addCookie($id) {
    $path = "users/".$id.".txt";
    if (file_exists($path)) {
        $cookies = file_get_contents($path) + 1;
        file_put_contents($path, $cookies);
    } else {
        $cookies = "1";
        file_put_contents($path, $cookies);
    }
}

相对路径可能无法正常工作。 始终使用完整路径,并确保目录可写。

使用PHP 错误报告

以下是这些修复程序:

/*** 
  Set error log at the top of the page:
 ***/
error_reporting(E_ALL);  

function addCookie($id) {
    $path = $_SERVER['DOCUMENT_ROOT']."/users/".$id.".txt";
    if(is_file($path) && is_readable($path)) {
      $cookies = (int)file_get_contents($path) + 1;
    } else {
       $cookies = "1";
    }
    file_put_contents($path, $cookies);
}

就个人而言,我认为您对文件是否存在过分谨慎, 如果文件由于任何原因失败,可以高兴地打开文件并只是采取行动:

function addCookie($id) {
    $path = $_SERVER['DOCUMENT_ROOT']."/users/".$id.".txt";
    $cookies = file_get_contents($path);        
    $cookies++; //will equal value + 1 or false + 1. Both work for you.
    file_put_contents($path, $cookies);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM