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);
}
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.