Category Archives: Server Administration

How to Figure Out Relative Humidity with PHP

Today, I had to calculate relative humidity using PHP and I have documented my findings below:

First, let's just use an example situation where we have a temperature of 60.1 and a dew point of 42.7, both in Fahrenheit, so...:

dew point in Fahrenheit: 42.7

temperature in Fahrenheit: 60.1

1) The first step is to convert to Celsius using the following formulas
Tc=5.0/9.0*(Tf-32.0)

Tdc=5.0/9.0*(Tdf-32.0)

Formulas explained:
Tc=air temperature in degrees Celsius, Tf=air temperature in degrees Fahrenheit

Tdc=dewpoint temperature in degrees Celsius

Tdf=dewpoint temperature in degrees Fahrenheit

Notice: If your temperature and dewpoint are in degrees Celsius, you can skip step 1 and proceed to step 2.

answer for equations:
Temp in Celsius: 15.61

Tc=5.0/9.0*(Tf-32.0)
5.0/9.0*(60.1-32.0)
5.0/9.0*28.1
0.5555555555555556 * 28.1 = 15.61111111111111

dewpoint in Celsius: 5.94
5.0/9.0*(Tdf-32.0)
5.0/9.0*10.7
0.5555555555555556 *  10.7 = 5.944444444444444

2) calculate saturation vapor pressure(Es) and actual vapor pressure(E) in millibars:
NOTE: first line is the equation and the subsequent lines represent one step solved at a time:
Es=6.11*10.0**(7.5*Tc/(237.7+Tc))
Es=6.11*10.0**(7.5*15.61/(237.7+15.61))
Es=61.1 ** (7.5*15.61/(237.7+15.61))
Es=61.1 ** (117.075/253.31)
Es = 61.1**0.4621807271722395
Es = 6.6907349413770067935260257174923

E=6.11*10.0**(7.5*Tdc/(237.7+Tdc))
E=6.11*10.0**(7.5*5.94/(237.7+5.94))
E=61.1 ** (7.5*5.94/(237.7+5.94))
E=61.1 ** (44.55/243.64)
E=61.1 ** 0.1828517484813659497619438515843
E = 2.1211957981192776150462474985589

3)  Once you have the saturation vapor pressure and actual vapor pressure, relative humidity(RH) can be computed by dividing the actual vapor pressure by the saturation vapor pressure and then multiplying by 100 to convert the quantity to a percent:
RH =(E/Es)*100
RH =(2.1211957981192776150462474985589/6.6907349413770067935260257174923)*100
RH = 0.31703479762758596814611114744566 * 100
RH = 31.703479762758596814611114744566%
SO... Humidity is 31.7%

And note here that ** means to the power of. I figured I'de clue anyone in that is as ignorant is I was when I had to figure it out.

How to Search and Replace File Names

A lot of times I am required to rename large quantities of files according to various rules. Sometimes this task can take hours to complete. Today I had a job requiring me to rename all files in a program that contained "xi" with "nap". The program had thousands of files in a dozen different directories. It would have taken days for me to go through them all manually and replace ea. occurrence of "xi" in the file names with "nap", so I tested several tools to help me do the job. The most capable tool I found was named simply "ReNamer" and can be downloaded from:
https://www.den4b.com/products/renamer

I downloaded the "portable" version of ReNamer version 6.7 Here is a screenshot of ReNamer's simply UI:
ReNamer

How to Download and Open ReNamer for First Use

First things first, so here is how to get started:

Use the link https://www.den4b.com/products/renamer to download the portable version of ReNamer and it will download a zip file to your PC. Place the file on your desktop and right click it and select "Extract All". Windows will extract the files and probably open the folder for you. Then click on renamer.exe to start the app. You will see the UI as in the above image. I like using this portable version because it is very light-weight and can be used on any PC. When I'm done using it, I simply delete the entire unzipped folder but I save the .zip folder I downloaded so I can use it again when needed and it doesn't waste any space on my PC when it's not in use. Next time I need it, I simply extract the files again and use it. Then I delete the folder when done again.

Find and Replace Text in File Names of Many Files at Once

It is easy as pie to use too! It only took me a couple of test runs to achieve the renaming rules I needed to do the job at hand. Just  click where it says "Click here to add a rule" and add a rule. I needed to find and replace text in the file names, so in my case, I clicked on "replace" in the left panel so the add rule screen looks like this:

renamerules

 

All I had to do was simply enter "xi" in the "find" field and "nap" in the "replace" field and click the "Add Rule" button to save your new rule. Then all you have to do is drag the folder containing all the files you want to rename into the UI as in the first image above, where it says "Drag Your Files Here". Then it gives you a preview of what files it will rename. Once you are happy with how it's doing the renaming, click the "Rename" button in the upper right corner of the UI and it will rename all of the files just like it showed you. If you have tested any of the other features of this tool, please comment below and describe your experience!

Enabling Multiple Domain Names and Sites on Apache2 Server

Today I set up a new server and I am documenting exactly how to set up multiple domain names, sub domains and websites on a new Apache2 Server. I am using Ubuntu, but I believe these directions are similar for any Linux Apache2 web server.

Pointing your domain or sub-domain

