Friday, May 16, 2025

Restrict a PHP script so that it only runs via cron (CLI execution) OR cron based HTTP but prevent accessed from a browser (HTTP request)

 Restrict a PHP script so that it only runs via cron (CLI execution) OR cron based HTTP but prevent accessed from a browser (HTTP request)


define('APPLICATION_SERVER_IP', '123.123.123.123');

define('CRON_SECRET_KEY', 'e17Il1b9aA0Oa');


function writeToLog($message, $logLevel = 'INFO') {

    $logFile = __DIR__ . '/../logs/cron_logs.log'; // Change as needed

    if (!file_exists($logFile)) {

        touch($logFile);

        chmod($logFile, 0644);

    }

    $timestamp = date("Y-m-d H:i:s");

    $logMessage = "[$timestamp] [$logLevel] $message" . PHP_EOL;

    error_log($logMessage, 3, $logFile);

}


// Validate access

if (

    isset($_SERVER['REMOTE_ADDR'], $_GET['CRON_SECRET_KEY']) &&

    $_SERVER['REMOTE_ADDR'] === APPLICATION_SERVER_IP &&

    $_GET['CRON_SECRET_KEY'] === CRON_SECRET_KEY

) {

    echo "Safe execution";

    // Place your execution logic here

    writeToLog("Cron executed successfully.", "INFO");

} else {

    $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';

    writeToLog("Unauthorized hit from IP: $ip", "WARNING");

    http_response_code(403);

    exit("You don't have permission to access.");

}

Monday, September 5, 2022

Composer detected issues in your platform: Your Composer dependencies require a PHP version

 Composer detected issues in your platform: Your Composer dependencies require a PHP version 

Faster and quick solution 

Path: ~/.composer/vendor/composer/platform_check.php

if (!(PHP_VERSION_ID >= 70300)) {
    $issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.0". You are running ' . PHP_VERSION . '.';
}

Here update/change php version id as your need

Monday, June 14, 2021

PHP Warning: session_start(): Failed to read session data: files (path: /var/cpanel/php/sessions/ea-phpXX)

 After upgrading the server/ PHP version/ Cpanel account transferring to a different server we might face this PHP Warning. It because of the session path-changing issue.

Example before transferring Cpanel account their was the variable session.save_path   might set different

Before session.save_path=/var/cpanel/php/sessions/ea-php56

After you might need to update based on your php version like 7.2 7.3

session.save_path=/var/cpanel/php/sessions/ea-php72

Or 

session.save_path=/var/cpanel/php/sessions/ea-php73

We can change this variable session.save_path path  using changing php ini file or using cpanel 

Login Cpanel  then

MultiPHP INI Editor >> Basic Mode" for each version of PHP installed on the system. However, ensure to revert this value back to "/var/cpanel/php/sessions/ea-php$$"

Here $$ means your current PHP version. example php71 /php72 / php73 / php74 



Saturday, January 2, 2021

Create table and copy from another database

CREATE TABLE destination_db.new_table LIKE source_db.existing_table; INSERT destination_db.new_table SELECT * FROM source_db.existing_table;

Sunday, December 27, 2020

MySQL UPDATE ONE TABLE WHERE CONDITION FROM ANOTHER TABLE

 Summary: in this tutorial, you will learn how to use the MySQL UPDATE JOIN statement to perform the cross-table update. We will show you step by step how to use INNER JOIN  clause and LEFT JOIN  clause with the UPDATE statement.

MySQL UPDATE JOIN syntax

You often use joins to query rows from a table that have (in the case of INNER JOIN) or may not have (in the case of LEFT JOIN) matching rows in another table. In MySQL, you can use the JOIN clauses in the UPDATE statement to perform the cross-table update.

The syntax of the MySQL UPDATE JOIN  is as follows:

UPDATE T1, T2, [INNER JOIN | LEFT JOIN] T1 ON T1.C1 = T2. C1 SET T1.C2 = T2.C2, T2.C3 = expr WHERE condition

