PHP – A Weblog of Priyank Maniar https://priyank.rocks Articles on web development & mobile app development Sun, 19 Mar 2023 08:47:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 PHP : require_once | Core function https://priyank.rocks/php-require_once-core-function/ Sun, 19 Mar 2023 08:47:16 +0000 https://priyank.rocks/?p=9421 I just want to log one pitfall here that I believe every developer must know.

require_once if we have it across different folders which include the same file, then we expect that it should only load once. But you might get an error saying cannot redeclare the trait again or the trait is already defined.

The key thing here is that require_once requires a full absolute path, then you can expect require_once to load it only once. I had files access from different folder levels and this solved the issue for me.

Maybe for files required at the same folder level, this may not be an issue, haven’t tested that yet.

]]>
PHP Objects https://priyank.rocks/php-objects/ Wed, 14 Sep 2022 10:18:18 +0000 https://priyank.rocks/?p=9129 How do we create a generic object in PHP?

1
2
3
4
5
6
7
8
#1 Standard Way
$obj = new stdClass();

#2 Typecaste way
$obj = (object)[];

#3 An anonymous class
$obj = new class{};
]]>
The command “migrate:fresh –seed” does not exist. https://priyank.rocks/the-command-migratefresh-seed-does-not-exist/ Mon, 28 Feb 2022 18:11:31 +0000 https://priyank.rocks/?p=8932 The command was not running on the production server. The fix was easy but in two steps:

Introduce force since we are running into production

\Artisan::call('migrate:fresh', ['--force' => true]);

Split the command into two. So.

\Artisan::call('migrate:fresh', ['--force' => true]);
\Artisan::call('db:seed', ['--force' => true]);
]]>
PHP: Try/Catch https://priyank.rocks/php-try-catch/ Thu, 02 Sep 2021 12:18:23 +0000 https://priyank.rocks/?p=8424 Does the try-catch block continue execution after the catch?

1
2
3
4
5
6
7
try {
    throw new Exception (1);
} catch (Exception $exception) {
    echo "gotcha!";
}

echo "what about me?";

The answer is Yes, it does.

]]>
How to upgrade PHP version from 7.2 to 7.3 on a Ubuntu Server? https://priyank.rocks/how-to-upgrade-php-version-from-7-2-to-7-3-on-a-ubuntu-server/ Wed, 07 Jul 2021 09:00:52 +0000 https://priyank.rocks/?p=7983 The following are the commands I ran in order to upgrade PHP version from 7.2 to 7.3 for a laravel project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Run commands one by one. Do not paste whole chunk.

sudo apt-get install software-properties-common;
sudo add-apt-repository ppa:ondrej/php;
sudo apt-get update;
sudo apt-get upgrade;
sudo apt-get install -y php7.3;

# Instantly php version changes
php -v;

# For a Laravel Project

sudo apt-get install php7.3-zip -y;
sudo apt-get install php7.3-gd -y;
sudo apt-get install php7.3-xml -y;
sudo apt-get install php7.3-curl -y;
sudo apt-get install php-mbstring -y;
sudo apt-get install php7.3-mbstring -y;
sudo apt install php7.3-mysql -y;

# do this too - https://stackoverflow.com/a/35240511/6275860
# Restart is not needed but we should still do it to see all is well.

sudo service apache2 restart;

sudo update-alternatives --config php;

# We are good to test now the websites.

# If required
sudo a2dismod php7.2 // disable
sudo a2dismod php8.0 // disable
sudo a2enmod php7.3;

sudo apt-get install libapache2-mod-php;

sudo update-alternatives --config php;
sudo update-alternatives --config phar;
sudo update-alternatives --config phar.phar;


# https://stackoverflow.com/a/46296973/6275860

# if nothig works, try this not sure though
sudo a2enmod mpm_prefork;

The process should be same for the other upgrades as well such as: 7.0 to 7.4, 7.2 to 7.4 etc.

]]>
Does a variable inside the loop retain its value in PHP? https://priyank.rocks/does-a-variable-inside-the-loop-retain-its-value-in-php/ Mon, 31 May 2021 12:13:33 +0000 https://priyank.rocks/?p=7801 The following is the code to put this to test.

1
2
3
4
5
6
7
8
9
10
11
12
$something = true;

$array = array('a', 'b', 'c', 'd');

foreach ($array as $a) {

    var_dump($a);
    var_dump($something);

    $something = false;

}

Here’s the output.


1
2
3
4
5
6
7
8
string(1) "a"
bool(true)
string(1) "b"
bool(false)
string(1) "c"
bool(false)
string(1) "d"
bool(false)
]]>
Suspicious PHP Variable / Show Hidden / Invisible Variable Text PHP https://priyank.rocks/suspicious-php-variable-show-hidden-variable-text-php/ Mon, 18 May 2020 20:37:26 +0000 https://priyank.rocks/?p=6622 I encountered a very weird thing lately. strtotime() was not working. If we accept the input from the DB (WordPress) it wasn’t working however if we type in the hardcoded string it was working.

The string was exactly the same. It had only one weird thing.

The string echo from DB with var_dump() showed one character extra than what it should.

