Skip to main content

Other useful things I sometime use but always forgot

 🐘Useful PHP functions


One line year array

// will get the past 3 year including current year. eg: 2021,2022,2023

for ($i=-2; $i <= 0 ; $i++) $data['year'][date('Y')+$i] = date('Y')+$i;


Unset attribute in array of array object

$body_list[$count] = array(

            'attr' => array(

                '1' => 'one',

                '2' => 'two',

            ),

            'data' => (object) array(

                '3' => 'three',

                '4' => 'four',

            )

        );


unset($body_list[$count]['data’]->{‘3’}); // will remove attribute ‘three’


Merge/combine array with duplicate keys while preserving the values

// use this inside loops where + wont work between each iteration

foreach ($array2 as $value) $array1[] = $value; 

return $array1;


Divide string in two parts based on certain lengths

private function _divide_string($text, $length) {

        $words          = explode(" ", $text);

        $top_text       = $bottom_text = "";

        $total_length   = 0;


        foreach ($words as $word) {

            $word_length = strlen($word) + 1;

            if ($total_length + $word_length <= $length) {

                $top_text .= $word . " ";

                $total_length += $word_length;

            } else {

                $bottom_text .= $word . " ";

            }

        }


        return [trim($top_text), trim($bottom_text)];

    }


List out all files in a folder into a html table for easy copying into excel/spreadsheets

public function spout_nonsense()

    {

        $string = shell_exec("ls application/controllers | paste -sd ',' -");

        $controller_list = explode(',', $string);


        echo '<html><head></head><body><table><tbody>';

        foreach ($controller_list as $file_name) {

            echo '<tr><td>'.str_replace('.php', '', $file_name).'</td></tr>';

        }

        echo '</tbody></table></body></html>';

    }


Export current db into another db as backup

/**

     * Export current db into another db as backup

     * @param String $api_key

     */

    public function backup_yesterday($api_key = NULL)

    {

        if ($api_key != SMAP_API_KEY) exit('No access');


        $start_time = time();


        $user   = $_SERVER['DB_USER'];

        $pass   = $_SERVER['DB_PASSWORD'];

        $db     = $_SERVER['DB_NAME'];


        $backup_db  = 'smap_backup';

        $file_path  = PATH_IMAGE . 'temp_backup/yesterday.sql.gz';

        $mysql_path = '/Applications/MAMP/Library/bin'; // for MAMP only, change this to suit your local machine


        if (!file_exists(dirname($file_path))) { // create folder if not exist

            mkdir(dirname($file_path), 0755, TRUE);

        }

        file_put_contents($file_path, ''); // create temporary file


        // export db into temporary file

        $export_command = "$mysql_path/mysqldump --single-transaction --quick -u $user -p'$pass' $db | gzip > $file_path";

        exec($export_command, $output, $result);


        $messages = '';

        if ($result == 0) {

            $messages .= "DB '$db' exported to $file_path \n\n";


            // import db

            $import_command = "gunzip < $file_path | $mysql_path/mysql -u $user -p'$pass' $backup_db";

            exec($import_command, $output, $result);


            if ($result == 0) {

                $messages .= "DB '$backup_db' imported from $file_path \n\n";

            } else {

                $messages .= "Error importing DB \n\n";

            }

        } else {

            $messages .= "Error exporting DB \n\n";

        }


        // delete temporary file

        if (unlink($file_path)) {

            $messages .= "Deleted $file_path \n\n";

        } else {

            $messages .= "Error deleting file \n\n";

        }


        $messages .= 'Runtime: ' . (time() - $start_time) . ' seconds';


        echo nl2br($messages);

    }


📝 Useful mysql scripts 


Error something something group by

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));


List all tables inside a database into a string

USE db_name;

SELECT GROUP_CONCAT(table_name SEPARATOR ', ') AS tables FROM information_schema.tables WHERE table_schema = ‘db_name’;


Sanitise data in table

UPDATE table_name

SET email = NULL, phone = NULL 

WHERE email NOT LIKE '%@getnada.com%';


Useful js funcs


Format currency strings like ’20,000.00’ into floats ’20000.00’

    function stringToFloat(str) {

        return parseFloat(str.replace(/,/g, ''));

    }




 


Comments

Popular posts from this blog

Setup existing IONIC project in local

Setup existing IONIC project in local  Steps: clone git repo install ionic -  npm install -g @ionic/cli masuk folder repo project install npm dependencies -  npm install run ionic project -  ionic serve buka android studio / xcode -  ionic cap open $var  - $var = ‘android’ atau ‘ios’. ada dua je option, replace $var dgn dua option tu sync changes vscode & dkt android studio / xcode -  ionic cap sync good luck Common issues: dependency conflict check https://www.npmpeer.dev/ utk tengok version yg compatible try naikkan/turunkan version dependency yg keluar dkt error. tembak je sampai hilang error g radle issue try upgrade gradle. kalau tak boleh, try remove folder android & build semula e rror cocoapod make sure install xcode make sure install cocoapod error java  home not found utk mac, buka ~/.zshrc & masukkan chang es dkt VSC tak masuk android studio / xcode try ionic cap sync try quit & buka semula cordo va.variables.gradle no...

🪄 Useful git spells

Navigating the world of Git can be akin to mastering an arcane art. For the savvy developer, knowing the right incantations can mean the difference between seamless collaboration and catastrophic code conflicts. Here's a compendium of Git commands that are essential for those critical moments. Handle them with care, for they wield great power. Reverting to a Specific Commit (Non-Shared Branches Only) When you need to undo changes and return to a known good state: `git reset --hard <commit-hash>` - This will reset your branch to the specified commit. `git push -f origin` - Force push the changes to overwrite the remote branch. Merging Branches Like a Pro To incorporate changes from one branch into another, follow these steps: `git checkout <branch-to-merge-to>` - Switch to the branch you want to update. `git fetch origin` - Fetch the latest changes from the remote. `git pull` - Pull the latest changes into your local branch. `git status` - Check the status of your branch...

Vulnerabilities in dependencies used in projects

  Vulnerabilities in dependencies used in projects The case of 4Chan never updated any dependencies since 2009 one dependency used was publicly-known to have multiple critical vuln Ghostscript - https://security.snyk.io/vuln?search=ghostscript Local File Inclusion - process pdf files but never checked if the pdf is actually pdf Remote code execution - after injecting. can run scripts on the server The modern wake up call - this event reminded everyone to stay up to date with dependencies updates Dependencies we’re using: mPDF - fixed vuln for versions lower than 7.1.8 deserialization of untrusted data - similar with how 4chan got hacked aws/aws-sdk-php - fixed path traversal vuln for versions lower than 3.288.1 can go back and open directories that are not public arbitrary code execution vuln for versions lower than 3.2.1 Best practices: stay up to date with the tech world join forums like reddit and stackoverflow check websites that publish security reports snyk security - https:/...