It is a good practice to point your domain name or sub-domain first, before you set it up on your server which I'll cover afterwards below, so let's go ahead and point our domain. Whether you are using a new domain name or a sub-domain on one of your existing domain names, the process is similar for pointing the domain name or sub domain name to your server IP address. You will need to go to your domain management console and create a Type "A" record. This will normally be done in your DNS provider's advanced DNS settings or zone file settings. Use the following settings to create two new records:

  • Name: if there is a name field, enter the domain name or sub-domain name(most require you to follow the domain with a "." so for my sub domain I entered "subdom.jafty.com.".
  • Type: "A" for both records.
  • Hostname field: enter "www" in the first record and "@" in the second.
  • Destination IPv4 address(sometimes just called Address): Use your server's IP address for both records.
  • TTL: use "14400" for both records.

That should be enough information for you to figure out how to create your two host records on just about any platform, but if your platform differs, ask your provider for assistance or google the providers name followed by DNS instructions or "How to point a name with Provider Name". You are creating two similar records, one for WWW and one for @. That way visitors of your site can access with either www.example.com or just example.com. The Hostname of @ makes the record for the domain without "www" in front of it. If your provider's DNS settings do not include the Host or Hostname field where we put either www or @, then you probably need to create two records with different names instead. For example, name one record "example.com." and name the other "www.example.com.". If you're using a sub domain then name one "sub.example.com." and the other "www.sub.example.com." You don't really need a www record for sub domains usually, but you can use one if you want, it won't hurt anything and might help some users find your site.

Steps to adding  a second domain name to your server

Here I am going to explain how I set up a sub domain as as second domain name pointing to a second website on my Linux/Apache2 web server:

Note: My first site was already set up in var/www/html. Most people prefer to set up multiple websites under the var/www directory, but to keep things simple, I'm going to use the var/www/html folder and not var/www. It really makes no difference. It's just a preference.

  1. Create your directory structure for your new website that will reside on your new domain or sub-domain. I'm creating a sub domain like subdir.jafty.com, but these directions are the same as if I were using just jafty.com instead. First, create the directory /var/www/html/subdir.jafty.com. Then create /var/www/html/subdir.jafty.com/logs and /var/www/html/subdir.jafty.com/public_html. If you are logged into FileZilla as root, you can create these from there, otherwise log in with putty and create them using the sudo command.
  2. Create your log files. Simple make two empty files named access.log and error.log and upload them to the logs folder you created in step one above.
  3. Create a VHOSTS file named after the domain or sub-domain followed by .conf, so in my case, I'd name my file subdir.jafty.com.conf. THen copy and paste the  content below under the heading "VHOSTS Example File Contents" into it then change all instances of my sub-domain name with your own domain or sub domain and upload that file to /etc/apache2/sites-available.
  4. Next, use the a2ensite tool from the Linux command line to finalize the new site with the following command(replace example.com with your domain or sub-domain):  sudo a2ensite example.com.conf
  5. Reset apache2 with: sudo service apache2 restart

VHOSTS Example File Contents

<Directory /var/www/html/planner.jafty.com/public_html>
    Require all granted
</Directory>
<VirtualHost *:80>
    ServerName planner.jafty.com
    ServerAlias www.planner.jafty.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/planner.jafty.com/public_html

    ErrorLog /var/www/html/planner.jafty.com/logs/error.log
    CustomLog /var/www/html/planner.jafty.com/logs/access.log combined
</VirtualHost>

Automating the process of setting up domain names and sub domains

If you have to do this often or alter DNS records often and create lots of virtual hosts, you should probably look into automating the process. I provide such a service and have done so for several of my clients. What I do is create a simple user interface in a secure admin web page on your own server where you can simply enter the domain name or sub domain name into a form field and press GO and it does all the above work for you! A real time saver if you have to do this more than once in a great while! IF you are interested in this service, contact me, Ian L. of Jafty.com for a fast, free quote by email or Skype. My email is linian11@yahoo.com and my Skype name is ianlin11. Or use the contact link on this site.

Summary

That is how you do it!

Understanding ARIA Click Button to Show or Hide Content Example Code

Understanding ARIA

ARIA stands for "Accessible Rich Internet Applications". Also known as the WAI-ARIA standard, it is a standard developed to help coders to provide proper semantics for custom widgets and to make them accessible, usable, and interoperable with assistive technologies for people with disabilities. To be clear, ARIA doesn't add functionality to an object. It adds roles and states that assist in identifying the intent and state of an object. However, usually JavaScript code is still needed to add any dynamic action to that object. I state this clearly at the top of this post because at first, I was under the impression that ARIA also added certain functionalities to HTML objects and was seriously disappointed when I found out otherwise. For example, when ARIA is used on a button that hides and shows content in a div, it only defines the roles and states of the button and corresponding div. JavaScript is still needed to do that work of hiding and showing the div in question.

Example Code

Here is an example of correctly implementing ARIA controls when making a button that hides and shows a div on the click of your mouse. It also binds the space bar and enter key to the div as well, so pressing either of those keys toggles the visibility of the div as well. Without any further ado, the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Aria Examples</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
div.topic {
    display: none;
    margin-bottom: 1em;
    padding: .25em;
    border: black thin solid;
    background-color: #EEEEFF;
    width: 40em;
}
</style>
</head>
<body>

<p class="button">
    <button id="button1" class="buttonControl" aria-controls="t1" aria-expanded="false"><span>Show</span> Topic 1</button>
</p>

<div id="t1" class="topic" role="region" tabindex="-1" >
    Topic 1 is all about being Topic 1 and may or may not have anything to do with other topics.
</div>

<script>
$(document).ready(function() {

   var hs1 = new hideShow('button1');
  // var hs2 = new hideShow('button2');
  // var hs3 = new hideShow('button3');
  // var hs4 = new hideShow('button4');
 
}); // end ready()

//
// function hideShow() is the constructor for a hideShow widget. it accepts the html ID of
// an element to attach to.
//
// @param(id string) id is the html ID of the element to attach to
//
// @return N/A
//
function hideShow(id) {

   this.$id = $('#' + id);
   this.$region = $('#' + this.$id.attr('aria-controls'));

   this.keys = {
               enter: 13,
               space: 32
               };

   this.toggleSpeed = 100;

   // bind handlers
   this.bindHandlers();

} // end hidShow() constructor

//
// Function bindHandlers() is a member function to bind event handlers to the hideShow region
//
// return N/A
//
hideShow.prototype.bindHandlers = function() {

   var thisObj = this;

   this.$id.click(function(e) {

      thisObj.toggleRegion();

      e.stopPropagation();
      return false;
   });
}

//
// Function toggleRegion() is a member function to toggle the display of the hideShow region
//
// return N/A
//
hideShow.prototype.toggleRegion = function() {

      var thisObj = this;

    // toggle the region
    this.$region.slideToggle(this.toggleSpeed, function() {

      if ($(this).attr('aria-expanded') == 'false') { // region is collapsed

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'true');

        // move focus to the region
        $(this).focus();

        // update the button label
        thisObj.$id.find('span').html('Hide');

      }
      else { // region is expanded

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'false');

        // update the button label
        thisObj.$id.find('span').html('Show');
      }
    });

} // end toggleRegion()
</script>
</body>
</html>

Thank you oaa-accessibility.org for providing me with enough knowledge to create and use the above example! They have the best example code for ARIA usage that I could find online after many Google searches. See their complete list of example ARIA examples at http://oaa-accessibility.org/

ARIA and WordPress

I noticed ARIA controls for the first time in the header.php file for my WordPress theme. I was trying to fix a mobile navigation menu and thought couldn't find the code that makes the menu appear on mobile devices when the button is clicked and thought ARIA had something to do with it. I was basically wrong. ARIA code was only present to mark the navigation menu and make it's role and states readily accessible. It is after all an accessibility feature.

Summary

So ARIA and the WAI-ARIA standard are used to enable more accessible HTML markup for disabled people. While it is a great initiative, it doesn't add much dynamic functionality to your HTML objects, JavaScript is still needed for that. ARIA combined with HTML, CSS and JavaScript can be used to make accessible web pages more user-friendly.

Get IP Address from Domain Name

Here is a simple little tool written in PHP that will return the IP address of any given domain name or if there are more than one, a list of IP addresses will be returned.

 

Get Domain Name's IP Address

Returns the IP address associated with the domain name you enter into the form. It will return a list of IP addresses if more than one is associated with the given domain name.


Get Domain Name's IP Address

Returns the IP address associated with the domain name you enter into the form. It will return a list of IP addresses if more than one is associated with the given domain name.

Domain name:

 

NGINX New Site Creation and Server Configurations

Today I'm going to share with my readers my list for manually creating another website on one of my NGINX servers. I am partially logging this here for my own reference as I often look for these directions I keep stored in a .txt file on my laptop. Wherever you see text in green in this post, it will indicate that the text is to be entered as a command at the command prompt in Linux.

Step by Step Directions to Add a New Site on NGINX Servers

1) Sign into Linux server using an application like Putty (Windows) or Terminal (Mac):

Login with root user and password if possible, otherwise login with the user and password you have and remember to use sudo commands(purring sudo before each command line command)

2) Create the website directory (for example, your_new_site.com):

mkdir -p /var/www/your_new_site.com/public_html
mkdir -p /var/www/your_new_site.com/logs

3) Change the ownership of the directory to the web user:
chown -R www-data:www-data /var/www/your_new_site.com/public_html
chown -R www-data:www-data /var/www/your_new_site.com/logs

4) Create the web site config file. To do this, you can simply copy the config file of an existing site and then make the required changes. For example try this command but change the existing_site to your own existing website on your server:
cp /etc/nginx/sites-available/existing_site.com /etc/nginx/sites-available/your_new_site.com

5) Edit the new config file to replace with the new site’s values:

nano /etc/nginx/sites-available/your_new_site.com
Edit the line that reads: root /var/www/existing_site.com/public_html to be the current domain name.
Edit the two server_name instances to be the new domain name.
Edit access_log and error_log paths for new domain name
Save the file by hitting Ctrl-X, then Y and then Enter.

6) Enable the new site in NGINX:

ln -s /etc/nginx/sites-available/sandiboudreau.com /etc/nginx/sites-enabled/

7) Restart NGINX:

service nginx restart

9) Create the database and user.

mysql -u root -p
your_password
create database database name;
(note: I often create the db and user with the same name as the domain name. That makes it easy to remember. However, MySQL users are limited to 16 characters. so if the domain name is longer, I truncate both in some fashion. Just make sure theu match.
grant all on your_new_site.* to 'your_new_site' identified by 'secret_password';
(the last part is the password. just make up a hard one - record this where only you can find it, you’ll need it with the restore)
quit

8) Copy your new website files into the public_html folder with your sFTP client and your site is up and running!

Using PHP to create an NGINX SITE MAKER

I used the above knowledge to create a Site Maker tool that does all the steps for you. All you have to do is enter a domain name. Email me if interested at linian11@yahoo.com

Summary