Let’s examine the MySQL UPDATE JOIN  syntax in greater detail:

  • First, specify the main table ( T1 ) and the table that you want the main table to join to ( T2 ) after the UPDATE clause. Notice that you must specify at least one table after the UPDATE  clause. The data in the table that is not specified after the UPDATE  clause will not be updated.
  • Next, specify a kind of join you want to use i.e., either INNER JOIN  or LEFT JOIN  and a join predicate. The JOIN clause must appear right after the UPDATE clause.
  • Then, assign new values to the columns in T1 and/or T2 tables that you want to update.
  • After that, specify a condition in the WHERE clause to limit rows to rows for updating.

If you follow the UPDATE statement tutorial, you will notice that there is another way to update data cross-table using the following syntax:

UPDATE T1, T2 SET T1.c2 = T2.c2, T2.c3 = expr WHERE T1.c1 = T2.c1 AND condition

This UPDATE  statement works the same as UPDATE JOIN  with an implicit INNER JOIN  clause. It means you can rewrite the above statement as follows:

UPDATE T1,T2 INNER JOIN T2 ON T1.C1 = T2.C1 SET T1.C2 = T2.C2, T2.C3 = expr WHERE condition

Let’s take a look at some examples of using the UPDATE JOIN  statement to having a better understanding.

MySQL UPDATE JOIN examples

We are going to use a new sample database named empdb in for demonstration. This sample database consists of two tables:

  • The  employees table stores employee data with employee id, name, performance, and salary.
  • The merits table stores employee performance and merit’s percentage.

MySQL UPDATE JOIN example with INNER JOIN clause

Suppose you want to adjust the salary of employees based on their performance.

The merit’s percentages are stored in the merits table, therefore, you have to use the UPDATE INNER JOIN statement to adjust the salary of employees in the employees  table based on the percentage stored in the merits table.

The link between the employees  and merit tables is the performance  field. See the following query:

UPDATE employees INNER JOIN merits ON employees.performance = merits.performance SET salary = salary + salary * percentage;
MySQL Update Join Example

How the query works.

We specify only the employees table after UPDATE clause because we want to update data in the  employees table only.

For each row in the employees table, the query checks the value in the performance column against the value in the performance column in the merits table. If it finds a match, it gets the percentage in the merits  table and updates the salary column in the employees  table.

Because we omit the WHERE clause in the UPDATE  statement, all the records in the employees  table get updated.

MySQL UPDATE JOIN example with LEFT JOIN

Suppose the company hires two more employees:

INSERT INTO employees(emp_name,performance,salary) VALUES('Jack William',NULL,43000), ('Ricky Bond',NULL,52000);

Because these employees are new hires so their performance data is not available or NULL .

MySQL Update Left Join Example

To increase the salary for new hires, you cannot use the UPDATE INNER JOIN  statement because their performance data is not available in the merit  table. This is why the UPDATE LEFT JOIN  comes to the rescue.

The UPDATE LEFT JOIN  statement basically updates a row in a table when it does not have a corresponding row in another table.

For example, you can increase the salary for a new hire by 1.5%  using the following statement:

UPDATE employees LEFT JOIN merits ON employees.performance = merits.performance SET salary = salary + salary * 0.015 WHERE merits.percentage IS NULL;
MySQL Update Left Join with Example

In this tutorial, we have shown you how to use the MySQL UPDATE JOIN  with the INNER JOIN  and LEFT JOIN  clauses to perform the cross-table update.

Monday, January 6, 2020

Find Duplicate Values in a SQL Table

Generally, it’s best practice to put unique constraints on a table to prevent duplicate rows. However, you may find yourself working with a database where duplicate rows have been created through human error, a bug in your application, or uncleaned data from external sources. This tutorial will teach you how to find these duplicate rows.
To follow along, you’ll need read access to your database and a tool to query your database.

