keyboard_arrow_up

 Simple PHP Snippets

Table of Contents

The purpose of this page is to archive and share short but useful PHP snippets. I use these a lot in my centralised functions.php file and it helps you to write less by making use of server-side magic!

Of course the codes samples written are completely in the public domain.

Automated Table of Contents using 2-Dimensional Array

function toc($toc, $tocTitle = "Table of Contents", $icon = "fa-list") {
    echo '<article class="toc">'."\n".'<h2><i class="fa '.$icon.'"></i> '.$tocTitle.' <i class="fa fa-caret-down spinable"></i></h2>'."\n<ul>\n";
    foreach($toc as $row) {
        echo '<li><a href="#'.$row[0].'">'.$row[1].'</a></li>'."\n";
    }
    echo "</ul>\n</article>\n";
}

Function accepts two optional arguments, $tocTitle which holds the title of the table of contents, and $icon which holds what icon to display (using FontAwesome).

Example Usage

// If you want to have the table of content to have different title name and different icon
toc($toc, "Categories", "fa-file-code-o");
// Otherwise you can just call the function with only the array as argument
toc($toc);

Now, before you can output the table of contents, an array $toc needs to be populated with elements. Then, you will need to call the function so the ToC can be displayed on the page. Example usage (assuming the function definition is already written):

$toc = [
    ["apps", "Apps"],
    ["tools", "Tools"],
    ["services", "Services"],
    ["webscripts", "Web Components"],
    ["games", "Games"]
];
toc($toc, "Categories", "fa-file-code-o"); // custom title, custom icon

Current Page URL (with additional features)

function currentURL($type = "path") {
    if($type == "path") {
        return $_SERVER['REQUEST_URI'];
    } elseif($type == "host") {
        return $_SERVER['HTTP_HOST'];
    } elseif($type == "isHomepage") {
        $url = $_SERVER['REQUEST_URI'];
        if($url == "/" || preg_match("/^\/index/", $url)) {
            return true;
        } else {
            return false;
        }
    } elseif($type == "hasIndex") {
        if(preg_match("/index\..{3,4}/", $_SERVER['REQUEST_URI'])) {
            return true;
        } else {
            return false;
        }
    } elseif($type == "canonical" || $type == "full") {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
        return $protocol.'://'.$_SERVER['HTTP_HOST'].preg_replace(array("/index\..{3,4}/", "/\?.*$/i"), "", $_SERVER['REQUEST_URI']);
    } else {
        return "Nothing!";
    }
}

This function accepts only one parameter $type which will determine what URL the function will return. This is by default “path”, which will only send the “request” part of the URL (/something.html instead of sub.host.domain/something.html). Other options include:

  • host which returns the host name
  • isHomepage which returns boolean “true” if page is the homepage (root index.php) otherwise “false”
  • hasIndex which returns boolean “true” if page URL has word “index” in it otherwise “false”
  • canonical which returns the full “canonical” address of the current page. Note that this will remove any occurences of “index” with the file extension
  • full is the alias of canonical
If unrecognisable parameter is received, it will return string “Nothing!”.

Example Usage

// return canonical url
echo "Current page URL: ".currentURL("canonical");
// return only request path
echo "Current page URL: ".currentURL();
// ditto
echo "Current page URL: ".currentURL("path");
// check if the page has "index" in its URL
if(currentURL("hasIndex")) {
    echo "Current page URL has 'index!'";
} else {
    echo "Current page URL has no 'index'";
}

Redirect using HTTP Headers

function redirect($url, $permanent = false) {
    if($url == 404 || $url == "404") {
        header('HTTP/1.1 404 Not Found', true, 404);
    } else {
        header('Location: '.$url, true, $permanent ? 301 : 302);
    }
    exit();
}

This function accepts 2 parameters, first being a requirement while the second optional. You will need to enter the target URL that you want the user to be redirected to. If the redirection is permanent in nature, you might want to enter boolean “true” for the second parameter.

Entering “404” for $URL parameter will instead redirect your user to your website's 404 ErrorDocument page as defined in your server configuration. If this is the case, $permanent parameter will not affect anything.

 Sending HTTP headers require that your server hasn't sent any bytes to the client, even whitespaces! PHP Documentation

Example Usage

// redirect, temporary
redirect("https://google.com");
// redirect, permanent!
redirect("https://google.com", true);
// 404 redirect
redirect(404);