So, this isn't too hard if you have something to reference such as the above cheat sheet. Once you get used it doing it, it is really easy. However if it's too complex, you can do what I did and make a tool to do it for you. Even if it's not too difficult, the tool saves you time if you add a lot of sites to your NGINX server as I do. Email me if you have interest in such a tool and I can custom build you one for your server! linian11@yahoo.com is my email.

How to Remove Slugs for a Custom Post Type in WordPress

So, back in the day, not to long ago, one could remove slugs in a CPT(Custom Post Type), simply by adding the following line to the arguments array when calling the register_post_type function:

'rewrite' => array('slug' => ''),//NOT THE SOLUTION!

However, that no longer works as of WordPress version 4.7.?, so I put together the following two function from various other solutions I've seen. This solution works for a single post type or multiple post types. I am publishing it because I haven't seen any elsewhere that could handle more than one CPT at a time. I wrote this to remove slugs for two CPTs, but you could us it for one or as many as you want, the two functions are as follows and can be added to functions.php or, as I do, to a plugin file, below the register_post_type functions:

<?php

//Two functions to remove slug from team_member and event CPTs:
function remove_evil_slugs($post_link, $post, $leavename) {

    if('team_member' != $post->post_type || 'event' != $post->post_type ||'publish' != $post->post_status) {
        return $post_link;
    }

    $post_link = str_replace('/' . $post->post_type . '/', '/', $post_link);

    return $post_link;
}
add_filter('post_type_link', 'remove_evil_slugs', 10, 3);

function  parse_evil_slugs($query) {

    if(!$query->is_main_query() || 2 != count($query->query) || !isset($query->query['page'])) {
        return;
    }

    if(!empty($query->query['name'])) {
        $query->set('post_type', array('post', 'team_member', 'event', 'page'));
    }
}
add_action('pre_get_posts', 'parse_evil_slugs');

?>

Those are the two functions that accomplish the goal. Simply replace all occurrences of "team_member" and "event" with the names of your own custom post types. If you use any rewrite rules in the args parameter for the register_post_type function, comment it out. For example if you see anything that looks like this:

'rewrite' => array('slug' => ''),

or

'rewrite' =>false,

...either comment it out of delete it all together from the function that creates the custom post type(CPT).

Update 3-27-2017

I've noticed that on some servers, the above solution no longer works, so I was able to program a new solution for NGINX servers. If your server is not an NGINX server, I found a solution here that should work for all even though it is a bit outdated: https://github.com/jonbish/remove-slug-from-custom-post-type. The code below is code I wrote based on that link but updated for nginx servers:

<?php
class JAFTY_CPT_SlugKiller{
    
    static $_s = null;
    private $htaccess_tag = 'SLUG KILLER REMOVE SLUG RULES';
    
    public function __construct() {
        $this->rewrite_rules();
        
        add_action('wp_insert_post', array(&$this, 'post_save'));

        add_filter('post_type_link', array(&$this, 'remove_slug'), 10, 3);
        
    }
    
    
    static public function init() {
        if (self::$_s == null) {
            self::$_s = new self();
        }
        return self::$_s;
    }
    
    static public function flush_rewrite_rules() {
        $jafty_o = self::init();
        $jafty_o->rewrite_rules(true);    
        //$jafty_o->add_rules_htaccess();
    }

    public function post_save($post_id) {
        global $wp_post_types;
        $post_type = get_post_type($post_id);
        foreach ($wp_post_types as $type=>$custom_post) {
            if ($custom_post->_builtin == false && $type == $post_type) {
                $this->rewrite_rules(true);
                //$this->add_rules_htaccess();
                flush_rewrite_rules();
            }
        }
    }
    
    public function remove_slug($permalink, $post, $leavename) {
        global $wp_post_types;

        foreach ($wp_post_types as $type=>$custom_post) {
            if ($custom_post->_builtin == false && $type == "team_member") {
                $custom_post->rewrite['slug'] = trim($custom_post->rewrite['slug'], '/');
                $permalink = str_replace(get_bloginfo('url') . '/' . $custom_post->rewrite['slug'] . '/', get_bloginfo('url') . "/", $permalink);
            }
        }
        return $permalink;
    }
    
    public function rewrite_rules($flash = false) {
        global $wp_post_types, $wpdb;
        foreach ($wp_post_types as $type=>$custom_post) {
            if ($custom_post->_builtin == false && $type == "team_member") {
                $querystr = "SELECT {$wpdb->posts}.post_name
                                FROM {$wpdb->posts}
                                WHERE {$wpdb->posts}.post_status = 'publish'
                                        AND {$wpdb->posts}.post_type = '{$type}'
                                        AND {$wpdb->posts}.post_date < NOW()";
                $posts = $wpdb->get_results($querystr, OBJECT);
                foreach ($posts as $post) {
                    $regex = "{$post->post_name}\$";
                    add_rewrite_rule($regex, "index.php?{$custom_post->query_var}={$post->post_name}", 'top');            
                }
            }
        }
        if ($flash == true)
            flush_rewrite_rules(false);
    }
    
    
    private function add_rules_htaccess() {
        global $wp_post_types;
        $suffix = get_option('jafty_permalink_customtype_suffix');
        $write = array();
        $htaccess_filename = ABSPATH . '/.htaccess';
        if(is_readable($htaccess_filename)){
            $htaccess = fopen($htaccess_filename, 'r');
            $content = fread($htaccess, filesize($htaccess_filename));
            foreach ($wp_post_types as $type=>$custom_post) {
                $rewrite_rule = (!empty($suffix))
                            ? "RewriteRule ^{$custom_post->query_var}/(.+)/\$ /\$1\.{$suffix} [R=301,l]"
                            : "RewriteRule ^{$custom_post->query_var}/(.+)/\$ /\$1 [R=301,L]";
                if (strpos($content, $rewrite_rule) == false && $custom_post->_builtin == false)
                    $write[] = $rewrite_rule;
            }
            fclose($htaccess);
        }else{
            add_action('admin_notices', array(&$this, 'compatibility_notice'));
            return;
        }
        
        if (!empty($write) && is_writable($htaccess_filename)) {
            $new_rules = '# BEGIN ' . $this->htaccess_tag . PHP_EOL;
            $new_rules .= str_replace('$', '\\$', implode(PHP_EOL, $write)) . PHP_EOL;
            $new_rules .= '# END ' . $this->htaccess_tag;
            if (strpos($content, "# BEGIN {$this->htaccess_tag}") === false) {
                file_put_contents($htaccess_filename, $new_rules . PHP_EOL . PHP_EOL . $content);
            }
            else {
                $pattern = "/# BEGIN {$this->htaccess_tag}.*?# END {$this->htaccess_tag}/ims";
                $content = preg_replace($pattern, $new_rules, $content);
                file_put_contents($htaccess_filename, $content);
            }
        }else if(!is_writable($htaccess_filename))
            add_action('admin_notices', array(&$this, 'compatibility_notice'));
    }//end add_rules_htaccess function

    
    public function compatibility_notice() {
        global $wp_post_types;
        $rules = '';
        foreach ($wp_post_types as $type=>$custom_post) {
            if ($custom_post->_builtin == false && $type == "team_member") {
                $slug = str_replace('/', '', $custom_post->rewrite['slug']);
                $rules .= 'RewriteRule ^' . $slug . '/(.+)$ /$1 [R=301,L]<br />';
            }
        }
        
        echo '<div class="error fade" style="background-color:red;"><p><strong>Remove Slug Custom post type error!</strong><br />.htaccess is not writable, please add following lines to complete your installation: <br />'.$rules.'</p></div>';
    }
}//End JAFTY_CPT_SlugKiller class to remove slugs from team_member CPT

//actions and hooks for above class to remove slug from team_member CPT:
add_action('init', array('JAFTY_CPT_SlugKiller', 'init'), 99);
//the following two lines make it so you don't have to manually go to settings/permalinks and re-save settings for links to work:
register_activation_hook( __FILE__, array('JAFTY_CPT_SlugKiller', 'flush_rewrite_rules') );
register_deactivation_hook( __FILE__, array('JAFTY_CPT_SlugKiller', 'flush_rewrite_rules') );
//END CODE TO ENABLE NO SLUG FOR team_member CPT

