Blog

  •  

    PHP Code Snippet Use

    Convert Seconds to Days, Hours and Minutes

    Making a number of seconds to convert into minutes, hours and days to estimate the same amount of time on a different scale. This conversion process is achieved with use of the below code snippet written in PHP after making necessary calculations. Make use of this code snippet and enter the number of seconds you want to get conversion of in different units. The result automatically shows at the bottom of your screen.

    function secsToStr($secs) {

        if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}

        if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}

        if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}

        $r.=$secs.' second';if($secs<>1){$r.='s';}

        return $r;

    }

    function secsToStr($secs) {

        if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}

        if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}

        if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}

        $r.=$secs.' second';if($secs<>1){$r.='s';}

        return $r;

    }

    <?php

    $seconds = "56789";

    $output = secsToStr($seconds);

    echo $output;

    ?>

    <?php

    $seconds = "56789";

    $output = secsToStr($seconds);

    echo $output;

    ?>

    PHP Code Snippet for Database Connection

    If you are making a database in PHP and you want a MySQL database connection, you can always make use of the below shown snippet and use it when you want to connect it to your programmed database.

    To store data, you would need a database. In this case, we would be using MySQL database.

    <?php

    $DBNAME = 'koonk';

    $HOST = 'localhost';

    $DBUSER = 'root';

    $DBPASS = 'koonk';

    $CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);

    if(!$CONNECT)

    {

                                               echo 'MySQL Error: '.mysql_error();

    }

    $SELECT = mysql_select_db($DBNAME);

    if(!$SELECT)

    {

                                               echo 'MySQL Error: '.mysql_error();

    }

    ?>

    <?php

    $DBNAME = 'koonk';

    $HOST = 'localhost';

    $DBUSER = 'root';

    $DBPASS = 'koonk';

    $CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);

    if(!$CONNECT)

    {

                                               echo 'MySQL Error: '.mysql_error();

    }

    $SELECT = mysql_select_db($DBNAME);

    if(!$SELECT)

    {

                                               echo 'MySQL Error: '.mysql_error();

    }

    ?>

    In the highlighted lines above, you would have to specify your own server database details.

    You can save the above file as config.php and you would have to include that file in all pages where you need database connectivity.

    PHP Coding Practices

    PHP Snippet for Directory Listing

    Using the below PHP development code snippet you would be able to list all files and folders in a directory.

    Trying to get all listing of files and folders in a directory, you need to use the code below until you get desired results.

    function list_files($dir)

    {

        if(is_dir($dir))

        {

            if($handle = opendir($dir))

            {

                while(($file = readdir($handle)) !== false)

                {

                    if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)

                    {

                        echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";

                    }

                }

                closedir($handle);

            }

        }

    }

    function list_files($dir)

    {

        if(is_dir($dir))

        {

            if($handle = opendir($dir))

            {

                while(($file = readdir($handle)) !== false)

                {

                    if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)

                    {

                        echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";

                    }

                }

                closedir($handle);

            }

        }

    }

    <?php

        list_files("images/"); //This will list all files of images folder

    ?>

    <?php

        list_files("images/"); //This will list all files of images folder

    ?>

    Detect User Language

    Using the below PHP snippet you would be able to detect the language used in your browser. The language other than English uncommonly used when surfing the web, discovered through this PHP based code will make a difference to you when understanding the language on websites. You will just require considering the snippet below and find out the foreign language that your browser is using.

    function get_client_language($availableLanguages, $default='en'){

                                               if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

                                                    $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

     

                                                    foreach ($langs as $value){

                                                                $choice=substr($value,0,2);

                                                                if(in_array($choice, $availableLanguages)){

                                                                            return $choice;

                                                                }

                                                    }

                                               }

                                               return $default;

    }

    function get_client_language($availableLanguages, $default='en'){

                                               if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

                                                    $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

     

                                                    foreach ($langs as $value){

                                                                $choice=substr($value,0,2);

                                                                if(in_array($choice, $availableLanguages)){

                                                                            return $choice;

                                                                }

                                                    }

                                               }

                                               return $default;

    }

    Reading a CSV File

    function readCSV($csvFile){

                                               $file_handle = fopen($csvFile, 'r');

                                               while (!feof($file_handle) ) {

                                                    $line_of_text[] = fgetcsv($file_handle, 1024);

                                               }

                                               fclose($file_handle);

                                               return $line_of_text;

    }

    function readCSV($csvFile){

                                               $file_handle = fopen($csvFile, 'r');

                                               while (!feof($file_handle) ) {

                                                    $line_of_text[] = fgetcsv($file_handle, 1024);

                                               }

                                               fclose($file_handle);

                                               return $line_of_text;

    }

    <?php

    $csvFile = "test.csv";

    $csv = readCSV($csvFile);

    $a = csv[0][0]; // This will get value of Column 1 & Row 1

    ?>

    <?php

    $csvFile = "test.csv";

    $csv = readCSV($csvFile);

    $a = csv[0][0]; // This will get value of Column 1 & Row 1

    ?>

    PHP Code Based on Open Source Platform

    Creating a CSV File from PHP Array

    Try using the code below and make a CSV file from the array provided. You can use it for easier access as well as store your data you need to use again in future.

    function generateCsv($data, $delimiter = ',', $enclosure = '"') {

       $handle = fopen('php://temp', 'r+');

       foreach ($data as $line) {

                                                       fputcsv($handle, $line, $delimiter, $enclosure);

       }

       rewind($handle);

       while (!feof($handle)) {

                                                       $contents .= fread($handle, 8192);

       }

       fclose($handle);

       return $contents;

    }

    function generateCsv($data, $delimiter = ',', $enclosure = '"') {

       $handle = fopen('php://temp', 'r+');

       foreach ($data as $line) {

                                                       fputcsv($handle, $line, $delimiter, $enclosure);

       }

       rewind($handle);

       while (!feof($handle)) {

                                                       $contents .= fread($handle, 8192);

       }

       fclose($handle);

       return $contents;

    }

    <?php

    $data[0] = "apple";

    $data[1] = "oranges";

    generateCsv($data, $delimiter = ',', $enclosure = '"');

    ?>

    <?php

    $data[0] = "apple";

    $data[1] = "oranges";

    generateCsv($data, $delimiter = ',', $enclosure = '"');

    ?>

    Parsing XML Data

    Below PHP snippet will help you explain how you can parse XML data in PHP.

    This code snippet allows you to interpret XML coding for use in other projects where you find its application. It is commonly accepted as a tool you access as well as simplify and implement in the developmental process.

    $xml_string="<?xml version='1.0'?>

    <moleculedb>

        <molecule name='Benzine'>

            <symbol>ben</symbol>

            <code>A</code>

        </molecule>

        <molecule name='Water'>

            <symbol>h2o</symbol>

            <code>K</code>

        </molecule>

    </moleculedb>";

    //load the xml string using simplexml function

    $xml = simplexml_load_string($xml_string);

    //loop through the each node of molecule

    foreach ($xml->molecule as $record)

    {

       //attribute are accessted by

       echo $record['name'], '  ';

       //node are accessted by -> operator

       echo $record->symbol, '  ';

       echo $record->code, '<br />';

    }

    $xml_string="<?xml version='1.0'?>

    <moleculedb>

        <molecule name='Benzine'>

            <symbol>ben</symbol>

            <code>A</code>

        </molecule>

        <molecule name='Water'>

            <symbol>h2o</symbol>

            <code>K</code>

        </molecule>

    </moleculedb>";

    //load the xml string using simplexml function

    $xml = simplexml_load_string($xml_string);

    //loop through the each node of molecule

    foreach ($xml->molecule as $record)

    {

       //attribute are accessted by

       echo $record['name'], '  ';

       //node are accessted by -> operator

       echo $record->symbol, '  ';

       echo $record->code, '<br />';

    }

Comments

  • (no comments)

This free website is created and hosted by Website.com's Site Builder.