how to write concurrent data in json file in php

<?php
$file = 'data.json';
$fp = fopen($file, 'c+'); // Open for reading and writing, create if not exists

if (flock($fp, LOCK_EX)) { // Acquire an exclusive lock
    $current_data = [];
    if (filesize($file) > 0) {
        $json_content = fread($fp, filesize($file));
        $current_data = json_decode($json_content, true);
        if ($current_data === null) {
            // Handle JSON decoding error
            error_log("Error decoding JSON from $file. Resetting data.");
            $current_data = [];
        }
    }

    // Simulate adding new data
    $new_entry = [
        'id' => uniqid(),
        'message' => 'Hello from process ' . getmypid(),
        'timestamp' => date('Y-m-d H:i:s')
    ];

    $current_data[] = $new_entry;

    ftruncate($fp, 0); // Truncate the file
    rewind($fp);      // Rewind file pointer

    $json_output = json_encode($current_data, JSON_PRETTY_PRINT);
    fwrite($fp, $json_output);

    flock($fp, LOCK_UN); // Release the lock
    fclose($fp);
    echo "Data written successfully by process " . getmypid() . "\n";
} else {
    echo "Could not acquire lock for $file by process " . getmypid() . "\n";
}
?>
 $file = 'activitydata.json';
    $fp = fopen($file, 'c+');   

