Sample .htaccess for Laravel with PHP FPM

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

#    RewriteEngine On
#    RewriteCond %{HTTP:Authorization} ^(Bearer\ )(.*)$ [NC]
#    RewriteRule ^(.*) $1?access_token=%2 [QSA]
#Header set Access-Control-Allow-Origin "*"
#Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
#Header set Access-Control-Allow-Headers "Content-Type, Authorization"
<IfModule mod_rewrite.c>

<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://kprep.api.ozandac.com/$1 [R,L]
RewriteEngine On
# Prevent direct access to the "public" folder - redirect to root
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /public/
RewriteRule ^public/(.*) /$1 [R=302,L]

# Redirect Trailing Slashes If Not A Folder...
# - but look for the file in the "public" folder
# (ensure we are not already in the "public" folder)
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{DOCUMENT_ROOT}/public/$1 !-d
RewriteRule ^(.*)/$ /$1 [R=302,L]

# Rewrite "everything" to the "public" subdirectory if not already
# This ignores existing files/dirs in the document root
RewriteCond %{REQUEST_URI} ^/(.*)
RewriteRule !^public/ public/%1

# Handle Front Controller... (as before)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Gravityforms limit submission – once for user, unlimited for guest

	public function context() {

		// rule targets specific user, if this user is different we don't need to test the rule
		if ( $this->user_id != 'all' ) {
			if ( $this->user_id != get_current_user_id() ) {
				return false;
			}
			
		}
		if($this->user_id == "all")
		{
		    if(get_current_user_id()===0)
			{
			    return false;
			}
		}

		return true;
	}

File: gp-limit-submissions/includes/GPLS_Rule_User.php

Plugin: https://gravitywiz.com/documentation/gravity-forms-limit-submissions

How to get Gravity forms entry value by label?

function harsh_get_value_by_label( $form, $entry, $label ) {
	foreach ( $form['fields'] as $field ) {
		$lead_key = $field->label;
		
		if ( strtolower( $lead_key ) == strtolower( $label ) ) {
			return $entry[ $field->id ];
		}
		if($field->inputs != null and count($field->inputs))
		{
			foreach($field->inputs as $children)
			{
				$subLeadKey = $children["label"];
				if ( strtolower( $subLeadKey ) == strtolower( $label ) ) 
				{
					return $entry[ $children["id"] ];
				}
			}
		}
	}
	return false;
}

PHP caveats – int/float type conversion

The following code checks various scenarios in which inbuilt functions like intval, floatval, is_numeric, is_float and filter_var would result for several different types of values. Feel free to run in your local, leave comments if I can make the results more interesting with some more functions.

https://gist.github.com/harshvardhanmalpani/8dd0222e4821d0e495532abe9007fef1

Output / Results

Test Value 1: (string)true
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 2: (boolean)1
Integer converted Value: 1
Float converted Value: 1
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 3: (boolean)
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 4: (string)false
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 5: (integer)0
Integer converted Value: 0
Float converted Value: 0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 6: (double)-0
Integer converted Value: 0
Float converted Value: -0
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 7: (integer)0
Integer converted Value: 0
Float converted Value: 0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 8: (string)-0
Integer converted Value: 0
Float converted Value: -0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 9: (string)+0
Integer converted Value: 0
Float converted Value: 0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 10: (string)-0.0
Integer converted Value: 0
Float converted Value: -0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 11: (string)+0.0
Integer converted Value: 0
Float converted Value: 0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 12: (string)0
Integer converted Value: 0
Float converted Value: 0
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 13: (string)0w
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 14: (string)0.0t
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 15: (string)0.1
Integer converted Value: 0
Float converted Value: 0.1
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 16: (double)0.1
Integer converted Value: 0
Float converted Value: 0.1
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 17: (integer)1
Integer converted Value: 1
Float converted Value: 1
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 18: (string)1
Integer converted Value: 1
Float converted Value: 1
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 19: (double)10000
Integer converted Value: 10000
Float converted Value: 10000
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 20: (string)2e
Integer converted Value: 2
Float converted Value: 2
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 21: (double)20000
Integer converted Value: 20000
Float converted Value: 20000
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 22: (string)2e4
Integer converted Value: 20000
Float converted Value: 20000
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 23: (double)1337
Integer converted Value: 1337
Float converted Value: 1337
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 24: (string)1e3
Integer converted Value: 1000
Float converted Value: 1000
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 25: (double)10
Integer converted Value: 10
Float converted Value: 10
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 26: (double)1.3
Integer converted Value: 1
Float converted Value: 1.3
✅ Valid Integer as per is_numeric
✅ Valid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 27: (string)1.4
Integer converted Value: 1
Float converted Value: 1.4
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 28: (string)1t
Integer converted Value: 1
Float converted Value: 1
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 29: (string)1.5n
Integer converted Value: 1
Float converted Value: 1.5
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 30: (integer)26
Integer converted Value: 26
Float converted Value: 26
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 31: (string)0x539
Integer converted Value: 0
Float converted Value: 0
❌ Invalid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
❌ Invalid Float as per filter validate
----
Test Value 32: (integer)34
Integer converted Value: 34
Float converted Value: 34
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 33: (string)042
Integer converted Value: 42
Float converted Value: 42
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
❌ Invalid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 34: (integer)42
Integer converted Value: 42
Float converted Value: 42
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 35: (integer)-42
Integer converted Value: -42
Float converted Value: -42
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 36: (string)+42
Integer converted Value: 42
Float converted Value: 42
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----
Test Value 37: (string)-42
Integer converted Value: -42
Float converted Value: -42
✅ Valid Integer as per is_numeric
❌ Invalid Float as per is_float
✅ Valid Integer as per filter validate
✅ Valid Float as per filter validate
----

