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 migrate Customers from Magento2 to WordPress?

Lets break it into 2 parts:

a. Migrate Customer data
b. Migrate Customer Passwords

1) Migrate Customer Data from Magento2 to WordPress

This is rather easy to be honest, there are several plugins for importing data from CSV and then mapping the CSV fields.

My recommended plugin is Customer/Order/Coupon CSV Import Suite by SkyVerge

It basically does everything from customer email to customer address data. It also provides column mapping and custom attribute import for all users. Also comes with multiple configuration options.

Best Free Alternative is https://wordpress.org/plugins/import-users-from-csv-with-meta
But in this one, you can not import magento2 passwords as of v 1.15.0.1
I will update about the solution very soon. So as of now only paid option is there.

2) Migrate Customer Password from Magento2 to WordPress

This wordpress plugin checks and updates passwords of users migrated from Magento2 to WordPress
Plugin Link: https://github.com/harshvardhanmalpani/migrate-password-from-magento2-to-wordpress

Requirements:

  1. user_pass column will have this kind data from Magento2 dcbdc524f215fd054502dcad5a23a702ec029c02ff8d7051d049f76e29927f8b:C8yVqeuPfkHWvkmipx0iKLPtOUGETpLL:1
  2. usermeta table must have a meta_key “migrated_cs” for this user, meta_value can be anything positive
  3. This plugin file password-migrator.php should be in wp-content/plugins and must be an active plugin

What is does?

For new wordpress based users which dont have anything to do with magento2, it doesnt do anything

For all migrated users (those have the key “migrated_cs”), this plugin checks if input password matches old password from magento2 or not, if matched, it clears the key migrated_cs and updates the password using wordpress’ algorithm ; else results false.

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);
}
}
?>

Sort keys of an array based on order of values in another array – PHP

$a=array(56,7,6,8,5,34);
$b=array(
array(6,"34er34",44),
array(8,"34d34",44),
array(7,"343th4",44),
array(34,"343d4",44),
array(56,"3434",44),
array(5,"343gh4",44));
$d=array_column($b,0);
var_dump($d);
$g=[];
foreach($a as $c)
{
$f=array_search($c,$d);
if($f!==false)
$g[]=$b[$f];
}
var_export($g);

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

Funny php bug due to hashing and is_numeric

So I was working on an automation project and was testing the api to upload entitites.

I used get parameters to send data and wrote a wrapper on server to process that. I used hashes (part of hashes to be precise) to identify the requester instead of using real names.

some name came up with hash

12200e7973d0eecd8d75da83e816783496e440e22210ee72cb5cf37f7989a8ff

I was using first 10 characters of this has which happen to be

12200e7973

If you notice, only alphabet is “e” and all others are digits.
But at the same time this is a number in scientific notation
just the way 1e3 is 1000 because of exponentiation involved. My partial hash string was also being converted and was close to infinity.

My api at the backend was checking the given parameter with is_numeric and in this case, my parameter “12200e7973is 100% numeric (EVEN IF I WAS STORING IT AS A STRING).
Hence my script was failing to save correct data and a major column was left empty in the tables.

This was another blunder by me at programming, but you can easily fix it if you use is_int instead of is_numeric because it would fail type checking via is_int.

Of course I had to edit some code with explicit type casting for other types of api calls which were using IDs instead of hashes to identify the users.

Example code: (This is Not the exact code, not recommended for production usage)

// API ENDPOINT
$user=isset($_REQUEST['user']) ?? $_REQUEST['user'] : 1;
// calling the function with string $user
abc ("xyz",$user);
// Normal code:
$user=$this->getLoggedInUser();
$userid=(int)$user; //explicit casting
//calling the same function with int val
abc("mnop",$userid);

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 fix Undefined class constant ‘ARRAY_AS_PROPS’ Fatal Error?

I received this error “Fatal Error: Uncaught error in Undefined class constant ‘ARRAY_AS_PROPS'”
This issue is not related to PHP if you have 7.0 and above, it is zend framework’s module zend-http wrapper which is affected if Apache module is not present

File responsible: zendframework\zend-http\src\Header\Cookie.php:75

public function __construct(array $array = [])
{
parent::__construct($array, ArrayObject::ARRAY_AS_PROPS);
}

Solution

Do check enabled modules for Apache, I found out that mod_expires was not enabled. So I edited httpd.conf and enabled mod_expires

I also enabled Zend Opcache in php.ini to make it run smooth on multiple pageloads.

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