0

I have a function, which has to create a file and write to it, but it only does the first thing. File permissions are 0777.

My code:

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);
    }
}
1stthomas
  • 731
  • 2
  • 15
  • 22
Fell Op
  • 5
  • 5

1 Answers1

0

Relative paths may not work properly. Always use full paths and make sure the directory is writable.

and

Use PHP error reporting!

Below are these fixes:

/*** 
  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);
}

Personally, I think you're being overly careful with if file exists and can happy open the file and simply act if it fails for any reason:

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);
}
Martin
  • 22,212
  • 11
  • 70
  • 132