How to batch edit multiple images to make square sized pictures with original image in center using php imagejpeg?

<?php
// WORKS FOR JPEG IMAGES ONLY. FOR PNG, change function names
// also create a folder named "out" in the $datadir folder
///only 4 lines to be edited
//1. dir in which your image files are present
$datadir="J:/dgcert/";
//2. Expected min. Width of the output file
$_outw=840;
//3. Expected min. Height of the output file
$_outh=840;
//4. output folder (inside datadir)
$outfolder= '/out/';
//5. force final size -- -- If set to 1/true then line 2 and 3 will become max sizes of output image
// TO BE DONE IN FUTURE . does not work as of now
$forcesize=0;
////// no more edits needed
$files=array_diff(scandir($datadir),array(".",".."));
foreach ($files as $file)
{
	if(is_file($datadir.'/'.$file)){		
$outw=$_outw;
$outh=$_outh;
$mugl_im= imagecreatefromjpeg($datadir.$file);
list($thiswidth, $thisheight)= getimagesize($datadir.$file);
if($outw<$thiswidth) $outw=$thiswidth;
if($outh<$thisheight) $outh=$thisheight;
if($outw<$outh)$outw=$outh;
if($outh<$outw)$outh=$outw;
//echo $width . $height;exit;
$thumb = imagecreatetruecolor($outw, $outh);
//white color rgb
$bg = imagecolorallocate ( $thumb, 255, 255, 255 );
imagefilledrectangle($thumb,0,0,$outw,$outh,$bg);
imagecopyresized($thumb,$mugl_im,ceil(($outw-$thiswidth)/2),ceil(($outh-$thisheight)/2),0,0,$thiswidth,$thisheight,$thiswidth,$thisheight);

imagejpeg($thumb,$datadir.$outfolder.$file);
imagedestroy($thumb);
imagedestroy($mugl_im);
	}
}

?>

How to filter and validate pincode in Indian woocommerce?

By default, Woocommerce only validates ZIP code of few countries only. Woocommerce stores in India, are thus invalidated in case of PINCODE inputs from customers. Here is how you can enable checking of pincode for India woocommerce:

Put the following code in your custom function file or child theme functions.php

add_filter('woocommerce_validate_postcode','validate_indian_postcode',10,3);

function validate_indian_postcode($valid, $postcode, $country){
	if($country=="IN")
			$valid = (bool) preg_match( '/^([0-9]{6})$/', $postcode );
  // checks your $postcode, if valid $valid will be true because of preg_match else false
  return $valid;
}

Reference:

https://github.com/woocommerce/woocommerce/blob/ef0f527b40dba539e982efff26211fa577a24cf9/includes/class-wc-validation.php#L44

How to reverse the ids in a mysql table column without breaking primary key constraint?

Let me explain the problem scenario: Let us assume we have a table with 4 columns in it out of which 1 is PRIMARY column and rest 3 contain some data.

What we want to do is to reverse the primary key IDs for that data keeping the rest of data intact. It is like shifting the first row to end and moving last row to starting.

Initial Data

