Failed to open dir : Bad file descriptor - php

I face this problem. When i try to open the file list in other server which is 10.200.4.202. The error below appears.
When I try using a local host, the file list can be viewed normally. I think the code is not the error but the server setting is not right.
I used IIS 10.0, PHP 7.3.15
This is what appears on web
status[parsererror] content[SyntaxError: Unexpected token < in JSON at position 0]
and this is the error in f12
Warning:
opendir(\\10.200.4.202\y\1.InspCheckSheet_PDF\log,\\10.200.4.202\y\1.InspCheckSheet_PDF\log): Access is denied. (code: 5) in C:\PGMPIS_Web\public_html\ics_filing\loglist_sub.php on line 68
Warning:
opendir(\\10.200.4.202\y\1.InspCheckSheet_PDF\log): failed to open dir: Bad file descriptor in C:\PGMPIS_Web\public_html\ics_filing\loglist_sub.php
on line 68
{"querytime":"2020-05-14 09:58:50","other_status":"ERR","errmsg":""}
Here's the code
<?php
$dir_log = '\\\\10.200.4.202\\y\\1.InspCheckSheet_PDF\\log';
require_once 'Log.php';
$log = Log::factory('file', 'log/okaspe.log', 'loglist_sub'); //$log->log('teeeeest!');
//$type = $_REQUEST['type'];
try{
// Set query_time
$emsg = "";
$now = new DateTime();
$res['querytime'] = $now->format('Y-m-d H:i:s');
//$res['querytime'] = $now->format('Y-m-d g:i:s A');
// Obtain log file name list → $fn[]
$cnt = $pos = 0;
unset($fn); // clear $fn for safety
if( $dir = opendir($dir_log) ) { // add # infront of opendir by asyraf
while (($file = readdir($dir)) !== false ) {
$pos = strpos ($file, 'main_'); // faster than preg_match() for simple search
if( $pos !== false && $pos == 0) {
$cnt++;
$fn[] = $file;
}
}
closedir($dir);
} else {
throw new Exception("Obtain Log File List failed......");
}
// sort in descending order
rsort($fn); //$log->log( print_r($fn, true) );
//set response
$res['list'] = $fn;
$res['cnt'] = $cnt;
} catch( Exception $e ) {
// Functional Err exception
$res["other_status"] = "ERR";
$res["errmsg" ] = $emsg;
$log->log($e->getMessage(), PEAR_LOG_ERR); // logging
} finally {
//DB disconnect (absolutely and always)
$pdo = null;
// Response in Json
header('Content-Type: application/json; charset=utf-8');
$json = json_encode( $res ); //$log->log($json, PEAR_LOG_ERR);
echo $json;
}
exit;
?>

Related

Codeginiter : chmod(): Invalid argument error

I am using pdftk library for modify the pdf files. but i am getting the chmod(): Invalid argument error.
Following is my code :
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf, 777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);
I have given all the necessary permission to folder and files. but don't know what is wrong??
Thanks in advance!!!
Why you need to give chmod($fdf,0777); to $fdf. It's not even the file. as per your code the $fdf = createXFDF( $pdf_file_url, $acord ); is calling function and it's not file. so just comment the chmod($fdf,0777); line and check your code is working or not??
Hope it helps!!!
Try like this...For chmod() function first number is always zero.
chmod(file,mode);
The mode parameter consists of four numbers:
1.The first number is always zero
2.The second number specifies permissions for the owner
3.The third number specifies permissions for the owner's user group
4.The fourth number specifies permissions for everybody else
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf,0777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);

PHP - fopen: failed to open stream: Permission denied