This was my only clue.

I came across a function that displays the variable in hex which we can then decode online and see the real output and there’s where I found the culprit.

See that weird character? It was not visible when we echo string in the browser.

The site where I decoded: https://www.convertstring.com/EncodeDecode/HexDecode

How did I encode?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Source: https://stackoverflow.com/questions/1057572/how-can-i-get-a-hex-dump-of-a-string-in-php
function hex_dump($data, $newline="\n")
{
  static $from = '';
  static $to = '';

  static $width = 16; # number of bytes per line

  static $pad = '.'; # padding for non-visible characters

  if ($from==='')
  {
    for ($i=0; $i<=0xFF; $i++)
    {
      $from .= chr($i);
      $to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
    }
  }

  $hex = str_split(bin2hex($data), $width*2);
  $chars = str_split(strtr($data, $from, $to), $width);

  $offset = 0;
  foreach ($hex as $i => $line)
  {
    echo sprintf('%6X',$offset).' : '.implode(' ', str_split($line,2)) . ' [' . $chars[$i] . ']' . $newline;
    $offset += $width;
  }
}

Final solution was to type in the string again in to DB and then it worked perfectly.

What could have caused this?

I copied the string from the admin panel ACF both the items were in same page, pasted from one to other and I encountered this issue.

]]>
PHP Converting &039; code to a single quote https://priyank.rocks/php-converting-code-to-a-single-quote/ Thu, 27 Feb 2020 06:27:37 +0000 http://priyank.rocks/?p=6219
1
htmlspecialchars_decode($text , ENT_QUOTES);
]]>
PHPDocumentor https://priyank.rocks/phpdocumentor/ Sun, 21 Jul 2019 14:01:44 +0000 http://priyank.rocks/?p=507 Download the PHAR from their website. This is the easiest method to start with and works perfectly.


1
php ~/phpDocumentor.phar -d . -t docs

I found an excellent configuration file that you just need to place and it will make life easier.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
&lt;?xml version="1.0" encoding="UTF-8" ?>
&lt;phpdoc>
    &lt;title>App Plugins Documentations&lt;/title>
    &lt;parser>
        &lt;target>reference/docs&lt;/target>
    &lt;/parser>
    &lt;transformer>
        &lt;target>reference/docs&lt;/target>
    &lt;/transformer>
    &lt;files>
        &lt;directory>.&lt;/directory> &lt;!-- Scan and parse all the php files except those found in the paths below -->
        &lt;ignore>assets/*&lt;/ignore>
        &lt;ignore>includes/gm-virtual-pages/*&lt;/ignore>
        &lt;ignore>includes/app_virtual_pages/*&lt;/ignore>
        &lt;ignore>includes/third-party/*&lt;/ignore>
        &lt;ignore>vendor/*&lt;/ignore>
        &lt;ignore>reference/docs/*&lt;/ignore>
        &lt;ignore>storage/*&lt;/ignore>
        &lt;ignore>views/*&lt;/ignore>
        &lt;ignore>index.php&lt;/ignore> &lt;!-- Ignore all the index.php files -->
    &lt;/files>
&lt;/phpdoc>

Ignoring vendor directory should be the first step to start with.

]]>
PHP: function number_format issues and solution https://priyank.rocks/php-function-number_format-issues-and-solution/ Sat, 23 Mar 2019 05:12:32 +0000 http://priyank.rocks/?p=410 We have bcmath too! Don’t forget about that.

Note: money_format is deprecated now.

Following is not really an issue but we could run into a trap if we don’t be careful about it. Bottom line is to understand that number_format returns string and when any arithmetic operation is performed to it, we could end up with huge problems.

We can use round but round for 45.20 will give 45.2. Even when we asked for 2 decimals. money_format returns string as well. I guess it will be best to use round for calculations and for displaying numbers use number_format or money_format.

The thing with number_format besides the string issue is, client could ask for $15 instead of $15.00. However number_format will stick to the the decimals as instructed.

A solution to the zeroes could be a filter.

1
2
3
4
5
Vue.filter('removeZeroes', function (value) {
    if (value) {
        return value.replace('.00', '');
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$a = number_format(100000, 2);
$b = number_format(100000, 2);

$c = $a + $b; // 200

// TODO: FIXME: REMOVE THIS
var_dump($c);

$a = round(100000, 2);
$b = round(100000, 2);

$c = $a + $b; // float(200000)

// TODO: FIXME: REMOVE THIS
var_dump($c);


$c = 45.1261423;
echo money_format('%i', $c); // 45.13


setlocale(LC_MONETARY, 'en_CA');

var_dump(money_format('%i', $c)); // string(13) "CAD200,000.00"

The other solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace App\Libraries;

class NumberFunctions
{

    public static function is_decimal($val)
    {
        return is_numeric($val) &amp;&amp; floor($val) != $val;
    }

    public static function handle_money_display($amount, $currency = "$")
    {
        if (self::is_decimal($amount)) {
            return $currency . number_format($amount, 2);
        } else {
            return $currency . number_format($amount, 0);
        }

    }

}
]]>