?>

The above code can be added to a plugin file or your themes functions.php.

NOTE: although the above code hasn't been thoroughly tested on non-nginx servers, it should work if you un-comment the two lines that call the add_rules_htaccess function. Simply do a search for "add_rules_htaccess" and remove the "//" before it in two occurrences and this code should work on any server as long as your .htaccess file is writable.

Building a Custom WordPress Navigation Menu Plugin

This is a semi-advanced WordPress tutorial so you should have a little bit of existing knowledge of WordPress if you want to be able to understand the concepts involved. I will try to make it as easy to follow as possible none-the-less.

We are just going to dive right in a create a new Plugin. I'll be calling the plugin Jafty-Nav, you can follow suit if you wish to keep things simple or give it your own name if you feel comfortable making such changes.

Create a New Plugin

<?php
/**
* Plugin Name: Jafty Top Nav Plugin
* Plugin URI: http://jafty.com/blog/?p=9813
* Description: A Plugin that adds a custom top navigation menu to WordPress.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

Register a New Menu Location with WordPress

Add this PHP code to your plugin file you created above:

<?php
add_action('after_setup_theme', 'register_jafty_menu');
function register_jafty_menu(){
  register_nav_menu('jafty-top-nav', __('Primary Jafty Menu', 'jafty-top-nav-plugin'));
}
?>

Now that is actually enough to create a simple plugin. The plugin will add a menu location to wp-admin and that's it, but we'll build on it after we install it. So go ahead and install the plugin by putting it into a folder named "jafty-top-nav-plugin" and naming the file "index.php". Then upload to your WordPress plugins directory. Activate the Jafty Top Nav Plugin then go to your admin and click on "Appearance/Menus" then select the "Manage Locations" tab and you'll see the new menu location your plugin as added to the admin like in the image below.

menuLOC

Placing a new top nav in your theme

The next task is to edit your current WordPress theme to work with the Jafty Top Nav Plugin. You'll need to create a new header file and edit your page, post and/or home page templates to contain your new top navigation menu. Here is how:

  1. Go into your current theme's folder and download a copy of the header.php file to your desktop and rename it header-jafty.php.
  2. open header-jafty.php in notepad and find the section that looks something like this:<nav id="site-navigation" class="main-navigation" role="navigation">
    <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'outer-gain-dev' ); ?></button>
    <?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu' ) ); ?>
    </nav>
  3. Inside the code within the Nav tag in your header-jafty.php file, change the theme_location value to 'jafty-top-nav' and save the file.
  4. Now upload your header-jafty.php file to your active theme's folder.
  5. Next you'll want to add the new header to your template files, Some templates you might want to do this too are front-page.php, single.php, page.php and any custom page templates in your theme or child theme you might have. The process is very similar for adding the new header to any of the files, so I'll just demonstrate on the home page template file, front-page.php. Open the template file in your notepad and near the top of the code you should see something like this:
    get_header();
    or you may have something like this instead:
    get_template_part('templates/header.php');
    Regardless which you have, replace the line with:
    get_header('jafty');
    and that will call your new header.jafty.php template into the page template so your customized header will be shown.
  6. Save and upload your altered template file and repeat for all necessary page and post templates until you have your new top nav menu at the top of all desired pages and/or posts throughout your entire WordPress site.

Now that we have more control of it, let's customize that ugly top nav!

Customizing the WP Navigation Menu

It's time to get down and dirty with some real-world customization of the top navigation menu in WordPress. We are not just doing some simple CSS changes here, we are talking about a complete rewrite of the navigation system. This is why I went with a plugin for this. Now I had to find what WordPress core functions I could use to alter the menu completely. My goal is to make a menu similar to the one at Stripe.com, which is not a WordPress site by the way. I just love the dynamic drop downs that fade in and out and their use of icons in the sub-menu items. I'll get to how I duplicated all of that later on, first we need to know how to rebuild the entire menu structure because the stripe.com style menu is nothing like a standard WordPress menu. Here's what I figured out:

 

First we need to be able to retrieve our custom navigation links from the WordPress backend. Remember earlier we created a menu location? Well, we need to retrieve the menu assigned to that particular location in WordPress. Therefore the first thing we want to do is make sure there is a menu assigned to the "Primary Jafty Menu". You could pick one from the drop down, but we want to make a new one that is sure to have both main menu items and sub menu items so we can adequately test our menu when it's complete. Therefore we locate the "Primary Jafty Menu" and click the link to the right of it that reads "Use New Menu" as I've circled in red in the below image:

menuLOC2

When creating the new Primary Jafty Menu, give it a name of "Jafty 1". It's best to do everything exactly as I have done just to be sure you don't have any conflicts. You can always change names and such after you have a completed working plugin. When creating the menu, make sure to add at least 2 main menu items with at least 2 sub menu items each so we can test the drop down effects. Here is an image of the one I made for testing. If you don't have enough pages or posts to make that many links, don't worry, just use two real links for the main menu items and click on "custom links" and create outside links for all of your sub menu items as I have done in the below image:

menustructure

In the above image, "site settings" and "Hello world!" represent our two main menu items and the sub links rest below them indented to show their sub-link status. Notice I have "Primary Jafty Menu" checked under "Menu Setings" too. Once you have your menu, be sure you save it. Now we can return to developing our plugin!

Retrieve Menu and Sub Menu Items from WordPress Admin

It is time to develop some custom WordPress code to extract out menu items and sub-menu items from the database. Lucky for us, WordPress has some built-in core functions to assist us. Here is the code I come up with to extract all menu and sub-menu items for the "Jafty Primary Menu" from the database to display them on the front-end:

<?php
      $menuLocations = get_nav_menu_locations(); // Get nav locations
      $menuID = $menuLocations['jafty-top-nav']; //menu assigned to Jafty Primary Menu
      $theNav = wp_get_nav_menu_items($menuID);
                
                    foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }
 ?>

The above code will go in out header file named header-jafty.php. Lets examine the code so you understand what it does.

The first line:

$menuLocations = get_nav_menu_locations(); // Get nav locations

as the comment says afterwards, it gets the navigation menu locations stored in WordPress. We added one of these in the beginning of the tutorial using the register_nav_menu function.

The second line reads:

$menuID = $menuLocations['jafty-top-nav']; //menu assigned to 'Primary Jafty Menu'

This line fetches the ID of the menu currently assigned to the menu location we created in the plugin file, "Primary Jafty Menu". We then use the id in the next line that reads:

$theNav = wp_get_nav_menu_items($menuID);

We now have a WordPress menu object stored in $theNav. If you do a print_r($theNav) command in PHP, you would see that the menu object holds all sorts of information about the menu we created earlier. However, we only need four key pieces of information from the menu object. We need to get:

  1. The Link URL
  2. The Link Text
  3. The Link ID
  4. The Link's Parent ID in case it is a sub-menu item.

We can get the four pieces of information we need using a foreach loop on the $theNav object like so:

     foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }

We now have all the information we need about the menu items after running the above foreach loop on the menu object. We have the link text, URL, ID and Parent ID. It's important to note that the parent ID will always be 0 if the link is a main menu item and we can determine if the link is a sub-menu item if the parent ID is anything other than zero. Then we know which link to put the sub-link under by matching the sub-link's parent ID to the ID of the main link item. Pretty simply really, once you get accustomed to it.

Now we need to open our header-jafty.php file and find the line that reads something similar to:

<?php wp_nav_menu( array( 'theme_location' => 'jafty-top-nav', 'menu_id' => 'primary-menu' ) ); ?>

And replace it with the code we wrote above:

<?php
$menuLocations = get_nav_menu_locations(); // Get nav locations
$menuID = $menuLocations['jafty-top-nav']; // Get the *primary* menu ID
$theNav = wp_get_nav_menu_items($menuID);

foreach ($theNav as $navItem) {
//get the url for the link:
$navURL = $navItem->url;
//get the nav link text/title:
$navTXT = $navItem->title;
//Get the nav link's ID:
$navID = $navItem->ID;
//Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
$navParent  = $navItem->menu_item_parent;
echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
//echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
}
?>

Now save your header-jafty.php file and upload it to your active theme's folder and refresh your home page. You should see the following information printed in the header area of your site instead of a top nav now:

ID: 47, Site Settings, 0, http://dev.outergain.com/site-settings/
ID: 49, Jafty Interactive, 47, http://jafty.com
ID: 50, Jafty Blog, 47, http://jafty.com/blog
ID: 48, Hello world!, 0, http://dev.outergain.com/2016/12/30/hello-world/
ID: 51, Yahoo Search, 48, http://yahoo.com
ID: 52, Google Search, 48, http://google.com

As you can see my site returned 6 lines of text in the header, one for each of the two main menu items and one for each of the four sub-menu items in the menu I created in wp-admin. Each of the lines above contains the main ID first, followed by the link text, then the parent ID and finally the link text. I highlighted the parent IDs in blue so you can see how the two main menu items have a parent ID of zero while the other four have parent IDs equal to the two main menu items with zero for parent ID. Make sense? I hope so:-)

For all you professional WordPress plugin developers, I can probably stop there. Now you have enough to make your own custom top navigation menu for your WordPress theme. You clearly don't need to do this as a plugin, in fact, it would normally done by adding the plugin code to functions.php in the current theme instead. I am making it a plugin just as a learning exercise.

You can use the information it printed in your header to figure out how to add in the HTML and CSS for any type of custom nav you desire, or you can read on to see how I recreated the stripe.com-like top nav for one of my clients.

Make a Static Top Navigation Menu as a Demo

Before we go about coding the menu into WordPress, I like to create a static version first. I created mine based on looking at the top nav found on Stripe.com. You can click the link to see what I mean. I didn't copy it by any means, but I did use it as a model for creating a similar one with similar transition effects. In the static demo, I didn't create great detail in the drop downs. Instead I concentrated on getting the transition effects and infrastructure perfect. I can worry about making the content of the dropdown boxes look pretty when I code it into the actual WordPress site. Here is my static demo: http://jafty.com/nav_demo

I won't post all of the code to my static navigation menu demo here but you may feel free to use the link provided and use your browser's view source option to see how I made it and copy it if you so desire.

 

 

 

WordPress now has Post Templates

Great news for some WordPress developers, WordPress version 4.7 recently came out with an exciting new feature! They now allow post templates similar to the way page templates work.

Activating Post Templates

To activate the new post template feature all you have to do is add your first post template. The one requirement to make them show up in the admin area on the new or edit post screen is that you have to add the following lines to the very top of your new template files:

/*
* Template Name: Your Post Template Name Here
* Template Post Type: CPT, names
*/

