9 Advanced PHP Hacks That Only Expert PHP Developers Know About

Sameer, one of our PHP developers, read a question on the PHP forum where a novice developer had asked advanced PHP tips to learn PHP web development.

To answer the question, Sameer has listed 9 useful advanced PHP tips and techniques that can be used to enhance and learn PHP code.

We thought to share it here on the blog as well.

Are you ready to explore it?

2

 

Level Up Your PHP Skills with These 9 PHP Techniques

  1. Php background process code

    Index.php

        $url = 'backgroundScript.php';
        $postfields = ['company_name' => "spaceo", 'developer_name' => "sameer"];
        
        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_NOSIGNAL => 1,
            CURLOPT_TIMEOUT_MS => 50,
            CURLOPT_VERBOSE => 1,
            CURLOPT_POSTFIELDS => http_build_query($postfields),
            CURLOPT_HEADER => 1,
            CURLOPT_FRESH_CONNECT => true,
        ));
        
        curl_exec($ch);
        curl_close($ch);
    Copy to Clipboard

    backgroundScript.php

        set_time_limit(0);
        header("Connection: close");
        ignore_user_abort(true);
        
        // write your background execute code
    Copy to Clipboard

     

  2. Delete whole folder with it’s content

        $dir = 'put your folder url path here'; // ex: '../uploads/media/1
    
        if (is_dir($dir)) {
            array_map('unlink', glob($dir . '/*'));
            rmdir($dir);
        }
    Copy to Clipboard

     

  3. Print debug log in particular location

    index.php

        require_once('errorLog.php');
        cloud_error_log('put your error result here'); // error result like text, array etc.
    Copy to Clipboard

    errorLog.php

        function cloud_error_log($errordata) {
            $handle = fopen('errorLogFile.txt', 'a+');
            $logtext = "******************" . date('d-m-Y h:i:s') . "******************\n\n";
            $logtext .= print_r($errordata, true);
            $logtext .= "\n\n**********************************************************\n\n";
            $errorlog = fwrite($handle, $logtext);
            fclose($handle);
            chmod('errorLogFile.txt', 0777);
            return true;
        }
    Copy to Clipboard

     

  4. Want to Develop a Web Application?

    Want to validate your app idea or consult with an expert? Get a free consultation now!

    Cta Image
  5. Getting list of dates from day name of particular year and month

        function getMonthDatefromDay($month, $year, $searchdayname) {
            $start_date = "01-" . $month . "-" . $year;
            $start_time = strtotime($start_date);
            $end_time = strtotime("+1 month", $start_time);
            for ($i = $start_time; $i < $end_time; $i += 86400) {
                if (strtolower(date('D', $i)) == $searchdayname) {
                    $list[] = date('Y-m-d', $i);
                }
            }
            return $list;
        }
        
        print_r(getMonthDatefromDay(09, 2016, 'mon'));
    Copy to Clipboard

     

  6. Encrypt and Decrypt password

    function encrypt_decrypt($string, $action = 'encrypt') {
        $encrypt_method = "AES-256-CBC";
        $secret_key = 'AA74CDCC2BBRT935136HH7B63C27'; // user define private key
        $secret_iv = '5fgf5HJ5g27'; // user define secret key
        $key = hash('sha256', $secret_key);
        $iv = substr(hash('sha256', $secret_iv), 0, 16); // sha256 is hash_hmac_algo
    
        if ($action == 'encrypt') {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if ($action == 'decrypt') {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }   
    
        return $output;
    }
    
    echo "Your Encrypted password is => " . $pwd = encrypt_decrypt('spaceo', 'encrypt');
    echo '<br/>';
    echo "Your Decrypted password is => " . encrypt_decrypt($pwd, 'decrypt');
    Copy to Clipboard

     

  7. Create random Unique Key

    echo md5(uniqid(time()));
    Copy to Clipboard
  8. Display users with suffix. (ex: Facebook users like 10K)

    function formatWithSuffix($input)
    {
        $suffixes = array('', 'K', 'M', 'B', 'T');
        $suffixIndex = 0;
        while(abs($input) >= 1000 && $suffixIndex < sizeof($suffixes)) {
            $suffixIndex++;
            $input /= 1000;
        }
        return ($input > 0 ? floor($input * 1000) / 1000 : ceil($input * 1000) / 1000) . $suffixes[$suffixIndex];
    }
    echo formatWithSuffix('10000');
    Copy to Clipboard

     

  9. Multiple array sorting

    $data = array[
        ['id' => 1, 'name' => 'sameer'],
        ['id' => 2, 'name' => 'yagnesh'],
        ['id' => 3, 'name' => 'chirag']
    ];
    foreach ($data as $key => $row) {
        $id[$key] = $row['id'];
        $name[$key] = $row['name'];
    }
    array_multisort($id, SORT_DESC, $name, SORT_ASC, $data);
    print_r($id);
    print_r($name);
    Copy to Clipboard

     

  10. Get size of the specified URL or file

    echo filesize('test.txt');
    Copy to Clipboard

     

Plus, bonus tip:

Never use for($i=0; $i<count($arrayName); $i++){…} instead of this use $cnt = count($arrayName); for($i=0; $i<$cnt; $i++){…}.

In the above example, the first method will call count function on each iteration for loop, while in the second iteration, count function is being called only once.

Apart from these techniques you can become a better PHP developer by reading our post on useful PHP development tools for web developers.

Want to Become a PHP Expert?

Finally, mastering advanced PHP hacks is critical for anyone learning PHP and aspiring to work in the PHP development industry. You can use these hacks to add impressive functionality to your PHP projects, such as creating an event calendar with PHP. By constantly honing your PHP skills, you can become an invaluable member of any team and propel your PHP development career to new heights.

We can assist you if you are planning to build a PHP project and need to consult with experts. Our custom PHP development company has extensive experience completing a variety of PHP projects using various frameworks. We have a team of expert PHP programmers for hire who can assist you in realising your ideas and developing high-quality web applications that meet your specific requirements. Contact us today.

Bhaval Patel

Written by

Bhaval Patel is a Director (Operations) at Space-O Technologies. He has 20+ years of experience helping startups and enterprises with custom software solutions to drive maximum results. Under his leadership, Space-O has won the 8th GESIA annual award for being the best mobile app development company. So far, he has validated more than 300 app ideas and successfully delivered 100 custom solutions using the technologies, such as Swift, Kotlin, React Native, Flutter, PHP, RoR, IoT, AI, NFC, AR/VR, Blockchain, NFT, and more.