idnameemailanything
1jacobwhateverhow to reverse
3nathanwhosoeverisnathanids in mysql table column
4jagmohanidontknowjagmohanwithout breaking
8monicaiamsexyprimary key constraint
9batmanidontexistinrealworldi am batman

Data after update

idnameemailanything
9jacobwhatever how to reverse
8nathanwhosoeverisnathan ids in mysql table column
4jagmohanidontknowjagmohan without breaking
3monicaiamsexy primary key constraint
1batman idontexistinrealworld i am batman

Dude, you are just reversing the column, what is so tough in this?

So, this seems simple to reverse an array if isolated by key “id“. But you have to understand that this column is the primary key. So if you run a command to change id for “jacob” to “9“. It will give you error: “Duplicate entry for id 9

So here is my proposed solution, I start with pair of first and last row and then swap them. Then swap second and second last row. and So on…

If total rows are odd, we will be left with 1 row which does not need correction because it will already be the middle row.

If total rows are even, we would swap middle two rows too.

Here is my solution in PHP

$possible_group_id="3";
$ai=12720; //can be any high int which does not exist in column `id` yet
$q="select id,email from table_name where `possible_group_id`=$possible_group_id order by id asc";
$r=mysqli_query($f,$q);
$row_collection=[];
$ct=[];
while($row=mysqli_fetch_row($r))
{
    $row_collection[]=$row;
    $ct[]=$row[0];
}
$pt=array_reverse($ct);
$size=count($row_collection);
for($i=0;$i<$size;$i++)
{
    $row_collection[$i][2]=$pt[$i];
}
echo "start transaction;<br>";
foreach($row_collection as $k=>$v)
{    
    if($k < floor($size/2)){
    echo 'UPDATE `table_name` SET `id`='.$ai.' WHERE `email`="'.$row_collection[$size-$k-1][1].'";<br>';
    echo 'UPDATE `table_name` SET `id`='.$v[2].' WHERE `email`="'.$v[1].'";<br>';
    echo 'UPDATE `table_name` SET `id`='.$row_collection[$k][0].' WHERE `email`="'.$row_collection[$size-$k-1][1].'";<br>';}
    else break;
}
echo "commit;<br>";

It would output this:

start transaction;
UPDATE `table_name` SET `id`=12720 WHERE `email`="idontexistinrealworld ";
UPDATE `table_name` SET `id`=9 WHERE `email`="whatever";
UPDATE `table_name` SET `id`=1 WHERE `email`="idontexistinrealworld ";
UPDATE `table_name` SET `id`=12720 WHERE `email`="iamsexy";
UPDATE `table_name` SET `id`=8 WHERE `email`="whosoeverisnathan";
UPDATE `table_name` SET `id`=3 WHERE `email`="iamsexy";
commit;

How to transpose an array in PHP with irregular subarray size?

    function transposeCsvData($data)
    {
	    $ct=0;
	    foreach($data as $key => $val)
        {
	        //echo count($val);
		    if($ct< count($val))
                $ct=count($val);
		    }
		//echo $ct;
	    $blank=array_fill(0,$ct,array_fill(0,count($data),null));
	    //print_r($blank);
	
	    $retData = array();
        foreach ($data as $row => $columns)
        {
            foreach ($columns as $row2 => $column2) 
            {
                $retData[$row2][$row] = $column2;
                }
            }
	    $final=array();
	    foreach($retData as $k=>$aval)
	    { 
            $final[]=array_replace($blank[$k], $aval);
           }
        return $final;
        }

Test Code

$a[]=array("name","john","sam","patrick");
$a[]=array("color","orange","green");
$a[]=array("bikes","suzuki","audi","mercedes","bmw","volks","rover");
$a[]=array("techgiants","samsung","amazon");

print_r(transposeCsvData($a));

Output

Array
(
    [0] => Array
        (
            [0] => name
            [1] => color
            [2] => bikes
            [3] => techgiants
        )

    [1] => Array
        (
            [0] => john
            [1] => orange
            [2] => suzuki
            [3] => samsung
        )

    [2] => Array
        (
            [0] => sam
            [1] => green
            [2] => audi
            [3] => amazon
        )

    [3] => Array
        (
            [0] => patrick
            [1] => 
            [2] => mercedes
            [3] => 
        )

    [4] => Array
        (
            [0] => 
            [1] => 
            [2] => bmw
            [3] => 
        )

    [5] => Array
        (
            [0] => 
            [1] => 
            [2] => volks
            [3] => 
        )

    [6] => Array
        (
            [0] => 
            [1] => 
            [2] => rover
            [3] => 
        )

)