I'm new to PHP. I planned to create folder, sub folder, into that file depends on user Input.
Folder and sub folders has been created successfully.
Finally I try to create a file its showing bellow error.
fopen(upload/localhost/hrms): failed to open stream: Permission denied
in C:\xampp\htdocs\ssspider\index.php on line 205
My code is:
$dir = "http://localhost:8080/hrms/index.php";
//make directory
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
mkdir($directoryForClient);
$splitePath = explode("/", $folderPath);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>";
mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen($dir,"w");
if($myFile)
{
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
Please help me to find out my problem?
Edit: Thanks. I got an error. In fopen I didn't mention file name . Now its working fine. Thanks
because you open a directory , fopen function just open file. your code is fill with error , just Refer to the following:
<?php
//make directory
$host = "aa"; //define $host variable
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
#mkdir($directoryForClient);
$splitePath = explode("/", $directoryForClient);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>2";
#mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen("upload/aa.txt","w");
if($myFile)
{
$returned_content = "hello world"; //define variable and his content before write to file.
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}

php warning fclose() expects parameter 1 to be resource boolean given

I use newrelic to keep track of anything on my website and I always get this error:
Error message: E_WARNING: fclose() expects parameter 1 to be resource, boolean given
Stack trace: in fclose called at /etc/snmp/bfd-stats.php (68)
This is how /etc/snmp/bfd-stats.php looks like
<?php
$a = 0;
$ptr = 0;
$any = 0;
$mx = 0;
$ns = 0;
$cname = 0;
$soa = 0;
$srv = 0;
$aaaa = 0;
$txt = 0;
$total = 0;
if(file_exists('/etc/snmp/bfd-log-pos.stat')) {
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','r');
$string = fread($lfh,2087);
$res = explode(',',$string);
fclose($lfh);
}
else {
$res = array();
$res[0] = 0;
$res[1] = 0;
}
if(file_exists("/var/log/bfd_log.1")) {
$stats = stat('/var/log/bfd_log.1');
if($stats[10] > $res[0]) {
$res[0] = 0;
$res[1] = 0;
}
}
$fh = fopen('/var/log/bfd_log', 'r');
fseek($fh,$res[1]);
$blocks = 0;
if(!$fh) {
echo "Error! Couldn't open the file.";
} else {
while (!feof($fh)) {
$data = fgets($fh);
if(preg_match('/executed\sban/',$data)) {
$blocks++;
}
}
}
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','w');
$timestamp = time();
$pos = ftell($fh);
fwrite($lfh,"$timestamp,$pos");
fclose($lfh);
if(!fclose($fh)) {
echo "Error! Couldn't close the file.";
}
print("bfd_blocks\n$blocks");
?>
On line 40: $fh = fopen('/var/log/bfd_log', 'r'); I looked at the directory /var/log and there is no file called bfd_log, I dont know if I have to create it by myself or it is automatically created.
Can anyone help me on fixing this error, Thanks in advance.
The error indicates that you are trying to pass a variable with a boolean value (true/false) to a function that needs a resource instead of a boolean value.
Please make sure that before you use resources from variables, the function that returns the resource has not run into trouble. Only on success perform the other functions that use this resource/variable.
$fh = fopen('/var/log/bfd_log', 'r');
// check fh before other functions use this variable
if (!$fh) {
echo "Error! Couldn't open the file.";
} else {
// perform task with resource $fh
fseek($fh, $res[1]);
[...]
$lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w');
// check before other code block is executed and use this variable
if( $lfh )
{
// perform task with resource $lfh
$pos = ftell($fh);
fwrite($lfh, "$timestamp,$pos");
fclose($lfh);
fclose($fh);
[...]
} else {
// lfh error
}
}
If you always check before using variables, you won't run into this error anymore.
I wrestled with this problem and could not find the answer until I separated my write check (put it first) from the actual file write code. So before I would open the file fopen/fwrite then do the is_writable check and then do the fclose and i would get this error.
To resolve I moved the is_writable and variable declaration before the fopen/fwrite and the error went away. Shown below (former php code position shown in comments) The first comment did help me realize this... Thank you.
$myfile = "/var/www/html/newfile.txt";
if (is_writable($myfile)) {
echo "The file is writable";
}
else {
echo "The file is not writable";
}
$txt = "$name, $email, $command, $searchtype, $keyword \n";
$myfile = fopen('/var/www/html/newfile.txt', 'w') or die("Unable to open file!");
fwrite($myfile, $txt);
// $myfile = "/var/www/html/newfile.txt";
// if (is_writable($myfile)) {
// echo "The file is writable";
// }
// else {
// echo "The file is not writable";
// }
fclose($myfile);
Try
$fh = fopen('/var/log/bfd_log', 'a+');
a+ mode will create the file if it does not exists

PHP die stops everything. What else can I use?

I hope this is the last time I have to bother you good people. I'm a newbie hack who is working on a unique hit counter for each page of a web site. I seem to have it working properly but after the first time when it hits and adds the IP to the file it stops the whole page from loading on refresh or coming back. I know the problem is with the 'die' statement which ends the loop of checking for the IP. I have also tried 'break' and 'exit' but the same thing happens. I have searched for anything else but I can't find anything. Is there a way of getting out of the php code without stopping everything else from loading? Thanks in advance.
<?php
// Declare string names
$ip_file = "ip_index.txt";
// get ip address of user
$user_ip = $_SERVER['REMOTE_ADDR'];
$ip_handle = fopen($ip_file, "r");
while (!feof($ip_handle) ) {
$line_of_text = fgets($ip_handle);
$ip = trim($line_of_text);
if ($user_ip==$ip){
die();
}
}
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$handle = fopen($count_file, "r");
$old_count=fgets($handle);
fclose($handle);
// write contents of count.txt
$fp = fopen($count_file, 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($count_file, "w");
$new_count = $old_count +1;
fwrite($handle, $new_count);
fclose($handle);
// write new IP to ip.txt file
$fp = fopen($ip_file, 'r');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($ip_file, 'a+');
$w_user_ip=$user_ip . "\n";
fwrite($handle, $w_user_ip);
fclose($handle);
?>
Don't exit the whole script when you find a match, just exit the loop. Set a variable that allows you to skip over the code that increments the unique hit counter.
$ip_exists = false;
while (!feof($ip_handle) ) {
$line_of_text = fgets($ip_handle);
$ip = trim($line_of_text);
if ($user_ip==$ip){
$ip_exists = true;
break;
}
}
if (!$ip_exists) {
// Update all the files
...
}
Not sure what you mean. You can reverse the condition of the if block and then just wrap the remaining code in the braces.
eg
if ($user_ip != $ip) {
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
// ... etc
}
}
When you have:
if ($user_ip==$ip){
die();
}
Put everything you don't want to run if the IPs are the same in an else{} block
Do this:
....
if ($user_ip != $ip) {
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$handle = fopen($count_file, "r");
$old_count=fgets($handle);
fclose($handle);
// write contents of count.txt
$fp = fopen($count_file, 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($count_file, "w");
$new_count = $old_count +1;
fwrite($handle, $new_count);
fclose($handle);
// write new IP to ip.txt file
$fp = fopen($ip_file, 'r');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($ip_file, 'a+');
$w_user_ip=$user_ip . "\n";
fwrite($handle, $w_user_ip);
fclose($handle);
}
If this is included by other code you can use return:
if ($user_ip==$ip){
return;
}
This will stop further execution of your script but code which is including wont die.
If on the other hand you want to terminate the while loop only then break is what you need (what issue did you have when using it?)
if ($user_ip==$ip){
break;
}

PHP Simultaneous file access / flock() issue

I'm having trouble implementing a script which should parse a json string from a file, either overwrite the object with the same id or add it to the json array and write it back to the file. The script is called in a for loop so that I tried to use flock to prevent overwriting the file before the json string could be parsed, but the results look really strange and I don't know whats going wrong. Here is the script:
$method = $_SERVER['REQUEST_METHOD'];
$file = fopen($userid . '.json', 'c+');
flock($file, LOCK_EX);
$jsonStr = (filesize($userid . '.json') == 0 ) ? '{"success": true}' : fread($file, filesize($userid . '.json'));
$jsonObj = json_decode($jsonStr);
if($method === 'POST') {
$dataStr = file_get_contents('php://input');
$dataObj = json_decode($dataStr);
$replacements = array();
if(isset($jsonObj->images)) {
foreach($jsonObj->images as $idx=>$image) {
if($image->id == $dataObj->id) {
$replacements += array($idx => $dataObj);
}
}
if(count($replacements)==0) {
array_push($replacements, $dataObj);
}
$jsonObj->images = array_replace($jsonObj->images, $replacements);
} else {
//$jsonObj = new stdClass();
$jsonObj->images = new stdClass();
$jsonObj->images = array($dataObj);
}
fwrite($file, json_encode($jsonObj));
file_put_contents('log.json', json_encode($dataObj), FILE_APPEND);
echo '{"success":true, "images":' . $dataStr . '}';
} else if($method === 'GET') {
echo $jsonStr;
}
fclose($file);
As result I get sometime three files one just called ".json" and the other one correctly userid.json and the log.json. The log looks best, since all 26 objects are shown correctly, but without checking for exiting objects previously. The ".json" is just blank and the looks really odd:
{"success":true,"images":[{"id":"f9f4b6ee-8b7b-414e-98f4-47ed5ee3c594","top":1200,"left":4050,"clicks":0,"affinity":[]}]}
{"success":true,"images":[{"id":"034c7661-9466-4651-b860-7e049e1543ac","top":900,"left":600,"clicks":0,"affinity":[]}]}
{"images":[{"id":"eebc35ec-6c0e-416a-9516-061df821083d","top":1800,"left":3300,"clicks":0,"affinity":[]}]}
{"images":[{"id":"e09da5b9-2e65-4a12-94cd-4745b354a256","top":1200,"left":1200,"clicks":0,"affinity":[]}]}
{"images":[{"id":"b023a259-4554-48a5-acd8-cb4215e6a391","top":1350,"left":1500,"clicks":0,"affinity":[]}]}
{"images":[{"id":"6521d8c3-461c-4fcd-b69d-69f14ae37418","top":600,"left":3750,"clicks":0,"affinity":[]}]}
{"images":[{"id":"4c082c1a-d4ae-4c1c-bfc4-ed36980f5db2","top":3150,"left":600,"clicks":0,"affinity":[]}]}
{"images":[{"id":"22dbdea2-4936-4353-825e-9af6e6f2ca93","top":3000,"left":2100,"clicks":0,"affinity":[]}]}
{"images":[{"id":"a7ba32d4-912e-489d-8f9b-e412bc1629c1","top":2850,"left":3750,"clicks":0,"affinity":[]}]}
{"images":[{"id":"b258148d-1779-4f17-ae5e-1160aa0a34b9","top":750,"left":4050,"clicks":0,"affinity":[]}]}
{"images":[{"id":"21c1c9d1-a7a6-48d2-a4ba-174c0fe248a3","top":1650,"left":750,"clicks":0,"affinity":[]}]}
{"images":[{"id":"bfed2f56-7876-4eb2-a217-e0f71f4455ee","top":3300,"left":1500,"clicks":0,"affinity":[]}]}
{"images":[{"id":"7f13b674-5d07-444f-bf6d-463758c96788","top":1650,"left":1950,"clicks":0,"affinity":[]}]}
{"images":[{"id":"fb8711f2-ba10-44d7-9038-02cae6438506","top":1800,"left":450,"clicks":0,"affinity":[]}]}
{"images":[{"id":"ac83e869-e4fb-4eee-8d2e-4d26762101d9","top":750,"left":1800,"clicks":0,"affinity":[]}]}
{"images":[{"id":"069a7595-2271-4430-b324-974115df7b80","top":2550,"left":1800,"clicks":0,"affinity":[]}]}
{"images":[{"id":"ea9ab2fc-e179-4f56-9ce7-8af456911b33","top":1950,"left":750,"clicks":0,"affinity":[]}]}
{"images":[{"id":"9b997ae3-0c66-4f78-937a-2fde2470d7d7","top":300,"left":300,"clicks":0,"affinity":[]}]}
{"images":[{"id":"f860dea4-3b27-4401-999b-72ce45022110","top":1200,"left":1950,"clicks":0,"affinity":[]}]}
{"images":[{"id":"2633c107-8a51-4e9c-bc2c-f87c30f7359d","top":750,"left":2100,"clicks":0,"affinity":[]}]}
{"images":[{"id":"bebcb2bb-c2f0-4e4d-b202-b05090eacf49","top":3600,"left":3600,"clicks":0,"affinity":[]}]}
{"images":[{"id":"460f961e-f1dd-4329-95be-d30770a37b83","top":2400,"left":1200,"clicks":0,"affinity":[]}]}
{"images":[{"id":"ee9b254f-fe6a-4ece-a662-e934625e992a","top":3600,"left":600,"clicks":0,"affinity":[]}]}
{"images":[{"id":"4e047ea9-345e-4cf9-a066-d0b431820c61","top":2100,"left":1350,"clicks":0,"affinity":[]}]}
{"images":[{"id":"8bbb5327-6d39-40e1-919e-d7b70e13fc2b","top":2700,"left":1200,"clicks":0,"affinity":[]}]}
{"images":[{"id":"0c50c0ec-e18b-4917-9787-bad245eed798","top":1200,"left":2550,"clicks":0,"affinity":[]}]}
I also get an exception:
<b>Strict Standards</b>: Creating default object from empty value in <b>C:\xampp\htdocs\gallery\store.php</b> on line <b>38</b><br />
I guess I didn't understand the procedure correctly and I'm happy for any help.
EDIT: The result I want, looks like this:
{"success":true,"images":[{"id":"f9f4b6ee-8b7b-414e-98f4-47ed5ee3c594","top":1200,"left":4050,"clicks":0,"affinity":[]},
{"id":"034c7661-9466-4651-b860-7e049e1543ac","top":900,"left":600,"clicks":0,"affinity":[]},{"id":"eebc35ec-6c0e-416a-9516-061df821083d","top":1800,"left":3300,"clicks":0,"affinity":[]},
{"id":"e09da5b9-2e65-4a12-94cd-4745b354a256","top":1200,"left":1200,"clicks":0,"affinity":[]},
{"id":"b023a259-4554-48a5-acd8-cb4215e6a391","top":1350,"left":1500,"clicks":0,"affinity":[]},
{"id":"6521d8c3-461c-4fcd-b69d-69f14ae37418","top":600,"left":3750,"clicks":0,"affinity":[]},
{"id":"4c082c1a-d4ae-4c1c-bfc4-ed36980f5db2","top":3150,"left":600,"clicks":0,"affinity":[]},
{"id":"22dbdea2-4936-4353-825e-9af6e6f2ca93","top":3000,"left":2100,"clicks":0,"affinity":[]},
{"id":"a7ba32d4-912e-489d-8f9b-e412bc1629c1","top":2850,"left":3750,"clicks":0,"affinity":[]},
{"id":"b258148d-1779-4f17-ae5e-1160aa0a34b9","top":750,"left":4050,"clicks":0,"affinity":[]},
{"id":"21c1c9d1-a7a6-48d2-a4ba-174c0fe248a3","top":1650,"left":750,"clicks":0,"affinity":[]},
{"id":"bfed2f56-7876-4eb2-a217-e0f71f4455ee","top":3300,"left":1500,"clicks":0,"affinity":[]},
{"id":"7f13b674-5d07-444f-bf6d-463758c96788","top":1650,"left":1950,"clicks":0,"affinity":[]},
{"id":"fb8711f2-ba10-44d7-9038-02cae6438506","top":1800,"left":450,"clicks":0,"affinity":[]},
{"id":"ac83e869-e4fb-4eee-8d2e-4d26762101d9","top":750,"left":1800,"clicks":0,"affinity":[]},
{"id":"069a7595-2271-4430-b324-974115df7b80","top":2550,"left":1800,"clicks":0,"affinity":[]},
{"id":"ea9ab2fc-e179-4f56-9ce7-8af456911b33","top":1950,"left":750,"clicks":0,"affinity":[]},
{"id":"9b997ae3-0c66-4f78-937a-2fde2470d7d7","top":300,"left":300,"clicks":0,"affinity":[]},
{"id":"f860dea4-3b27-4401-999b-72ce45022110","top":1200,"left":1950,"clicks":0,"affinity":[]},
{"id":"2633c107-8a51-4e9c-bc2c-f87c30f7359d","top":750,"left":2100,"clicks":0,"affinity":[]},
{"id":"bebcb2bb-c2f0-4e4d-b202-b05090eacf49","top":3600,"left":3600,"clicks":0,"affinity":[]},
{"id":"460f961e-f1dd-4329-95be-d30770a37b83","top":2400,"left":1200,"clicks":0,"affinity":[]},
{"id":"ee9b254f-fe6a-4ece-a662-e934625e992a","top":3600,"left":600,"clicks":0,"affinity":[]},
{"id":"4e047ea9-345e-4cf9-a066-d0b431820c61","top":2100,"left":1350,"clicks":0,"affinity":[]},
{"id":"8bbb5327-6d39-40e1-919e-d7b70e13fc2b","top":2700,"left":1200,"clicks":0,"affinity":[]},
{"id":"0c50c0ec-e18b-4917-9787-bad245eed798","top":1200,"left":2550,"clicks":0,"affinity":[]}]}
Cheers,
Daniel
I finally have it working and for anyone else having issues with simultaneous file access, here's my solution:
Check if the file exists, if not, create it and set up the data structure (to prevent the strict standard error)
$filename = $userid . '.json';
if(!file_exists($filename)) {
$file = fopen($filename, 'w');
if(flock($file, LOCK_EX)) {
fwrite($file, '{"success": true, "images": []}');
flock($file, LOCK_UN);
fclose($file);
}
}
Open the file using c+ as second parameter (w+ would set the filesize to 0). Check if you can get the exclusive lock. Read the file and rewind in order to overwrite it later.
else {
$file = fopen($userid . '.json', 'c+');
if(flock($file, LOCK_EX)) {
$jsonStr = fread($file, filesize($userid . '.json'));
$jsonObj = json_decode($jsonStr);
rewind($file);
Manipulate the object how you need it and write it back as encoded json string using fwrite
if($method === 'POST') {
$dataStr = file_get_contents('php://input');
if(isset($dataStr) &&$dataStr != '') {
$dataObj = json_decode($dataStr);
$replace = -1;
foreach($jsonObj->images as $idx=>$image) {
if($image->id == $dataObj->id) {
$replace = $idx;
}
}
if($replace != -1) {
$img = $jsonObj->images;
$img[$replace] = $dataObj;
$jsonObj->images = $img;
} else {
array_push($jsonObj->images, $dataObj);
}
fwrite($file, json_encode($jsonObj));
}
echo '{"success":true, "images":' . $dataStr . '}';
} else if($method === 'GET') {
echo $jsonStr;
}
Release the lock and close the file.
flock($file, LOCK_UN);
fclose($file);
}
}

Categories