Identify Duplicate Criteria

The first step is to define your criteria for a duplicate row. Do you need a combination of two columns to be unique together, or are you simply searching for duplicates in a single column? In this example, we are searching for duplicates across two columns in our Users table: username and email.

Write Query to Verify Duplicates Exist

The first query we’re going to write is a simple query to verify whether duplicates do indeed exist in the table. For our example, my query looks like this:
SELECT username, email, COUNT(*)
FROM users
GROUP BY username, email
HAVING COUNT(*) > 1
HAVING is important here because unlike WHERE, HAVING filters on aggregate functions.
If any rows are returned, that means we have duplicates. In this example, our results look like this:
USERNAMEEMAILCOUNT
Petepete@example.com2
Jessicajessica@example.com2
Milesmiles@example.com2

List All Rows Containing Duplicates

In the previous step, our query returned a list of duplicates. Now, we want to return the entire record for each duplicate row.
To accomplish this, we’ll need to select the entire table and join that to our duplicate rows. Our query looks like this:
SELECT a.*
FROM users a
JOIN (SELECT username, email, COUNT(*)
FROM users 
GROUP BY username, email
HAVING count(*) > 1 ) b
ON a.username = b.username
AND a.email = b.email
ORDER BY a.email
If you look closely, you’ll see that this query is not so complicated. The initial SELECT simply selects every column in the users table, and then inner joins it with the duplicated data table from our initial query. Because we’re joining the table to itself, it’s necessary to use aliases (here, we’re using a and b) to label the two versions.
Here is what our results look like for this query:
IDUSERNAMEEMAIL
1Petepete@example.com
6Petepete@example.com
12Jessicajessica@example.com
13Jessicajessica@example.com
2Milesmiles@example.com
9Milesmiles@example.com


Thursday, May 16, 2019

Redirect a page with variable in PHP with POST method

When a form submit I want to redirect to another page with some variable in the POST method.

We can't redirect page with post values in PHP directly.
In that case, there are several other options we can use. Here is one of them.


If we can use javascript as most sites are doing.


 we can do it as below.

<form name='fr' action='redirectpage.php' method='POST'>
      <input type='hidden' name='var1' value='val1'>
      <input type='hidden' name='var2' value='val2'>
</form>

<script type='text/javascript'>
     document.fr.submit();
</script>

This will post all variables to redirectpage.php.

I hope this will help you.

Thursday, May 2, 2019

Dynamic PHP variable


PHP allows you to use dynamic variable names, called variable variables. You can name a variable with the value stored in another variable. That is, one variable contains the name of another variable.


$Bangladesh = 147570;
$dhaka = 11500;
$cityname = "Bangladesh";
echo "The size of $cityname is ${$cityname}";
$cityname = "dhaka";
echo "The size of $cityname is ${$cityname}";
The output from this code is
The size of Bangladesh is 147570
The size of dhaka is 11500

Ref: https://www.dummies.com/programming/php/how-to-use-php-variable-variables/

Saturday, January 19, 2019

Install phpmyamin in Raspberry Pi

First, install MySQL which is a free opensource database system.

sudo apt install mysql-server php-mysql
The PHPMyAdmin installation is pretty quick and easy, we simply have to use the packet manager with this command :
sudo apt install phpmyadmin
but here we're going to install phpmyadmin in a another way. go to phpmyadmin website then download as zip. unzip the copy to var/www/html path.

After install mysql go cmd to set new password for root
sudo mysql_secure_installation   
 [to set new pass type none then entry new password]

To login mysql go cmd and type
sudo mysql -p -u root 
Then add new super user to access phpmyadmin
set password for user esteemsoft
CREATE USER ‘esteemsoft’@’%’ IDENTIFIED BY ‘password’ 
GRANT ALL PRIVILEGES ON *.* TO  ‘esteemsoft’@’%’ WITH GRANT OPTION;
Done!!! now go to localhost/phpmyadmin and enjoy....