That's all there is to it! Make up a template name for the first parameter and use the Custom Post Type name or names for the second parameter, Template Post Type:.

Lets say you created a custom post type named "movies" and you created a template named movie-posts.php, then your movie-posts.php file would start out like this:

/*
* Template Name: Movie Posts
* Template Post Type: movies
*/

Then go ahead and add your loop and other code to your template file and when you upload it you'll see a new "template" drop-down appear under the attributes heading in the right column of the edit posts and add new posts screen for that custom post type:

postemp

Summary:

Note that this also works with ACF plugin or Advanced Custom Fields Pro plugin. That should explain it all. I hope this becomes as useful for some of my readers as it already has for me!

The WordPress Loop

Today I finally decided to dedicate a single tutorial on the wonderful WordPress loop. I will demonstrate how to create a basic loop and show several examples of the loop in action. The loop is what gets post and/or page data in WordPress template files, so if you ever have a need to make a custom page or post template, you'll need to understand how the loop works.

 

The Basic WordPress Loop

Most often you will see the loop look something like this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!------------This is where you present your post data....-------------->

<?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

The above example doesn't contain the middle part of the loop in order to demonstrate where the loop typically begins and ends. That way you can find the loop in your current theme and work with it by knowing where it starts and stops at least.  Next we'll discuss what to put in between where it says <!------------This is where you present your post data....-------------->.

Fetching Data Inside a WordPress Loop

Post Title:

First I'll show you how to display the Title as a link to the Post's permalink.

<h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

Just place the above code example where it says you present your post data in the the loop example above.

Post Content:

You can display the Post's content in a div with the following code inside of your loop:

<div class="entry">
<?php the_content(); ?>
</div>

Again, use the above code in between the starting and ending loop code explained above and this will display the general content of the post as entered into the standard WYSIWYG editor in the WordPress admin.

Using More Than One Loop

If you need to use two more more loops in the same template file, then you will have to reset the WordPress loop with rewind posts function like this:

<?php rewind_posts(); ?>

Just use the above line before your second loop and any loops afterwards and they will reset and be ready to function again.

 

Understanding IP Addresses

Have you ever needed to know how an IP Address works? Have perhaps just wondered how they worked? Well in my line of work it has eventually become necessary for me to fully understand exactly how IP addresses work and are made up. Therefore I aim to share my knowledge on such with anyone who cares to read about IP addresses here on my wonderful blog.

First of all it's important to know that IP addresses are displayed in what is known as dotted-decimal format. For example your current IP address is 23.20.166.142

For anyone Interested, I got your IP address using the following PHP code:

<?php
$ipaddress2 = $_SERVER[REMOTE_ADDR];
echo "<h3>Your Current IP Address: $ipaddress2</h3>";
?>

Just notice the format of the IP address above for now though.

Two Main Parts of an IP Address

While an IP address appears to have 4 parts due to the dotted-decimal format used, in reality, IP addresses are made up of only two main parts. They are "Network ID" and "Host ID". The two parts are not equal or consistent. The Network ID is defined first and the Host ID will be the remaining portion of the IP address.

IP Address Classes

IP addresses are divided into different classes. There are actually five IP classes, but only three are in common use, they are Classes A,B, and C. Classes D and E are reserved classes. Class D is Reserved for Multicasting. Class E is Experimental; used for research. The three main classes are shown in the following examples:

  • Class A - Class A IP addresses use 8 bits for the Network ID(8 bits = 1 byte or 1 segment in dotted-decimal format or 1 octet). Class A addresses only include IP addresses from 1.x.x.x to 126.x.x.x. The IP range 127.x.x.x is reserved for loopback IP addresses. Therefore a Class A IP address might look like 19.23.20.100. From what we know about the two parts of an IP address now, we know that the "19." portion of this example IP address defines the Network ID and the  remaining part(23.20.100) represents the Host ID.
  • Class B - Class B IP addresses use 16 bits for the Network ID(16 bits = 2 bytes or 2 segments in dotted-decimal format or 2 octets). The remaining 16 bits are used for the Host ID of course.
  • Class C - Class C IP addresses use 24 bits for the Network ID(24 bits = 3 bytes or 3 segments in dotted-decimal format or 3 octets). The remaining 8 bits are used for the Host ID in this case.

How to Determine IP Address Class

Determining whether an IP address belongs to class A, B or C can be a daunting task if you don't understand how IP addresses function. That is why I will explain it clearly here for you! First you need to realize that IP classes are determined by the first few bits of the IP address. Then you need to know that bits are not the same as the dotted-decimal format you are accustomed to! For example My IP address now shows as 173.6.69.165 if I open this post in my current browser. What class does 173.6.69.165 belong to? Well here is how I found out:

First, convert the dotted-decimal formatted IP address of 173.6.69.165 to its binary form and count the bits. Actually, you can do just the first octet or 173 in this case. Here is how to convert a decimal octet to a binary Byte:

You divide the number(173 in this case) by 2 and take the answer with the remainder and note both. Then divide the answer by two and note the answer and remainder again....do this eight times. Start at the top of a sheet of paper and move to a new line each time you start a new calculation.  Be sure to circle the remainder each time as those are the 8 bits that make up the Byte we are after. Here is my sloppy example of how I did it with my IP address that began with 173:

binarypaper_ink_li Notice that I circled the remainder after each division problem above. The final step is to start at the bottom and write each circled remainder down in order.

So from the image above, I get the binary number: 10101101

The first three bits of the binary 10101101 determine it's class. In my case, the first three bits are 101.