if (flock($fp, LOCK_EX)) {
    $arrayData = [];
     if (filesize($file) > 0) {

        $currentData =  fread($fp, filesize($file));
        $arrayData = json_decode($currentData, true);  // true for associative array
            if ($arrayData === null) {
            // Handle JSON decoding error
            error_log("Error decoding JSON from $file. Resetting data.");
            $arrayData = [];
        }
     }
       $arrayData[] = $success;
       ftruncate($fp, 0); // Truncate the file
       rewind($fp);      // Rewind file pointer
         $jsonData = json_encode($arrayData, JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT for readability
         fwrite($fp, $jsonData);
         flock($fp, LOCK_UN); // Release the lock
         fclose($fp);
}

how to write concurrent data in json file

PHP enable concurrent and simultaneous writes to json file

Scenario: I have a website hosted which is being accessed by multiple users (1000+), I have to store their selections/choices in a single json file (on server). I use PHP and JQuery for this.

Problem: the code is not able to log data from multiple users. the data is getting overwritten. If I use lock (php) only one user gets to write , and other users data doesnt get saved. I tried append and got horrible results (lots of data repetition)

Looking for: A way to allow simultaneous writes to the json file using php without losing or overwriting data. Or a better approach for storing these user preferences/choices.

I thought of keeping data in localstorage/sessionstorage and commit write on browser exit, but I couldnt find a foolproof way to always catch a browser exit across various avl versions of IE, Chrome, Firefox, safari.

create and append json file php

To create and append data to a JSON file using PHP, the following steps are required:

  • Define the JSON file path: Specify the name and location of the JSON file.

Code

    $filename = 'data.json';
  • Prepare the new data: Create an associative array in PHP representing the data to be appended.

Code

    $newData = [
        'name' => 'Aditya Singh',
        'age' => 43,
        'city' => 'India'
    ];
  • Read existing data (if any): Check if the JSON file exists. If it does, read its contents and decode them into a PHP array.

Code

    if (file_exists($filename)) {
$currentData = file_get_contents($filename);
$arrayData = json_decode($currentData, true); // true for associative array
} else {
$arrayData = []; // Initialize an empty array if file doesn't exist
}
  • Append new data: Add the $newData to the $arrayData. If the JSON file stores an array of objects, append the new data as a new element in that array.

Code

    $arrayData[] = $newData;
  • Encode and write to file: Convert the updated PHP array back into a JSON string using json_encode() and write it to the file using file_put_contents().

Code

    $jsonData = json_encode($arrayData, JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT for readability
file_put_contents($filename, $jsonData);

This process ensures that new data is added without overwriting existing content, while also handling the creation of the file if it doesn’t already exist.

minimum-stability dev or stable meaning

In the context of dependency management with tools like Composer, “minimum-stability” determines the least stable version of a package that Composer will consider during dependency resolution. “dev” represents the least stable, while “stable” represents the most stable. 

Here’s a breakdown: 

  • dev:This is the least stable version, typically used for development and testing. It’s not recommended for production environments due to potential instability and breaking changes.
  • stable:This signifies the most stable version, suitable for production use. It indicates a release that has been thoroughly tested and is considered reliable.

When minimum-stability is set to dev, Composer will consider all versions, including development branches (like dev-main) and alpha/beta releases, if no stable version is available. If minimum-stability is set to stable, only stable releases will be considered, and development versions will be ignored. 

For example, if you have minimum-stability: dev and prefer-stable: true, Composer will try to install stable versions first, but if a stable version isn’t available, it will fall back to a development version. 

how to enable imagick php extension in whm for php 8.2

To enable the Imagick PHP extension for PHP 8.2 in WHM, you need to use the Module Installers feature, specifically the PHP PECL installer. After logging into WHM as root, navigate to Software -> Module Installers, select PHP PECL, choose PHP 8.2 from the dropdown, search for “imagick”, and click Install. 

Here’s a step-by-step guide:

  1. Log in to WHM: Access your WebHost Manager (WHM) with root access. 
  2. Navigate to Module Installers: Go to the “Software” section and then click on “Module Installers”. 
  3. Select PHP PECL: Click on the “Manage” button next to “PHP PECL”. 
  4. Choose PHP Version: Select PHP 8.2 from the dropdown menu. 
  5. Search for Imagick: In the search box, type “imagick” and click “Go”. 
  6. Install Imagick: Click on the “Install” button under the “Actions” column. 
  7. Confirmation: The system will start the installation process and display a success message upon completion. 

display series of month in php between years

$start    = (new DateTime(‘2025-01-01’))->modify(‘first day of this month’);

$end      = (new DateTime(‘2036-01-01’))->modify(‘first day of next month’);

$interval = DateInterval::createFromDateString(‘1 month’);

$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {

    echo $dt->format(“Y-m”) . “<br>\n”;

}

Pagination example with previous and next in php

$record = 75;
$condition = "";
if(isset($_GET['page_no']) && $_GET['page_no'])
{
 $page_no = $_GET['page_no'];
}else
{
    $page_no = 1;
}

$condition =""; 
$table = "table_name";

$rec = 0;
$reqpage = explode('?',$_SERVER['REQUEST_URI'])[0];
$total = $obj->GetNumberOfRows($table,$condition);
    $pages = $total / $record;

    $rec = ($page_no - 1) * $record;
    $prev = $page_no - 1;
    $next = $page_no + 1;
    $prevlinks = "";
    $nextlinks = "";
    $pages = ceil($pages);
    if($prev >= 1)
    {
    $prevlinks = "<li class='page-item'>
      <a class='page-link' href='$reqpage?page_no=$prev' aria-label='Previous'>
        <span aria-hidden='true'>&laquo;</span>
        </a>
    </li>";
    }
    if($next <= $pages)
    {
    $nextlinks = "<li class='page-item'>
      <a class='page-link' href='$reqpage?page_no=$next' aria-label='Next'>
        <span aria-hidden='true'>&raquo;</span>
        </a>
    </li>";
    }
  echo "<nav aria-label='Page navigation example' class='mt-3'>
  <ul class='pagination'>".$prevlinks." <li class='page-item'><a class='page-link bg-primary text-white'>&nbsp;$page_no&nbsp;</a></li> ".$nextlinks." </ul></nav>";
  }

$objresult=$obj->GerFunction($para1,$para2,$para3,$rec);

Pagination example with page number in php

$record = 10;
$condition = "";
if(isset($_GET['page_no']) && $_GET['page_no'])
{
 $page_no = $_GET['page_no'];
}else
{
    $page_no = 1;
}

$condition =""; 
$table = "table_name";

$rec = 0;
$reqpage = explode('?',$_SERVER['REQUEST_URI'])[0];
$total = $obj->GetNumberOfRows($table,$condition);
    $pages = $total / $record;
    $links = "";
    if($pages > 1){
    for ($i = 1; $i <= ceil($pages); $i++) {
      $rec = ($page_no - 1) * $record;
    $links .= ($i != $page_no ) 
           ? "<li class='page-item'><a class='page-link' href='$reqpage?page_no=$i'>$i</a> </li>": "<li class='page-item active'><a class='page-link'>".$page_no."</a></li>";
    }
}

echo "<nav aria-label='Page navigation example' class='mt-3'>
  <ul class='pagination'>".$links." </ul></nav>";


$objresult=$obj->GetFunction($para1,$para2,$para3,$rec);

default file and folder permissions in linux for laravel

In a Linux environment, Laravel projects generally use file permissions of 644 for files and 755 for folders, with some exceptions for specific directories like storage and bootstrap/cache which might require 775 or even 777 for write access by the web server user. 

File Permissions (644):

  • Owner: Read and Write (rw)
  • Group: Read (r)
  • Others: Read (r) 

Folder Permissions (755):

  • Owner: Read, Write, and Execute (rwx)
  • Group: Read and Execute (r-x)
  • Others: Read and Execute (r-x) 

Special Cases (775/777):

  • storage and bootstrap/cache:These directories need write access for the web server user (often www-data) to store temporary files, logs, and cached data. Therefore, these folders may require 775 or even 777 permissions to allow the web server to write to them. 
  • Other writable folders:Depending on your project’s specific needs, you may also need to adjust permissions for other folders that require write access by the web server. 

Why these permissions?

  • Security:Limiting permissions to the minimum necessary helps prevent unauthorized access and modification. 
  • Performance:Allowing the web server to access and modify files without excessive permissions improves performance. 
  • Laravel Functionality:Laravel relies on certain directories being writable to function correctly. 

How to set permissions:

You can use the chmod command to change file and folder permissions. For example: 

  • To set all files to 644: chmod -R 644 ./*
  • To set all folders to 755: chmod -R 755 ./*
  • To set storage and bootstrap/cache to 775: chmod -R 775 storage bootstrap/cache

Important Considerations:

  • Web Server User:Make sure the web server user (e.g., www-data) has the necessary permissions (write, read, execute) on the relevant directories. 
  • Project Root:These commands should be run from the project’s root directory. 
  • Recursive Changes:The -R flag applies the changes recursively to all files and folders within the current directory. 
  • Security:Avoid excessive permissions on files and folders, as it can create security vulnerabilities.