Thursday, August 9, 2018

Handling undefined & null parameters in JavaScript

Here with a given example is enough to make it understand


 function foo(DivID, color) {  
   if (!color) { // the correct test here should be 'typeof color == "undefined"'  
     color = "green";  
   }  
   DivID.style.backgroundColor = color;  
 }  
 foo(div_color, "red"); //set the background color to red  
 foo(div_color); //set the background color to the default green  
 foo(div_color, "");​ //remove the background color !This will fail!  

Friday, May 25, 2018

Load multiple javascript/js files from one javascript file

Sometimes there are several javascript files used to include in a project. but js file could be a small file. It's good practice if we use less file in a web project. So, in that case, we can load multiple javascript/js files from one javascript file.

Example
<footer>
<script type="text/javascript" src="jsfile1.js"></script>
<script type="text/javascript" src="jsfile2.js"></script>
<script type="text/javascript" src="jsfile3.js"></script>
</footer>
We need to make a function example function name include also this function will use that single js file where we can call other js files.
Code for the single js file (single.js)
function include(jspath) {
    document.write('<script type="text/javascript" src="'+jspath+'"><\/script>');
}

include("jsfile1.js");include("jsfile2.js");include("jsfile3.js");
Now we can call just one single js file where other 3 js file already include
<footer>
<script type="text/javascript" src="single.js"></script>
</footer>

One important thing to remember that if we need to use the function or this code to combine js file
document.write('<script type="text/javascript" src="jsfilepath.js"><\/script>');

some js file may not work if we use this jquery method.
$.getScript("includes/tableExport/jspdf/jspdf.js", function(){});



Sunday, May 20, 2018

MySQL Performance Tuning

When MySQL becomes too slow (or too unstable), temptation usually is to tweak the MySQL configuration file. Indeed, it’s a good place to start. But if you ever looked at the available configuration options, you know things can get messy – MySQL now has over 450 configuration variables for your consideration, that are not classified in any way, and neither of them is included in the stock my.cnf.

We can setup/change default MySQL setup value by two methods.
1. using MySQL cmd / phpmyadmin which is the temporary solution. after restarting MySQL server all setup will change to the default value.

2. using the changing mysql config file name my.cnf  vis ssh
To edit the MySQL settings with my.cnf file type the following command. 

nano /etc/my.cnf

Find the settings you wish to edit. Say, for example, you want to increase the max_connections limit for MySQL server. Locate max_connections and set your desired value.

max_connections=20

To increase the max_connectionsto 30 change it to the following.

max_connections=30

Enter Ctrl + O to save the settings and Ctrl + X to exit. Restart the MySQL server by typing the following command.

service mysql restart

What does it mean the process "Sleep"?

There is a lot of connection seeing sleep. It's not a query waiting for a connection; it's a connection pointer waiting for the timeout to terminate.

It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does. But if it crosse max_connection limit then MySQL will trigger error "Too many connections"

It'll better to kill "sleep" connections. By default connection still alive / stay in task list up to 8 hours


mysqld will timeout database connections based on two server options:
Both are 28,800 seconds (8 hours) by default.
You can set these options in /etc/my.cnf
If your connections are persistent (opened via mysql_pconnect) you could lower these numbers to something reasonable like 600 (10 minutes) or even 60 (1 minute). Or, if your app works just fine, you can leave the default. This is up to you.
You must set these as follows in my.cnf (takes effect after mysqld is restarted):
[mysqld]
interactive_timeout=180
wait_timeout=180
We can check from directly MySQL using this command
show variables like "interactive_timeout"
If you do not want to restart MySQL, then run these two commands:
SET GLOBAL interactive_timeout = 180;
SET GLOBAL wait_timeout = 180;
This will not close the connections already open. This will cause new connections to close in 180 seconds automatically.





Total Pageviews