Then refer to the following table to determine your class:

  • CLASS A: the binary will begin with a zero.
  • CLASS B: the binary must start with 10.
  • CLASS C: the binary must start with 110.

So as you can see from the above table and the image above that, my IP address of 173.6.69.165 converts to a binary number of 10101101 and can then be identified as a CLASS B IP address because its binary form begins with 10. Alot to do to figure out the class of an IP, but it is mostly for learning purposes that I have explained it all like I have. Really, all you have to do is refer to the following table of information which will allow you to convert it to a class using just the first octet of the IP address(173 in my case):

Quick & Easy Method to Determine IP Class

  • CLASS A: First 3 digits of the IP address will be from 0 to 127.
  • CLASS B: First 3 digits of the IP address will be from 128 to 191.
  • CLASS C: First 3 digits of the IP address will be from 192 to 223.

So again, my IP(173.6.69.165) starts with 173 so I can use the above three lines of data to confirm that it is indeed a CLASS C IP address because 173 falls in between 128 and 191.

 

 

mysqli_result function to replace old mysql_result

Many of us are busy upgrading our PHP and MySQL code when migrating from PHP5 to PHP7. One of the first things you learn is that the MySQL functions have been depreciated and removed completely in PHP7, therefore can no longer be used! That's a major pain in the butt for many of us, but luckily the fix is not too difficult most of the time. Simply doing and find and replace replacing "mysql" with "mysqli" is often a good first step, but you will also need to add the connection variable as an argument to many of the mysqli functions as well. Then some functions, such as the mysql_result function, do not have a mysqli counterpart. That means there is no mysqli_function defined in PHP7! Real pain right? well copy and paste the following functino into your PHP code and you can now use the mysqli_result function effectively. Be sure to pass it the connection variable as most mysqli functions require even though mysql counterparts did not. Here's the function:

function mysqli_result($res,$row=0,$col=0){ 
    $numrows = mysqli_num_rows($res); 
    if ($numrows && $row <= ($numrows-1) && $row >=0){
        mysqli_data_seek($res,$row);
        $resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
        if (isset($resrow[$col])){
            return $resrow[$col];
        }
    }
    return false;
}

Find a file using Linux find Command

If you need to find a file anywhere on a server, what directory it is in or not, the Linux Find command is your go to command! Here are some basic usage cases:

Find a file in the current directory:

find . -name "this-file.php"

Find a file anywhere on the server above the root directory:

find / -name "filename.php"

Notice in the first example we used a period and in the second we used a forward slash. The period means to search the current directory and the forward slash means to search from the root directory and will basically find a file anywhere on the file in the root directory or any of its sub-directories.

Perform a case-insensitive search:

The above commands all use the -name parameter which performs a case-sensitive search. To perform a case-insensitive search, replace -name with -iname in the above examples, like so:

find / -iname "filename.php"

Perform a wildcard search:

The wildcard character is *. If you want to find all .php files, for example, use the following command:

find / -iname "*.php"

 

 

How to change DNS settings on your local PC

Have you ever been working on a website, changed your DNS settings over to a different server and later needed to access that server again from the old domain name for some reason? Well if you are an active developer, this situation is somewhat common. I'll explain or you can skip the rest of this paragraph to quickly learn now to do it. Let's say you own the domain name example.com and a web server with an IP address of 111.111.111.111. Now assume you have a WordPress blog on that server that you had to move to another server with IP 222.222.222.222. Let's say you already changed the DNS settings for domain.com to point to the new server with IP 222.222.222.222 but you need to go back to the original WordPress site on the other server with an IP of 111.111.111.111. What do you do? We all know a WordPress site won't function properly with just the IP address, so that is out. What you need to do is repoint example.com to 111.111.111.111 in order to access that WordPress site again. What a PITA, right? Well read on and I'll show you a fast and easy way to make the site on the original server work with example.com even after you've pointed it to another IP address or web server! It's as simply as controlling a local host file on your local PC to make example.com route to 111.111.111.111 even though the internet routes it to 222.222.222.222! Here's how:

Using hosts file to override DNS settings for your PC

A lot of people don't realize that when you make a request to the Internet using your local computer it first checks a local copy of the hosts file for an entry and only if one isn’t present it goes out to the Internet DNS servers. Therefore there's an opportunity present for you to redirect example.com only for your own PC if you wanted to! Here are the easy steps:

  1. Open file explorer and navigate to C:\Windows\System32\drivers\etc.
  2. Open the file named "hosts" in notepad or another text editor that could be used as a code editor such as Notepad++, which is what I use.
  3. Now simply add a line to the end of the hosts file that contains the IP address of the server you want to route the domain name too followed by a space and then the domain name you want to reroute. So in our example scenario above, you would enter a new line that reads simply: 111.111.111.111 example.com
  4. Save the hosts file and open your browser and navigate to the domain which in our example was example.com. Note that there is a difference between example.com and www.example.com, so if you want it to work with www, you have to add another entry for www.example.com.

If you're using Notepad++ or similar as I was, you'll need to open it in administrator mode in order to be able to save the hosts file. Good luck! That's all there is to it.

How to change local DNS settings on a Mac

If you're on a Mac, the instructions are basically the same but do this instead:

From the terminal, type:

nano /private/etc/hosts
and then add the IP and domain name as described above, so the only real difference between Mac and a PC when it comes to changing DNS settings is that you will use a different editor and the hosts file is located in different places.

 

 

How to Use IPTables

What is iptables?

iptables is a fairly flexible firewall system developed for Linux/Unix operating systems and used commonly for web server administrators to block access to servers by IP address or groups of IP addresses. It can also be used to white-list IP addresses as well. It is a command line tool that allows server administrators to enter simply one line commands to add, edit or delete rules for accessing the web server from the outside world.

Understanding iptables Infrastructure

Understanding the infrastructure of iptables in an important component to learning how to use iptables. Basically there are tables, chains and rules. Tables contain chains and chains contain rules. Here is a simple graphic to illustrate my point:

iptables

There are four default tables in iptables and you can add others if you want to get deep into config options. However, I recommend using the default tables to keep things simple. In fact, the filter table is the only one we will be messing with for now. The four default tables are filter, nat, mangle and raw.

  • Filter Table - default table for iptables. If you do not define a table, you’ll be using the filter table. The filter table has the following built-in chains:
    1. Input Chain - handles incoming connections.
    2. Output Chain - handles outgoing connections.
    3. Forward Chain - handles routing of connections like a router.
  • Nat Table - Consists of prerouting, postrouting and output chains. The prerouting chain helps translate destination ip address of the packets to match the routing on the local server. The postrouting chain translates packets as they leave the system and alters packets after routing. The output chain is NAT(Network Address Translation) for locally generated packets on the firewall.
  • Mangle Table - for specialized packet alteration. We will leave this table alone for now as it it outside the scope of this tutorial, but just know it is there.
  • Raw Table - for configuration exemptions. Raw table has a prerouting chain and an output chain.

Chain? WTF does my server need Chains for? Is it winter already?

When using iptables, there are basically three types of chains that we are mainly interested in. They are input chains, output chains and forward chains, the three chains from the filter table described above.

  • Input Chain - used to control the behavior of incoming connections. For example, if a user attempts to SSH into your server, iptables will attempt to match the IP address and port to a rule in the input chain.
  • Output Chain - used with outgoing connections. For example, if you try to ping jafty.com, iptables will check its output chain to see what the rules are regarding ping and jafty.com before making a decision to allow or deny the attempt to connect.
  • Forward Chain - used for incoming connections that aren’t delivered locally. It is something like a router where data is always being sent to it but is not destined for the actual router. Data is forwarded to its target. Unless you’re doing some type of routing or NATing  that requires forwarding, you probably won't use a forward chain much if at all.

Understanding iptables Commands

In order to use iptables in Linux, you need to know the basic commands, so I'll go over some of the more common iptables commands here for your learning pleasure!

Note that after you make any change, it is important to save iptables with the following command on Debian/Ubuntu servers:

iptables-save

or in some cases

/sbin/iptables-save

The save command is a little different for other servers, so take note of the one that applies to your server as noted below:

  • Centos / Redhat: service iptables save or sudo service iptables save if you are not root user.
  • If that didn't work, try:  /etc/init.d/iptables save with and without sudo first.

