Snippets Sandbox

A collection of PHP, CSS, HTML, Python snippets for your projects.

Browse Snippets Add a Snippet

Snippets


09/05/23 PHP Check if session_start() is already running By Raymond Hernandez
Avoid creating duplicate PHP sessions. Paste on every top of PHP scripts.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
08/30/23 PHP Attributes By Raymond Hernandez
Attributes provide a way to add metadata to classes, methods, properties, and more. They can be retrieved at runtime using the Reflection API.
#[MyAttribute]
class MyClass {}

$reflection = new ReflectionClass(MyClass::class);
$attributes = $reflection->getAttributes();
08/30/23 PHP JSON for Simple Serialization By Raymond Hernandez
Instead of using PHP's serialize() and unserialize(), using JSON is more portable across different systems and languages.
$array = ['a' => 1, 'b' => 2];
$json = json_encode($array);
$arrayAgain = json_decode($json, true);
08/30/23 PHP Late Static Bindings By Raymond Hernandez
It's a way to reference the called class in a context of static inheritance. self:: refers to the class in which it is called, while static:: refers to the class that was originally called.
class A {
    public static function who() {
        echo static::class;
    }
}
class B extends A {}

B::who();  // Outputs "B"
08/30/23 PHP Output Buffering By Raymond Hernandez
This allows you to capture all output (like echo) in a buffer. This can be useful if you want to manipulate the output before sending it to the browser.
ob_start();           // Start buffering
echo "Hello, ";
$output = ob_get_clean(); // Fetch the buffer contents and stop buffering
08/30/23 PHP List() & Foreach By Raymond Hernandez
With the list() function, you can assign multiple values in an array to multiple variables in one go.
list($a, $b, $c) = [1, 2, 3];
echo $a; // 1
08/30/23 PHP Variable-length Argument Lists By Raymond Hernandez
Functions can accept a variable number of arguments without explicitly declaring the number of parameters.
function sum(...$numbers) {
    return array_sum($numbers);
}
echo sum(1, 2, 3, 4, 5);  // Outputs 15
08/30/23 PHP Group Use Declarations By Raymond Hernandez
This is a concise way to import multiple classes, functions, or constants from the same namespace.
use MyNamespace\{
    ClassA, 
    ClassB, 
    ClassC as C
};
08/30/23 PHP Generators By Raymond Hernandez
Generators provide an easy way to create iterators without implementing the Iterator interface. They yield values one at a time using the yield keyword and save memory when dealing with large data sets.
function getRange($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}
08/30/23 PHP Spaceship Operator By Raymond Hernandez
It returns -1, 0, or 1 when $a is respectively less than, equal to, or greater than $b. It's handy for sorting functions.
usort($array, function ($a, $b) {
    return $a <=> $b;
});
08/30/23 PHP NULL Coalesce Operator By Raymond Hernandez
This operator is a shorthand for checking if a variable exists and has a non-null value. If it does, it returns its value; otherwise, it returns the value on the right side.
$username = $_GET['username'] ?? 'Guest'; 
// If $_GET['username'] is set and non-null, $username will get its value. Otherwise, 'Guest'.
08/30/23 PHP Array Destructuring By Raymond Hernandez
Array destructuring allows you to unpack elements from arrays directly into named variables. This can be especially useful in loops or when working with list-like structures.
$data = ['first', 'second'];
[$first, $second] = $data;
echo $first; // Outputs 'first'
08/30/23 PHP Anonymous Classes By Raymond Hernandez
Disposable Class so you don't have to assign a Class name.
$object = new class {
    public function sayHello() {
        return "Hello!";
    }
};
echo $object->sayHello(); // Prints "Hello!"
08/19/23 PHP JavaScript Alert Box and Forward Header Wrapped in PHP By Raymond Hernandez
An alert box that redirects to a different URL and displays a message or error notice if needed.
function redirect ( $url, $message ) {
    echo "<script type='text/javascript'>
            alert( '".$message."' );
            window.location.href='".$url."';
            </script>";
}
01/30/23 PHP Translate English Months to Tagalog By Raymond Hernandez
For a project I'm working on since it's parsing in Tagalog but the Date() in PHP only works in English.
function convert_to_tagalog($month) {
    $months = [
        'January'   => 'Enero',
        'February'  => 'Pebrero',
        'March'     => 'Marso',
        'April'     => 'Abril',
        'May'       => 'Mayo',
        'June'      => 'Hunyo',
        'July'      => 'Hulyo',
        'August'    => 'Agosto',
        'September' => 'Setyembre',
        'October'   => 'Oktubre',
        'November'  => 'Nobyembre',
        'December'  => 'Disyembre'
    ];

    return array_key_exists ( $month, $months ) ? $months[$month] : $month;
}
01/15/23 PHP Export your SQL Table as a CSV File By Raymond Hernandez
If a specific column needs to be modified, make sure to do it before fputcsv(). The headers are used to prepare the file for download, by specifying the type of file, name, time for expiry and whether to cache the file or not. The readfile function will read the contents of the file and output it to the browser, so that the browser can download it.
<?php