How to fix Composer should be invoked via the CLI version of PHP, not the cgi-fcgi SAPI error in SSH?

Put this in your bash profile and run source ~/.bashrc

alias composer="/opt/cpanel/ea-php71/root/usr/bin/php /opt/cpanel/composer/bin/composer"

As Composer is now available via WHM you can use this to find it:

which composer

This returned path “/opt/cpanel/composer/bin/composer” for me. If this returns nothing then disregard the rest of this answer, as Composer is not available to you at system level.

You can now use php-cli to call this with Composer’s absolute path:

php-cli /opt/cpanel/composer/bin/composer install
php-cli /opt/cpanel/composer/bin/composer update
php-cli /opt/cpanel/composer/bin/composer require whatever/example

You may however need to alias php-cli if your system claims this isn’t found. It very much depends how PHP has been deployed on the WHM server. Learn how to fix PHP CLI error. You can do this by adding a user alias to the end of your “.bashrc” or “.bash_profile” file as follows:

alias php-cli=/opt/cpanel/ea-php72/root/usr/bin/php

Replace ea-php72 with the release of PHP you want to use. Submit this as a command in the shell to make it available immediately, otherwise it’ll become available when you open your next Bash session.

If you want to make this available with just composer alone you could create this alias again in “.bashrc”:

alias composer=/opt/cpanel/ea-php72/root/usr/bin/php /opt/cpanel/composer/bin/composer

Reference: https://stackoverflow.com/a/53478183/2229148

Testing Configuration for Paytm Gateway Plugin India

Paytm Payment Gateway Testing Data

Online payment solutions for all your transactions by Paytm Woocommerce Plugin

Download the plugin here: https://github.com/Paytm-Payments/Paytm_Woocommerce_Kit

Enable/Disable
Enable/Disable Enable Paytm Payments.
Title
Title
Paytm
This controls the title which the user sees during checkout.

Description
Description
The best payment gateway provider in India for e-payment through credit card, debit card & netbanking.
This controls the description which the user sees during checkout.

Merchant Identifier
Merchant Identifier
<provided link below>
Merchant Id Provided by Paytm

Secret Key
Secret Key
<provided link below>
Merchant Secret Key Provided by Paytm

Website
Website
WEBSTAGING
Website Name Provided by Paytm

Industry Type
Industry Type
Retail
Industry Type Provided by Paytm

Channel ID
Channel ID
WEB
Channel ID Provided by Paytm

Transaction URL
Transaction URL
https://securegw-stage.paytm.in/theia/processTransaction
Transaction URL Provided by Paytm

Transaction Status Url
Transaction Status Url
https://securegw-stage.paytm.in/merchant-status/getTxnStatus
Transaction Status URL Provided by Paytm

API Keys

You can get your keys here https://dashboard.paytm.com/next/apikeys

API keys are unique credentials issued to every merchant. While MID is used as an identification used for all exchange correspondence, merchant key is used to encrypt every API request to Paytm and decrypt every response from Paytm. Ensure that you keep the merchant key on server side and should not be shared with anyone. In case API keys are compromised, please reach out to our helpdesk to get new API keys.

  • MID (Merchant ID) – Unique identifier issued to every merchant.
  • Merchant Key – This is a unique secret key used for secure encryption of every request. This needs to be kept on server side and should never be shared with anyone.
  • Industry Type ID – This is part of bank and paymode configuration done wrt to an account.
  • Website – This parameter is used to support multiple callback URLs to post the transaction response. Each URL needs to be mapped to a website parameter.

Test API Details are something like this:

  • Test Merchant ID WArHEFXXXXXXXXXXXXXX <–wont work
  • Test Account Secret Key XXXXXXXXOcv1u7P2 <- wont work

Testing Resources / Testing Instruments

Source: https://developer.paytm.com/docs/testing-integration

  • Testing Debit/Credit Card
Card NumberAny Visa or Master Card
Expiration Month & YearAny Future month and Year
CVV123
OTP123123
  • Testing Paytm Wallet Details
Mobile Number77777 77777
PasswordPaytm12345
OTPDoesn’t require 2nd factor authentication489871
  • Testing Netbanking Details
Bank NameAndhra Bank
User IDtest
PasswordTest

Note:
In case you are testing on production environment, use live paymode details to complete the transaction. Once the transaction is successful, you can initiate refund from the dashboard.