If you don't save after a change by typing the above at your command prompt and hitting enter, you will most likely lose your changes and/or they will never take effect.

iptables Command to Block a Single Simple IP address

If you wish to simply block an IP such as 206.190.152.176 from accessing your server in any way and from any port, type this at your command prompt and press enter, then save:

iptables -A INPUT -s 206.190.152.176 -j DROP

Whenever possible, always test to be sure your iptables rules work after adding then to be safe. Be sure to save using the appropriate iptables save command as mentioned above after you successfully enter your new rule.

Blocking all IP addresses but your own with iptables

If your server is getting throttled and you want to lock it down immediately or you are simply under construction and don't want anyone but you to be able to access your server, here is how you can block all IP addresses from accessing your server and white-list just one or more IP addresses that will be able to access your server:

iptables -A INPUT -s 0.0.0.0 -j ACCEPT
iptables -A OUTPUT -d 0.0.0.0 -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT DROP

First, you should flush your current rules(see below). Then simply replace 0.0.0.0 with your own IP address in the commands above and enter each of the four commands one at a time from the command line, pressing enter after each, then save iptables.

Flushing iptables rules

To get rid of all active rules in iptables, enter the following command at the Linux command prompt:

iptables -F

Deleting Single iptables Rules

If you entered one or more iptables rules you want to delete without deleting the entire configuration, here is how to do it:

  1. List numbered rules using this command: sudo iptables -L INPUT -n --line-numbers
  2. To delete the first rule enter: sudo iptables -D INPUT 1(where 1 is the line number you want to delete)
  3. Confirm deletion took place by running the first command again and verify the rule is no longer present: sudo iptables -L INPUT -n --line-numbers
  4. Save iptables to be safe: sudo iptables-save

 

Restrict Number of Connections Per IP

Use connlimit to place restrictions on the number of connections allowed per IP address. To allow 4 ssh connections per client host, enter:
# iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 4 -j REJECT

Set HTTP requests to 20:
# iptables -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j DROP
Where,

  1. --connlimit-above 3 : Match if the number of existing connections is above 3.
  2. --connlimit-mask 24 : Group hosts using the prefix length. For IPv4, this must be a number between (including) 0 and 32.

 

What is this nonsense after the slash in iptables ip addresses?

This is what I need to touch on before we go much further because you've no doubt seen existing rules in your iptables with IP addresses listed similar to:

188.0.0.0/8
or:
192.12.0.0/16

...and have surely wondered why there is a slash followed by a number after the ip addresses listed in your iptables rules. Well I'll explain as best as I can in the next section as it is a little complicated to explain...

Knowing how to read and write more complex iptables rules with CIDR notation.

Learning to write iptables rules can get very frustrating if you don't understand how the notation works. CIDR, Classless Inter Domain Routing notation, is often confused with network masks which are similar but not the same. I will offer my best explanation of CIDR notation here which I've gathered from several different sources to put together an explanation I feel comfortable with:

Imagine an IP address something like xxx.yyy.zzz.www/N, where N is the number of bits from 0 to 32. Each of the other numbers represents one byte out of the 4 bytes that make up an IP address. N says how many BITS of those 4 bytes matter. So any address that looks like 10.X.Y.Z/8 refers to ANY IP starting with "10.": 8 bits = 1 byte, meaning everything after the first byte is ignored. The convention is to use zeroes in the ignored positions, so the canonical name for that subnet is 10.0.0.0/8. Most of the time, N is a multiple of 8, so it says to ignore a certain number of bytes.

Once in a while, you'll see something other than that, like a /29. This means that PART of one of the bytes is ignored. For simplicity's sake however, we will stick to multiples of 8 in this guide.

It's also important to note that if the N is omitted, then it's usually assumed to be 32, i.e. a single IP address specification.

So, taking what I've just explained above regarding CIDR notation, Here are some general examples of how netmasks work in conjunction with iptables rules:

10.0.0.0/8  - A CIDR of 8 bits means that only 1 of 4 possible bytes of the IP address is noted as represented by the "10" here. so this would cover the IP range from 10.0.0.0 to 10.255.255.255. In other words any IP address starting with "10.".

100.50.0.0/16 - A CIDR of 16 means that 2 of 4 possible bytes of the IP address are noted as represented here by "100.50.". In this case, a range from 100.50.0.0 to 100.50.255.255 is covered.

92.50.8.0/24 - A CIDR of 24 means that 3 of the 4 IP address bytes are noted as seen here with "92.50.8." This time a range from 92.50.8.0 to 92.50.8.255 is represented.

Those should be the three most common types of CIDR notations. Following the above pattern of incrementing the number of bits by 8, the next logical example would be something like 92.50.8.210/32. While that is a perfectly good notation and will work, it is also moot because 32 bits would represent the entire IP address, so you might as well enter it without the CIDR notation(with no slash and number after the IP).  In iptables rules, 92.50.8.210/32 means the exact same thing as simply putting 92.50.8.210.

What do Bytes and Bits have to do with IP Addresses?