include('db.php'); // YOUR DATABASE CREDENTIALS
/* include('debug.php'); */

$result = mysqli_query( $con, "SELECT * FROM `YOUR_TABLE`" );

if ( ! $result ) { die( 'Error: ' . mysqli_error( $con ) ); }

$fp = fopen( 'import_householders.csv', 'w' ); // write mode

// Get the column names
$field_info_all = mysqli_fetch_fields( $result );
foreach( $field_info_all as $field_info ) {
  $headers[] = $field_info->name;
}

// Output the column names as the first row
fputcsv( $fp, $headers );

// Output the rest of the rows
while ( $row = mysqli_fetch_assoc( $result ) ) { 
  // OPTIONAL: Change the value of the first column to an empty string
  // $row[$headers[0]] = '';
  
  // Write it now as CSV
  fputcsv( $fp, $row );
}

// Close the file and the database connection
fclose( $fp );
mysqli_close( $con );

// This sets the content type of the file as "text/csv" browser knows 
// that it's a CSV file and can handle it accordingly.
header( 'Content-Type: text/csv' );

// This sets the filename that will be used when the file is downloaded. 
// It also sets the Content-Disposition as "attachment" so that the browser 
// prompts the user to download the file instead of displaying it in the browser.
header( 'Content-Disposition: attachment; filename="import_householders.csv"' );

// This tells the browser not to cache the file, 
// so that it will always be the latest version.
header( 'Pragma: no-cache' );

// This sets the expiration date of the file to 0, so that the browser 
// will always check if a new version is available.
header( 'Expires: 0' );

// This reads the CSV file and sends its contents to the browser.
readfile( 'import_householders.csv' );
?>
01/13/23 PHP Get GPS Coordinates from an Address (using cURL) By Raymond Hernandez
This version of the function uses cURL library instead of file_get_contents to send the request to the google api, cURL is more efficient and flexible than file_get_contents and also it provide more options like handling redirects, cookies and more.
<?php
function geocode($address) {
    // Map API needs '+' in place of spaces
    $key = /*Use your Google API Key!*/
    $address = str_replace (" ", "+", urlencode($address));
    $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=' . $key; 

    // Use curl instead of file_get_contents
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $unparsed_json = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($unparsed_json, true);

    // Extract only the necessary data
    $location = $result['results'][0]['geometry']['location'];
    $formatted_address = $result['results'][0]['formatted_address'];
    $building_type = $result['results'][0]['types'][0];

    $gps = array (
        'latitude'      => $location['lat'],
        'longitude'     => $location['lng'],
        'full_address'  => $formatted_address,
        'building_type' => $building_type
    ); 

    return $gps;
}
?>
01/12/23 PHP Display PHP Errors for Debugging By Raymond Hernandez
It's hard to track PHP errors, well at least for me anyway so I add this on every page I need to debug.
<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
?>
01/11/23 HTML Paginate Your Site By Raymond Hernandez
This is the code I used for the Territories page of Service Records. The code below must be pasted on each page that needs pagination...

$sql = 'SELECT COUNT(*) FROM your_table'; 
$total_pages = $con->query($sql)->fetch_row()[0];
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
$num_results_on_page = 20;
// pagination.php