Good question, glad I asked myself! To properly understand how CIDR notation works you have to understand the math behind it. A Byte is made up of 8 bits(that's why we increment by 8 in our previous examples). An IP address is made up of 4 Bytes or 32 Bits(4x8=32).

As you probably know, an IP address is made of of four numbers separated by dots or periods(.) like this: N.N.N.N where N can be any number from 0 to 255. This raised a question in my mind: In an IP address byte, how does a range from 0 to 255 have 8 bits? Well my question just goes to show I don't fully understand how Bytes and Bits correspond with numbers because I googled around and discovered that indeed Eight binary bits can represent any whole number from zero to 255, so the segments of a dotted decimal address are decimal numbers with a range from 0 to 255.  I think it's enough for now to understand that it is correct without getting into exactly how Bytes and Bits work with IP addresses because I don't want this tutorial to confuse you even more. Let's just know for now that 1 Byte = 8 Bits and that a Byte can be any number from 0 to 255 in an IP address which is made up of 4 Bytes and/or 32 Bits. If anyone would like to explain how this works in more detail, feel free to make a comment on this post and I'll make sure it gets published.

wp_redirect Causing Page Isn’t Redirecting Properly Error

I was working on a client's WordPress website today and had to do a redirect after successful login to his WordPress site. I tried to use wp_redirect with several different hooks including init, wp, wp_login, wp_redirect....etc. and none worked. I kept getting an error in Firefox that looked like this saying "The page isn't redirecting properly....Firefox has detected that the server us redirecting the request for this address in a way that will never complete:

redirecterr

The Solution

So, in short Here is my solution. While I'm sure there may be another better way, this is the only one I found after two hours of trying to use wp_redirect. I simply used this line in place of where I would normally use wp_redirect:

echo "<script>document.location = '/my-account/';</script>";

So I essentially insert a JavaScript redirect into the page using PHP. Hackish? Yes, but it works and hopefully this post will save someone hours of wasted time trying to get wp_redirect to work!

 

Cron Job Not Working

Cron jobs seem to be one of the things I have to do often that give me trouble. That's why I'm putting together this guide full of troubleshooting tips for people having problems with cron jobs.

Just today, for example, I wasted several hours figuring out why my cron job didn't seem to be working and here is what happened:

I set up my cron job exactly as I always do according to my own tutorial I posted here:

Linux Cron Job Tutorial

however, it didn't seem to be working so I tried chaing the shebang, changing the php location, etc. with no luck at all.

The Solution

Finally after hours of wasting time, I figured out that the output of my cron job was not going where I thought it would go. For example, my test script created a file and wrote a line to that file to show the cron job ran. My cron test PHP file looked like this:

crontest.php:

<?php

#!/usr/bin/php
<?php
$myFile = "cronresults.txt";
$fh2 = fopen($myFile, 'a') or die("can't open file to append");
$stringData = "appended text from cron job...\n";
fwrite($fh2, $stringData);
fclose($fh2);
?>

Simple, right? well the trick is the $myFile variable works as expected in that it creates the file in the same directory as crontest.php when crontest is called from a web browser. So when I opened up Firefox and went to mysite.com/crontest.php, it worked fine, it would create a file named cronresults.txt in my public_html folder and write a simple line of text to it. However. HERE IS THE TRICKY PART! I call the script in crontest.php from a cron tab by adding the following line in crontab -e:

* * * * * /usr/bin/php   /var/www/mysite.com/public_html/crontest.php

but when I call it that way and look for the cronresults.txt file or look for the line of text it added to the file if it already exists, there is nothing so it appears as if the cron job didn't work! Oh damn! I say. Then I try everything I can think of to fix it. The problem is that is was never broken! When you call a PHP script from a cron job and you do not specify the file path of the results file, it assumes the current users home folder! Therefore, it was working the whole time, but was creating and writing to a file in my /home/root directory because that's the directory I called crontab -e from! THerefore my solution was as simply as replacing the $myFile line with this:

$myFile = "/var/www/mysite.com/public_html/cronresults.txt";

WHEN YOU USE THE ENTIRE PATH IT WORKS AS EXPECTED! I can't over emphasize the importance of this because I wasited several hours due to not knowing this.

Cron Job Troubleshooting Tips

  • Always use a simple test script to test cron jobs for the first time on a new server. You can use my example crontest.php script above, but be careful to set the $myFile variable with the entire path to the output file or you'll have the same problem I wrote about above in this post.
  • Always use a very simple command line in crontab when first testing your cron job. You can customize it after you get it working. I use something like:                               * * * * *  /usr/bin/php  /path/to/cron/crontest.php      then crontest.php will be executed every minute so you can quickly see if it is working. This makes testing and debugging much easier.
  • Can't figure out your Shebang or don't know where PHP is on your server? Then simply go to a command prompt on your server using putty remotely or any command prompt if you are on your own server and type the following command: "which php" without the quotes. That will give you the path to php for both your shebang and your crontab file, like where it says /usr/bin/php in my examples above.

How to Use PHP SESSION Variables in a WordPress Plugin

I was writing a WordPress plugin today that required me to use PHP SESSION variables so the app could save variables across multiple runs of the application. So at first, I tried using SESSION variables in my PHP code just like I would with any other PHP application outside of WordPress, but it failed. So read on for the solution I found that works perfectly and is as simple as adding three lines of code to your plugin or functions.php file.

Add this code to your main plugin file or theme's functions.php file:

function register_session(){
    if(!session_id()) session_start();
}
add_action('init','register_session');

Those four magic lines of code was all I had to add to my main plugin file to make the following code work:

<?php
// Start the session
session_start();

    if(isset($_SESSION['timesran'])){
        $_SESSION['timesran']++;
        $runno = $_SESSION['timesran'];
    }else{
        $runno = 1;
        $_SESSION['timesran'] = 1;
    }
    echo "Run number $runno<br />";
    ?>

So each time the WordPress plugin's application is ran, it increments the timesran session variable successfully as long as I have already added the previous code snippet above to my plugin's main file. The register_session function is needed for sessions to work and should be in your plugin's index.php file or whatever file is your plugin's main file. You can then use PHP session variables in any file within your plugin.

 

How to Restart a Web Server with PHP

Today, I had the task of having to write a PHP script that restarts a web server. This is not allowed by default. It should be noted before I continue, that it is not allowed because it opens a security hole. It makes possible a server attack that would lock up your server by constantly restarting it from PHP. However, now that you're aware of the risk, if you still wish to continue. Here is how it is done:

PHP Code:

    if(exec("sudo service nginx restart")) {
            echo "server restarted!<br />";
        }else{
            echo "ERROR! Server failed to restart!<br />";
        }

Test the above code. NOTE: it is likely not to work because normally you will have to edit the sudoers file on the server.

Edit the Sudoers File to Allow PHP to Use the Restart Command

On the Linode/Nginx server I am working on currently the sudoers file can be found at /etc/sudoers. It can be found in a similar location on most Linux servers. In order to edit the sudoers file on a Linux NGINX server, simply open the file and add the following to the end of the file and save it before restarting the web server:

www-data ALL=(ALL) NOPASSWD: /usr/sbin/service nginx start,/usr/sbin/service nginx stop,/usr/sbin/service nginx restart

Note that your server may require you to edit the sudoers file with visudo. If you have root access with Filezilla, you can go to /etc/ folder and download the sudoers file then edit it with notepad or notepad++ as I do.

For reference only, here are all the commands I added to sudoers file to get it to work with the site creation app that used the server restart function above:

#Ian added to allow www-data user to run nginx restart command:
www-data ALL=(ALL) NOPASSWD: /usr/sbin/service nginx start,/usr/sbin/service nginx stop,/usr/sbin/service nginx restart

#Ian added following line to allow the site maker app to change permissions of sites to 777 before deleting them:
www-data ALL=(root) NOPASSWD: /bin/chmod -R [0-7][0-7][0-7] /var/www/*, /usr/bin/chmod -R [0-7][0-7][0-7] /var/www/*
www-data ALL=(root) NOPASSWD: /bin/chmod [0-7][0-7][0-7] /var/www/*, /usr/bin/chmod [0-7][0-7][0-7] /var/www/*
www-data ALL=(root) NOPASSWD: /bin/chown www-data\:www-data /var/www/*, /usr/bin/chown www-data\:www-data /var/www/*

Summary

So there you have it, you can now restart your NGINX server from a PHP script. I put the command in an iframe so it wouldn't mess with the page I was on because when the restart command works, you'll get a connection reset notice or something similar from your browser...

 

 

Find and Replace All Occurrences of a File on Linux Server from Command Line

Today I was given the challenge of providing a client with a command line command that would allow my client to replace all occurrences of any file named this-file.php with a new file with the same name that resides in the server's root directory. Here is how I accomplished the challenge with a single line command from the Linux command prompt:

find . -name "this-file.php" -print -exec cp this-file.php {} \;

What we have there is basically two commands in one. First is the command to find all occurrences of this-file.php on the server and display the results. I have it displaying results so you can verify what files were replaced in the end. So, the command to just find all files named this-file.php and list them is:

find . -name "this-file.php" -print

Type the above command at your Linux command prompt and you'll get a list of paths found to files with the name this-file.php.  However, it should be noted that the above command is the command to use if you are in the base directory of your server, otherwise you will want to specify the root directory. In the above command, the '.' (period) means to search in current directory. So if you're not in the curent directory, use something more appropriate such as a / instead of a . so it forces it to search all directories above and including /. Try this:

find / -iname "this-file.php"

That is a safer command than the first because it doesn't matter what directory you call it from. Notice we also didn't use the -print parameter at the end this time. It is actually moot because it will print the results anyway. It was included in the first example to explain it's use in the find and replace command, but is not needed when find is used by itself.

The second part of the challenge was to replace all those files listed with a new version of the file stored in the root directory. Therefore, before we go any further, we need to change into the root directory or whatever directory you will use to store the new file that will be used to replace all of the other files with. So change directories with the cd command like this:

cd /

That changes you into the root directory where you can go ahead and upload your new file if you haven't done so already.

Next is the command to copy this-file.php and overwrite the old version of the file. As long as you use the same file name, this works out-of-the-box with Linux. The simple command to copy a file from the root directory to a website's sub-directory might look something like this:

cp this-file.php /var/www/amykukuck.com/public_html/wp-content/themes/oily-sites-wide/templates/this-file.php

Combining two Linux Commands into One Line

The final part of our challenge is to combine the two commands we have learned above into one simple command to find and replace all occurrence of the file named this-file.php with a new version of it stored in the root directory that has the same file name. Here are the two commands combined:

find . -name "this-file.php" -print -exec cp this-file.php {} \;

Notice the find command which ends with -print looks the same. Then the find command is followed by -exec and then the cp command. Finally the combined command ends with {} \;. That last part has two functions. The brackets, {}, are used to replace what is found by the find command each time it finds something. The \; part lets Linux know the command is done and it can stop. Please note that for this to work the way it is written here, you must change directories into the directory that contains the new file in which will replace all instances of the file with the same name elsewhere on your server. So, be sure to execute the combined command only after changing into the correct directory which contains your new file!