<?php if (ceil($total_pages / $num_results_on_page) > 0): ?>
    <ul class="pagination">
    <?php if ($page > 1): ?>
    <li class="prev"><a href="territories.php?page=<?= $page-1 ?>"> Prev </a></li>
    <?php endif; ?>

    <?php if ($page > 3): ?>
    <li class="start"><a href="territories.php?page=1">1</a></li>
    <li class="dots" style="color:black">. . .</li>
    <?php endif; ?>

    <?php if ($page-2 > 0): ?><li class="page"><a href="territories.php?page=<?= $page-2 ?>">
    <?= $page-2 ?></a></li><?php endif; ?>
    <?php if ($page-1 > 0): ?><li class="page"><a href="territories.php?page=<?= $page-1 ?>">
    <?= $page-1 ?></a></li><?php endif; ?>

    <li class="currentpage"><a href="territories.php?page=<?= $page ?>"><?= $page ?></a></li>

    <?php if ($page+1 < ceil($total_pages / $num_results_on_page)+1): ?>
    <li class="page"><a href="territories.php?page=<?= $page+1 ?>"> 
    <?= $page+1 ?></a></li>
    <?php endif; ?>
    <?php if ($page+2 < ceil($total_pages / $num_results_on_page)+1): ?>
    <li class="page"><a href="territories.php?page=<?= $page+2 ?>">
    <?= $page+2 ?></a></li><?php endif; ?>

    <?php if ($page < ceil($total_pages / $num_results_on_page)-2): ?>
    <li class="dots" style="color:black">. . .</li>
    <li class="end">
    <a href="territories.php?page=<?= ceil($total_pages / $num_results_on_page) ?>">
    <?php echo ceil($total_pages / $num_results_on_page) ?></a></li>
    <?php endif; ?>

    <?php if ($page < ceil($total_pages / $num_results_on_page)): ?>
    <li class="next">
    <a href="territories.php?page=<?= $page+1 ?>">Next</a></li>
    <?php endif; ?>
    </ul>
<?php endif; ?>
01/11/23 PHP Get GPS Coordinates from an Address By Raymond Hernandez
Must use your own Google Maps API to query addresses.
<?php
// THIS FUNCTION CONVERTS STREET ADDRESS INTO GPS COORDINATES
function geocode($address) {

    // Map API needs '+' in place of spaces
    $key = /*Use your Google API Key!*/
    $address = str_replace (" ", "+", urlencode($address));
    $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=' . $key; 
    
    $unparsed_json = file_get_contents($url);
    $result = json_decode($unparsed_json, true);
    
    $gps = array (
        'latitude'      => $result['results'][0]['geometry']['location']['lat'],
        'longitude'     => $result['results'][0]['geometry']['location']['lng'],
        'full_address'  => $result['results'][0]['formatted_address'],
        'building_type' => $result['results'][0]['types'][0]
    ); 

    return $gps;
}
?>
01/11/23 PHP Paginate Your WordPress Site By Raymond Hernandez
Effective pagination improves user experience by enabling them to navigate through your website using intuitive links such as 'previous' and 'next' rather than searching manually. Our WordPress code snippet can assist in implementing this feature.
global $wp_query;
$total = $wp_query->max_num_pages;

if ( $total > 1 )  {
    // get the current page
    if ( !$current_page = get_query_var('paged') ) {
        $current_page = 1;
    }
    // structure of "format" depends on whether we're using pretty permalinks
    $format =  get_option('permalink_structure', '') ? 'page/%#%/' : '&page=%#%';
     
    echo paginate_links ( 
        array (
            'base'     =>  home_url() . '/%_%',
            'format'   => $format,
            'current'  => max( 1, get_query_var('paged') ),
            'total'    => $wp_query->found_posts,
            'mid_size' => 4,
            'type'     => 'list'
        )
    );
}
01/10/23 PHP Disable Search in WP By Raymond Hernandez

Disable Search in WordPress

This code hooks into the template_redirect action in WordPress, which is run before the template for a specific page is selected. The is_search() function checks if the current page being viewed is a search results page. If it is, the wp_redirect() function redirects the user to the homepage of your website, and the exit command stops the rest of the code from running.

This should disable the search feature on your website. It will redirect all the requests made to search page to home page.

function disable_search() {
    if ( is_search() ) {
        wp_redirect( home_url() );
        exit;
    }
}
add_action('template_redirect', 'disable_search');
01/10/23 PHP Allows Upload Images to WP By Raymond Hernandez
Allows contributors to upload images to WordPress. Paste to functions.php.
if ( current_user_can('contributor') && !current_user_can('upload_files') )
     add_action('admin_init', 'allow_contributor_uploads');      
     function allow_contributor_uploads() {
          $contributor = get_role('contributor');
          $contributor->add_cap('upload_files');
     }
01/10/23 HTML Dynamic Footer By Raymond Hernandez
Footer for all my sites. Year is dynamic with the current year.
&copy; 
<?php echo date('Y'); ?> 
<a href="https://www.arbhie.com" target="_blank">arbhie.com</a> 
by Raymond Hernandez
01/10/23 PHP Display All Rows - WHILE Loop By Raymond Hernandez
This is the WHILE loop I use for all my sites to display all row values from a database.
<?php
    $result = mysqli_query($con, $query); 
    while ($row =  mysqli_fetch_assoc($result)):
        // echo row values here //
    endwhile;
?>

Add Snippet