Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

Online Marketing in 2018

2018 is now upon us and the web is still steamrolling as the best place for online marketing. Since Internet marketing and can make or break a business, I have come up with a plan that can be used to avoid pitfalls and generate useful leads.

The 7 topics of Internet marketing discussion are SEO, SEM, content marketing, social media, ppc, Google Business Listings and Structured Data Markup. Since every website will receive traffic from various sources at different rates, I have put forward a list of the top places where you can make a presence and attract visitors and friends.

SEO

SEO in 2018SEO is the short hand term for search engine optimization. Most people online know the meaning of seo and tend to have a wanting to rank high organically with the search engines. With proper coding, text, images, links and document structure, this can be a pretty straightforward procedure from the start. But, it can be tricky and patience is required.

Although the ultimate outcome cannot be achieved overnight, you can acquire excellent results relatively quickly. It helps to have strong writing, coding and reporting skills in order to have an edge of the competition.

When pages are built to gain organic traction, you must remember to test for local terms to hit the desired audience. For example, a recent survey explained that 17% of people searching don’t use a local term. It also explains that 21% of youth do and a whopping 63% of older searchers do add a local term. Keep that in mind; especially if your market is an older audience, or maybe someone who prefers using a local modifier as the results without one are often irrelevant.

SEO just not mean just pleasing Google. For example, in Canada you can find estimates that ~21% of searchers use Yahoo and another 9% use Bing; which are both owned by Microsoft. Essentially, the combination can be attributed to almost 30% of web surfers. This may be slightly less than half of the queries that Google receives, but they do cater more to SEO techniques like content writing and proper coding than does Google.

Therefore, always make Yahoo and Bing a high priority because they will grade your documents an ‘A’ like a teacher while Google can make it very hard to show up and conquer the established competition. Even though that is just the way it is, your efforts will be rewarded from them too, although a different process.

SEM and PPC

sem 2018Search engine marketing and pay per click advertising can be implemented immediately in various forms. Typically, they are paid ads which are displayed when someone browses the web using specific keywords.

The ads can be used to display broad matches, phrase matches and exact matches. In addition, you can add negative keywords like free so that when people search for ‘tacos in Anaheim’ they will find you, but when they search for ‘free tacos in Anaheim’ they will not.

In rural areas, Adwords and Bing Ads are typically much more affordable and it is cost efficient to get to the top and stay there.

Asides from traditional search ads, joining paid directory websites and others listings can bring in referral traffic too.

Content Marketing

2018 content marketingIn general, I see online content marketing as a writer’s dream, and the most common source of marketing weakness in most websites. For whatever reason, whether it reminds someone of those dreaded University papers or a high school dropout that hated writing anything down, people just tend to want to avoid doing this and it looks as though they would rather save their writing bursts for social media where social wording is natural, short and sweet.

Since content marketing works well in all search engines; especially Yahoo and Bing which seems to make coding and content a priority, one should use this method to grab the bull by the horns and go to uncharted territory.

But, this method does not best as a marathon, rather than a short sprint. As a site is updated regularly, search engines will take notice. You will likely find that other pages and your site as a whole will show traffic increases that resemble a hot trading stock. Take away the momentum and it can drop the other direction.

Thus, creating content regularly is a key. In fact, once or twice a week is not overdoing it.

Social Media

social media marketing 2018Social media is a great place to build awareness. Again, there are some tricks to making social media be effective. Posts should be published often, and local ads and posts can be boosted from time to time as a mixture of organic and paid advertising will get the word out; especially if people follow your page.

Google Business Listing

Google Business listingFor any established business or new business, building a Google business listing should be automatic.

Structured Data Markup Helper

Adding Structured Data Markup to your websites can allow for alternative presentations when your site is crawled; such as displaying future events. There are various formats that can be used to display your results, but one stands out; JSON-LD. JSON-LD is a simple snippet of JSON that can be added inside script tags. The two links below can be used to create and test the markup.

https://www.google.com/webmasters/markup-helper/
https://search.google.com/structured-data/testing-tool

This post will explain how to link images, header and footer files across all folders. For example, let’s say you want to create a subfolder for seo purposes. In this case, let’s create a new folder called new-york. Meanwhile, our files in the root folder had all the css, images and javascript. Since the plan is to keep the same look, we only want to use the header and footer file from the root folder and allow those links to work perfectly.

However, if you do this and include the header to the subfolder with ‘include(“../header.php”);’, it will include that file. The issue is that the default path for the the files in the subdirectory will not link up because the path takes on the folder of the file in the new-york directory.

Luckily, there is one easy trick to allow everything to work flawlessly, thus, you only need one file in the new-york folder to utlize all css, images and js of the root folder. The simple line of code is the self closing base tag. An example is shown below with a line of code that can be added to the file in the new-york directory.

Do note that placement is critical. It should be positioned above all links to css and js; otherwise any links above it will use the path in the current directory. Both examples shown below will work.

<base href="example.com" />

 

<base href="/" />

As a Linux enthusiast, particularly Ubuntu for home pcs, I had decided to write this article to explain why I have really taken to Ubuntu Mate. If I could sum it up in two words, it would be Ubuntu compatibility.

Several years ago, I had an old HP laptop that came with Windows Vista for which I wanted to install Ubuntu. After installing Ubuntu 12 and 14, the graphics did not not work properly out of the box. Even with some tinkering, there was issues. But, when I installed Linux Mint, it worked fine.

However, I had used Ubuntu extensively throughout the years and really liked the forums, always kept a copy of the book ‘Ubuntu Unleashed’ close to my workstation and was brand faithful. Thus, although I liked a lot about Linux Mint, especially the GUI, it always felt like I was substituting for my favorite Linux flavor.

Hence, if you have a Linux background, you may know what I am about to say next. When I first installed Ubuntu Mate 16 in the same old laptop, everything went perfect. In addition, I really liked the GUI and color scheme.

Since then, I bought several old laptops at auctions and have installed them without any issues as well.

Finally, my new Raspberry Pi3. I bought a new 16GB micro SD card and installed the Ubuntu Mate image designed for the Raspberry Pi. Again, I was very impressed how well it performed.

That’s it, my little story about Ubuntu Mate and why I have it in four of my pcs.

The idea here is to run a Linux cron job to reset a mySQL database at the desired interval. In the case of this tutorial, the interval is every two hours.

The code below clearly shows how this can be done in its entirety. It is a cron file for the user named myUser. Although it appears that it has 4 cron sections, note that to are commented out. Also, note that the top two lines of cron commands and bottom two are for 2 different databases.

The top two cron jobs have backticks with backslashes that are required for database names with hyphens, but the latter two lines use underscores where they are not required.

So, you may notice that the top line that is commented out is nice and easy. But, you may also find that it is only useful when you want to dump data into an empty database. Thus, the uncommented option, will run two mysql commands that drop and create a database for the desired user ‘myUser’, then dumps the data from a sql file into the database.

That is all there is to it.

SHELL=”/usr/local/cpanel/bin/jailshell”

#0 */2 * * * mysql -u myUser -pmyPassword myUser_my-DB < /home/myUser/cron/db.sql >/dev/null 2>&1

0 */2 * * * mysql -u myUser -pmyPassword -e “DROP DATABASE \`myUser_my-DB\`; CREATE DATABASE \`myUser_my-DB\`”;  mysql -u myUser -pmyPassword myUser_my-DB < /home/myUser/cron/db.sql >/dev/null 2>&1

#0 */2 * * * mysql -u myUser -pmyPassword myUser_my_db < /home/myUser/cron/db.sql >/dev/null 2>&1

0 */2 * * * mysql -u myUser -pmyPassword -e “DROP DATABASE myUser_my_db; CREATE DATABASE myUser_my_db”; mysql -u myUser -pmyPassword myUser_my_db < /home/myUser/cron/db.sql >/dev/null 2>&1

If you ever have used a theme or script, you will often see an element with various classes attached to that element; such as ‘<div class-=”red black”>’. As you may have already expected, the element makes reference to the red and black classes.

That is the easiest part while applying the style to the element is only a little more involved. If the single element contains 2 classes, how is the style interpreted from the stylesheet? To make this a little more clear, add the code below to the final stylesheet.

As you can see below, the element can access all 3 colors. But, the priority is top down for the single classes while the reference using .black.red takes precedence. Thus, the actual color of the text is blue even if you moved .black.red to the top. But, if you deleted .black.red and shuffled the order for .red and .black you will see that color will change to reflect the last single class.

<style>    
    .black{color:black}
    .red{color:red} 
    .black.red{color:blue}  
</style>

<div class="red black">My Text</div>

 

Now, try the code below. As you can see, the color is now red, because red overrides black and the use of !important will stick unless it is overridden by another !important.

<style>
    .black{color:black}
    .red{color:red !important}
    .black.red{color:blue}
</style>

<div class="red black">My Text</div>

 

Finally, try the code below. As you can see, the color is blue as you may have expected.

<style>
    .black{color:black}
    .red{color:red !important}
    .black.red{color: blue !important}
</style>

<div class="red black">My Text</div>

 

Now, for one little twist. Move the .black.red above .black so it looks the block below. As you can see, .black.red !important overrides anything below. Also, if you had the same order without !important, the text color would be blue too.

<style>
    .black.red{color: blue !important}
    .black{color:black}
    .red{color:red !important}    
</style>

<div class="red black">My Text</div>

After browsing around the web, looking a perfect solution for making all bootstrap columns the same height, I ended up crafting a custom solution because all the options I pursued were incomplete. Why incomplete? Well, using a simple Jquery solution to take the tallest column and make others the same height was short and sweet and looked great on an Ipad, Laptop and PC, but, when it came to the phone, using the largest column left too much unwanted space on the shorter column(s).

So, here is what I did. I chose the break point width of 768px to be mark where I would only want the Jquery to execute making the columns the same height. Since the columns had custom color backgrounds with text, they did need to be the same height when side by side or the layout would look off and lack symmetry.

 

Method A

Within the row class, the added a class called inner-top to each of the columns. In my case, it was 2 columns, but that could easily be adjusted to three, if needed. Here is a quick synopsis of the code below. The script will get the width of the window from the device being used. Do note that there are two ways to achieve this; one being $(window).width() and the other screen.width. It is important to remember that the latter actually detects your device with while the former detects browser width which in some cases could be wider than the device width.

If the device has the larger view port where columns will be shown side by side, we find the height of the desired columns of the inner-top class. The eq() method is used to get them. The first column from the top of the source code is eq(0) and the second is eq(1).

Once the dimensions are found, a simple if and else statement will apply the width from the largest column to the smaller column.

In addition, the page will reload if it is resized so that they will maintain the proper heights.

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

        width = $(window).width();
        //width = screen.width;
if (width > 768) { var first = $('.inner-top').eq(0).height(); var second = $('.inner-top').eq(1).height(); if (first > $('.inner-top').eq(1).height()) { $('.inner-top').eq(1).height(first); } else { $('.inner-top').eq(0).height(second); } var imageDiv = $('.inner-top img').eq(1).height(first); $('.inner-bottom').each(function (index, value) { if (index == 0) { var newHeight = $(this).height(); $('.inner-bottom').eq(1).height(newHeight); } }); } $(window).resize(function () { if ($(window).width() > width || $(window).width() < width) { window.location.href = window.location.href; } }); }); </script>

 

Method B

For those who find the method above a little redundant, you can use the map() method below to grab all heights of the inner-top class and make the class take on the height of the largest column.

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

        width = $(window).width();

        if (width > 768) {
            var all_heights = $(".inner-top").map(function () {
                    return $(this).height();
                }).get();

         maxHeight = Math.max.apply(null, all_heights);
         $(".inner-top").height(maxHeight);
 
 }


 $(window).resize(function () {
 
 if ($(window).width() > width || $(window).width() < width) {
 window.location.href = window.location.href;
 }
 });

});

 </script>

 

Method C

This method uses a bootstrap class called row-eq-height. Thus, the row like

<div class="row"> becomes <div class="row row-eq-height">

In some cases, Bootstrap may not have included the class, thus, it is shown below. When using this class, you may not be home free since the row may not stack the columns on top of each other as you expect on the smaller devices. Again, you could add a simple piece of Jquery that would remove the class when the device is less than 768 px.

.row-eq-height {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display:         flex;
}

 

The code to remove the class is shown below. Again, you see the window will reload in order to make it look right if someone resizes the page.

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

        width = $(window).width();

        if (width < 768) {
            $(".row").removeClass("row-eq-height");

        }


        $(window).resize(function () {
            
            if ($(window).width() > width || $(window).width() < width) {
                window.location.href = window.location.href;
            }
        });

    });

</script>

The purpose of this article is to explain how to adapt to using angular.js for those who have a background in PHP; since angular is MVC, uses controllers, and outputs $scope variables in the HTML using {{variableName}} much like a template engine like Smarty, Twig and Blade.

If you have at least a basic understanding of object oriented PHP that is good. If you have familiarity with PHP Frameworks like Laravel or Symfony, that will likely help even more; especially for those with more experience.

Now that I brought some basics to the table, I will point you to a basic angular.js example.  This explains the bare bones basics of an angular.js app using $scope, a controller and variable output in HTML.

However, another step forward in your progression is the usage of the factory() and service() methods. Here are two good examples of using these two methods.

Service Methods

Factory and Service Method

If you look into the factory and service methods, you will see that everything starts from the controller. Within the controller, a service or factory method can be called using the name that was given to the method. This is very much like using a class with PHP and calling another function within the class. In addition, you could come across a situation(such as the latter link above) for which the controller calls a service which in turn calls a factory method.

Naming Conventions

Here is a quick lesson in naming the controller, factory and service methods.

Controller

The controller is accessed in your HTML file via the ‘ng-controller’ directive, or as you would normally here in HTML, the attribute. The ‘ng-controller’ takes place between the beginning and ending tag for which it is used; such as a div. The name of the controller is important because a name like ng-controller=”myController” means that it will reference the Javascript code where the first parameter in the method is the name of the controller.

After you look over the examples from above, this link about controllers  may help clear up details regarding how a controller works. As you can see, you can add the $scope and dependencies into an array between the [] brackets and call an anonymous function. That anonymous function will allow you to run methods from a factory or service method. Alternatively, you can run a service method that can run an anonymous function using a factory method.

Ending Statements

So, to wrap things up, I hope you could absorb some of the methods to use angular.js based in the fact that you have a background in PHP. This should make the usage of angular more friendly because it takes the knowledge and essentially, many of the features of angular.js that you already know.

So, here is what you have learned. You should now know how to setup a controller in the Javascript and initiate its usage from within the HTML using the ng-controller directive.

Although the tutorial links above showed some good examples, remember that you can run a function within a controller very easily with the on-click directive. If that is not totally clear, the code below shows a simple example that calls a function within a controller.

Here is what is happening. The input box has ng-model=”myInput”. That value will be $scope.myInput in the Javsacript. When myFunc() is initiated, the function in the controller runs and a new $scope variable called $scope.outputMessage is created.

Call the Function In HTML

<input ng-model=”myInput”>
<button ng-click=”myFunc();”>Submit</button>

 

The Actual Function in the Javascript

controller(‘Controller1’, [‘$scope’, function ($scope) {
$scope.myFunc = function() {
$scope.outputMesssage = “Hi ” + $scope.myInput;
};
}])

Angular.js is a Javascript Framework that can be used quite effectively with single page web applications, ajax and PHP. This article will not show various methods to use angular.js. It will focus on using modules, controllers and output.

When you use Angular.js, there are three parts in the file for which you need to know about. The first and second parts take place in the head of the file. In the head, you need to include angular.js from a local or external source and you need a custom script for which you will build the custom application.

The other part takes place in the HTML code and will include the required angularjs attributes. In each application the attributes will vary; depending on what you are trying to achieve. A good place to check out what angular.js is capable of is to read the documentation at angularjs.org.

 

CONTROLLERS

The two methods to use controllers are shown below. Although both work, the latter method allows you to have as many controllers as you want in your HTML and they all can have corresponding code in the Javascript.

 

Global Controller

var myController = function ($scope) {
$scope.name = ‘Rufus’;
}

 

Using Angular Namespace, module function and controller function

angular.module(‘myAppName’, [])
.controller(‘myController’, function($scope){
$scope.name = ‘Rufus’;
});

 

Before we move on to the HTML, I am reminding you that the code block above is the Javascript that is going to be used to work with the HTML. In order for Angular.js to work, you will see that the HTML code has the attributes ng-app=”myAppName” and the attribute ng-controller=”myController”.

Those two pieces of the puzzle are very important for everything to work. If you look at the Javascript, you can see the module uses the app name and the controller uses the value from ng-controller, which is “myController”.

Finally, look at how {{name}} takes its value from $scope.name.

 

HTML

<body ng-app=”myAppName” ng-controller=”myController”>

<h1>Hello, {{name}}!</h1>

</body>

 

After that, you could add more HTML and more Javscript to accommodate another controller. The code below shows how you would make that second controller in the Javascript.

angular.module(‘myAppName’).controller(‘secondController’, function($scope, $http) {
// add ajax code here
}

 

Keep in mind that when you use multiple controllers in your HTML, you can use them with closing and opening tags; such as <div></div>tags.  Thus, html could resemble the code below if you added a second controller.

<body ng-app=”myAppName” >

<div ng-controller=”myController”>

<h1>Hello, {{name}}!</h1>

</div>

<div ng-controller=”secondController”>

Add custom stuff here

</div>

</body>

 

Those examples were quite simple. If you move on to forms, loops and other data, more, new coding is required. For example, this form to email example on a web page explains how to use Angular.js to use a function within a controller using the ng-click directive which is a lot like like onclick() with vanilla Javascript or onclick() with Jquery.

This post will demonstrate how to submit a form and email a message to the desired recipient. This lesson will use ajax with PHP and Angular.js. In addition to the form submission, a new class and a one time token are used to ensure that the form is actually submitted from the website and not through some script on a foreign machine.

How It Works

Whenever the page is loaded, the csrf class is called and a new hash, the one time token is created. That value is set as a session variable and added to a session array. Since browsers like Firefox and Chrome can handle sessions differently, creating the array ensures that if a token is created a second time, its value is stored no matter what.

The form itself is has typical angular attributes like ng-click and ng-model. As you may or may not already know, ng-model values come from the $scope.itemname created in the Javascript. Thus, when you see a tag like ng-model=”{{message}}”, you know its value comes from $scope.message in the Javascript.

Now for the action. When the form is submitted, the check_credentials() function is called.

If you look in the angular code, you will see that all form inputs, including the hidden csrf input are passed into the ajax post.

Once this code arrives to the php file, variables are set and sessions are checked to ensure that the one time token passes the test. Since the one time token is created on the server, this ensures email is not sent unless the csrf is valid.

Once the email is sent, all session variables are emptied due to the last line that shows $_SESSION = array();

Now, back to the angular.js code. Once all is successful, the original form is hidden, and a success message pops up with an image and a success message. Meanwhile, the page is not refreshed and the user experience is quite satisfying.

 

CSRF Class

class csrf
{
    public $csrf;
    public $session;
    public $csrf_array = array();

    public function __construct()
    {
        $csrf = hash("sha1", rand() . time() . rand());
        $_SESSION['csrf'] = $csrf;
        $session = $_SESSION['csrf'];
        $this->MakeToken($csrf, $session);
    }

    public function MakeToken($csrf, $session)
    {
        $this->csrf = $csrf;
        $this->session = $session;

        array_push($this->csrf_array, $this->csrf, $this->session);
        return $this->csrf_array;
    }

}

 

Top of File

<?php
    session_start();
    include("classes/csrf.php");
    $csrf = new csrf();
    $_SESSION['csrf'] = $csrf->session;
    $_SESSION['csrfs'][] = $csrf->session;
?><!DOCTYPE html>

 

Form

<div class="footer-widget newsletter-widget" id="message-received" ng-controller="ProjectsListCtrl" style="color:white">
    <div id="message"></div>
    <form name="myForm">
        <p><input type="text" size="40" ng-model="name" value="{{name}}" placeholder="Name"></p>
        <p><input type="text" size="40" ng-model="phone" placeholder="Phone"></p>
        <p><input type="text" size="40" name="email" ng-model="email" placeholder="Email" value="{{email}}" ng-pattern="/^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/" required></p>
        <p><textarea id="mess" placeholder="Your Message" ng-model="message" value="{{message}}"></textarea></p>
        <input type="hidden" name="csrf" ng-model="csrf" value="{{csrf}}"/>
        <button ng-click="check_credentials()">Send Message</button>
    </form>

</div>

 

Angular Code

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>

<script>
    angular.module('admin-projects', []);

    angular.module('admin-projects').controller('ProjectsListCtrl', function($scope, $http) {

        $scope.check_credentials = function () {

            if ($scope.email === undefined) { alert("Webmaster says email is undefined because it did not match pattern!") }

            if($scope.email.length < 5){
                alert("Email is invalid");
            }else{
                //alert("Email is valid");
                //alert($scope.csrf);
            }

            $scope.csrf = "<?php echo $csrf->session; ?>";

            var request = $http({

                method: "post",
                url: "post.php",
                data: {
                    email: $scope.email,
                    name: $scope.name,
                    message: $scope.message,
                    csrf: $scope.csrf
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            });

            request.success(function (data) {
                        
                    $('#message-received').hide();
                    $('#message-received').html('<em><span style="font-size:12px; color:white">Your message has been successfully sent!</span></em>&nbsp;<span style="color:#FB3F43" class="glyphicon glyphicon-ok"></span><br/><img style="width:100%; border:1px solid #FB4848; border-radius:10px;" src="images/clients/myimage.jpg">').fadeIn(3000);
     
                $scope.email = '';
                $scope.name = '';
                $scope.phone = '';
                $scope.message = '';

            });

        }

    });

</script>

 

PHP Code

session_start();
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    //Request identified as ajax request
} else {
    die("No direct access");
}
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$password = $request->name;
$subject = $request->subject;
$content = $request->message;
$csrf = $request->csrf;

$session_array = $_SESSION['csrfs'];

//echo "CSRF: ". $csrf . " and CSRF Session: " . $_SESSION['csrf'] . print_r($_SESSION['csrfs']) . print_r($_SESSION);

if ($csrf == $_SESSION['csrf'] || in_array($_SESSION['csrf'], $session_array)) {

    $to = "test@example.com";    
    $headers = "From: $email" . "\r\n";
    mail($to, $subject, $content, $headers);
}

$_SESSION = array();

Laravel is a popular PHP framework and may programmers and employers like to use a framework. Using a framework encourages decent coding methods and can help keep code organized and secure.

Now that you know that you want to build a web application with Laravel, here are the essentials to get up and running.

Step # 1 Installation

So, you go to Laravel’s website or Google around, and you see that a common way to install it is by using composer. What you say? Why I can’t I just download a zip and be good to go. Well, you can actually do that by going to github and making a download. For example, you can download Laravel from Guthub at https://github.com/laravel/laravel.

However, using composer is a pretty good idea and it makes it very easy to install other frameworks like Symfony as well. So, let me help straighten you out about composer.

For Windows, you can download composer at https://getcomposer.org/download/. After that, you can open or reopen a command prompt and type composer. You will see that it works. The code below will download laravel and install it to a folder named laravel-composer. You can now build your application here.

C:\xampp\htdocs> composer create-project –prefer-dist laravel/laravel laravel-composer

Step #2 Using the Framework

After that, you will need to know how the framework operates. Let’s start by building a static webpage. In order to be able to display any page, you need to set a route for get or post requests. Since this exercise is simple, the focus will be on a get request.

routes.php located at app\Http\routes.php

Open this file and add the following code.

Route::get('test', 'TestController@get_index');

Here is the breakdown. The test parameter is the file url. Thus, the url on a localhost xamp server at home would be http://localhost/laravel5/public/test. The code before the ‘@’ symbol refers to the controller and filename located in the app\Http\Controller folder. Thus, when the url is referred to in the browser, the TestController.php and the TestController class is used. The get_index after the ‘@’ symbol  refers to the method that is called within the class.

So, now, lets make a TestController.php file and write the appropriate class and methods. The simple code is shown below.

<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use Auth;
use Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;

class TestController extends Controller
{
    public $restful = true;

    public function get_index()
    {

        $title = "My Test Title";

        $data = "Foo";
        $title = "Bar";

        $myArray = array('apples','oranges');
        
        return View::make('test.index')
            ->with('data', $data)
            ->with('title', $title)
            ->with(array('name' =>"first", 'age' => 'last'))
            ->with('myArray',$myArray);
    }

    public function post_index()
    {
        $title = "Test page";
        $input = Input::all(); // gets all input from forms
        $rules = array('html_begin' => 'required', 'html_end' => 'required');
        $v = Validator::make($input, $rules);
        if ($v->fails()) {

            return Redirect::to('login')->with_errors($v);
        } else {

            $data = array('html_begin' => $input['html_begin'], 'html_end' => $input['html_end']);

            return View::make('test.success')
                ->with('data', $data)
                ->with('title', $title);

        }
    }

}

After the workhorse file which does the heavy lifting is finished, you can make the view file.

View Files

Look for the folder called resources\views. Now, make another folder called test. Within this folder, make a file called index.blade.php. This is the file that is rendered from the TestController. As you can see, the variables and arrays created in the controller are parsed within curly tags. For example, this is a vairable {{ $variable }} and this accesses an array item {{ $array[key] here }}.

<html>

<body><div class="row">
    <div class ="span4 offset4">
        <div>{{ $title }} add variables here {{ $name }} and parsing array is {{ $myArray[0] }} and {{ $myArray[1] }}</div>
        <div class="bs-example well-sm" style="border:1px solid #C1BFBF; width:250px; border-radius:1em; margin: 0 auto; ">


        </div>
    </div>
</div>
</body></html>

Without getting too heavy with theory, these simple points makes it easy to piece together your logic and views. Although only single templates are used in this example, you can create master templates for an application to keep separate files for headers, footers, etc.

@extends('master')
@section('content')

<div class="row">
    <div class ="span4 offset4">
        <div>{{ $title }} add variables here {{ $name }} and parsing array is {{ $myArray[0] }} and {{ $myArray[1] }}</div>
        <div class="bs-example well-sm" style="border:1px solid #C1BFBF; width:250px; border-radius:1em; margin: 0 auto; ">


        </div>
    </div>
</div>

@endsection

Here is explanation about what is happening above. The master template file sits only folder up from the current view file. Thus, this current file extends the master template. The content between the @section tags is displayed in the master.blade.php file because it has a line that reads @yield(‘content’). The line displays the content from the page in the exact spot.

Conclusion:
So there you have it, a simple web app. The next stage would be to setup a database that you can use for an application. When using a database, you will execute queries within your controller. The syntax is very similar to typical PHP / mySQL queries.

This article is about customizing a WordPress theme with custom html, css, javascript and php. It will not refer to plugins that can be added to themes, but, rather refer to how you can add your own code to the current template files.

For starters, your WordPress website will have a current theme that will style your home page, posts, pages and other such navigational pages like categories and archives. A good reference to see what exists in a typical WordPress page can be found at the WordPress.org website theme development.

Please keep in mind that many custom themes that are free or paid may have their own custom named files that  handle specific requests; such as a page that lists of posts of a specific category, or archived pages based on the date.

To edit the pages, you need to know where they are. You have two means of editing the content; one through the WordPress backend and the other from editing files within the wp-content/themes/mythemename folder.

Method #1: WordPress backend

If you plan to use the WordPress backend, you can find them at Appearance >Editor. After you select ‘Editor’, the pages will be displayed on the right hand side of the screen. Do note, that some themes can extend another theme and that means you need to go to a parent theme in order to make your desired changes.

Once you make the changes, you can simply click the ‘Update File’ button of the bottom of the page that you are editing. If you plan to edit content this way, I recommend backing up the wp-content folder or file in order to have a disaster-proof plan.

Method #2: Files From Directory

If you navigate to the wp-content/themes/mytheme(your actual theme you are using) folder, you can edit any of these files as you want. Thus, you can open your favorite editor and code away.

This simple lesson will show how to use the Jquery serialize() function to pass all form data to an ajax file. With the serialize() function, it is very easy to pass all form data name and values to the ajax file without having to send them all separately.

I will go over this in detail. When the user inputs a name in the text input box and clicks ‘Submit it’, the Jquery .submit() method is triggered. We pass in the e into the function and use e.preventDefault() method too because you do not want the usual form submission to happen….which would be a typical post request that would reload the page.

After that, the formData variable is created and it contains the names and values from the form. Then, it is passes into Ajax for which it is sent to the ajax_1.php file.

After it arrives to the ajax_1.php file, the parse_str() function is used to make an array from that serialized data. In that array, is the first name that was entered into the text field. Thus, the value of that posted test becomes $myArray[‘myFirst’]. Remember that myFirst was the name of the input text box.

After that, it is pretty much a simple mySQL query that finds all users with that first name. Finally, the names are printed in two separate ‘div’ elements. Note that the printed text in the ajax file is handled as the msg variable in the original file.

Thus, there are two places and methods for which the same text is printed; one using vanilla javascript and the other using Jquery.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $('form').submit(function (e) {
                e.preventDefault();

                var formData = $(this).serialize();

                $.ajax({

                    type: "POST",
                    cache: false,
                    url: "ajax_1.php",
                    data: {myData: formData},

                    success: function (msg) {
                        //alert("Success!");
                        document.getElementById("vanillajs").innerHTML = msg;
                        $("div#jqueryjs").html("<p>" + msg + "</p>");

                    }

                });

            });

        });

    </script>
</head>
<body>
HTML

<form method="POST" action="" id="login">
    <input id="myFirst" type="text" name="myFirst" value=""/>
    <input id="contacted" class="contacted" type="submit" name="contacted" value="Submit it"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

The code below is represents the ajax_1.php which handles the data made from the original page. The code is very limited and although it shows how to handle the data, any production server would need a layer of security built around it so unauthenticated users and web robots would be unable to cause damage.

function PDO_Connect()
{
    $user = 'root';
    $pass = '';
    $PDO = new PDO('mysql:host=localhost;dbname=abook', $user, $pass);
    $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    return $PDO;
}

$PDO = PDO_Connect();

parse_str($_POST['myData'], $myArray);

$first = trim($myArray['myFirst']);
//echo $first;

$command = "SELECT * FROM leads WHERE firstname=TRIM(:first)";
$result = $PDO->prepare($command);
$result->bindParam(':first', $first);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
//print_r($rows);
foreach ($rows as $row) {
    echo "<br/> " . $row['firstname'] . " " . $row['lastname'];
}

After many years running a blog on Joomla 1.5, I decided to migrate to the latest WordPress  since it was useless without a responsive design.

I chose WordPress rather than upgrade to the latest Joomla 3.XX for many reasons. One of those reasons are that Joomla 1.5 had so many security issues that had to be addressed; even to the limit of disabling all file uploads to the website account, removing all third party editors, and more.

WordPress was also selected because it is simpler to just create a new template and code PHP however you desire.

The final deal breaker was that WordPress had free migration plugins while Joomla was going to cost.

So, here is how I made the migration that had about 800 blog posts filled with code blocks and illustrations. After all, the blog was about Lampstack development.

  1. Installed WordPress to a subfolder
  2. Installed the FG Joomla to WordPress plugin.
  3. Opened the Joomla configuation.php to copy the database details into the FG Joomla to WordPress plugin.
  4. Ran the plugin to make the upgrade. The upgrade happened very quickly and moved images, text, etc.
  5. Installed a desired WordPress theme that looked good with the content.
  6. Made minor changes to code blogs as a little formatting was lost.

Moving WordPress from a subfolder to a root folder can be very quick and easy. This example will explain how to move it from a subfolder like example.com/wordpress to the root folder example.com.

For simplicity, this tutorial will use the subfolder ‘wordpress’ for instructional purposes.

The first thing to do is copy the files from the wordpress subfolder to the root folder. This can be done with ftp or Linux command line.

Once the files are moved the root folder, logging into the new admin at example.com/wp-admin can be problematic. So, here is what you can do after you moved the files.

Login to your Cpanel or phpMyAdmin. Hopefully, you have phpMyAdmin or some other mySQL admin manager. Once you have logged in, open up your database. At this point, you will have access to all the tables.

A quick way to find the old url in database tables is to search all tables for the string like ‘example.com/wordpress’. You will then see a list of tables like wp_options. If you used a different prefix than the default, the table would be yourprefix_options. In this table, you will want to change the option_name fields which are site_url and home. They are the first two items in the list. Meanwhile, you may want to change recently_edited.

Changing Posts

Now, if you have old links you may want to update them. The code below will remove the wordpress subfolder from the url so that image links and other links will work within the current folder.

UPDATE `wp_posts`
SET `post_content` = replace(post_content, ‘example.com/wordpress’, ‘example.com’)

UPDATE `wp_posts`
SET `guid` = replace(guid, ‘example.com/wordpress’, ‘example.com’)

Asides from that, you may want to check your .htaccess file and make sure rewritebase is ‘RewriteBase /’ and not ‘RewriteBase /wordpress’.


PHP, Jquery and Ajax Tutorial

The purpose of this article is to explain several options for which to use PHP and Ajax. Ajax has been around a long a time and there are multiple reasons why a developer would want to use it.

However, what ranks it high on the list is its ability to make a call to another file and return data that can be presented on a page without the need for a refresh. The data from the requested file can be a string or data queried from a database.

But, retrieving data without refreshing is only one such advantage of Ajax. You may want to post data to the Ajax file and perform any CRUD operation like Insert, Update or Delete as well as return updated information. All this is possible with Ajax.


How is a typical Ajax Request Performed?

To start with, it often begins with a POST or GET request that sends variables to the Ajax file. Since POST is more secure and often the programmer’s choice for dealing with data from forms, the following examples will explain how to make Ajax calls with POST variables.

Although the examples in this tutorial will show how to output data on the page without a refresh, please keep in mind there are two important ways to do this. One method, is to print a string in the Ajax file while the other is to print JSON data from the Ajax file. With the former, you can easily output any desired HTML as a string and it will magically appear exactly as you code it in the called Ajax file.

However, if you decide to print(echo) JSON data from the file, you have the option to parse it and manipulate it in Jquery which can allow for many more options in terms of placing various portions of data on the page. If that sounds confusing, the examples should make it much easier to see how it is done.

Now, let’s let the examples take over. Each example consists of 2 files. One file is the page that is loaded in the browser and the Ajax file is the one that is called from the main file.

Example #1

Overview

When the button with the ‘contacted’ class is clicked, it triggers the Jquery. After the click function, the Javascript variable myurl is the value of ‘yahoo.com’.

Immediately after the variable creation, the Ajax shown by ‘$.ajax’ takes over. As you can see, it is a POST request that calls the my_ajax_print_php.php file.

This variable myurl is posted as my_variable, thus, when it arrives at the Ajax file it becomes $_POST[‘my_variable’]. 

Once the variable arrives at the Ajax file, you can do whatever you want with it. If you look at the file in this example, you see a potential query you can use to output data. Meanwhile, I will explain what is happening in this case since we are only going to parse an array.

The array is parsed and printed. But, keep in mind that this takes place in the success function in the main file. The entire data that was printed in the Ajax file becomes the variable msg. As you can see, that output is sent to 2 locations on the page; the first is the div element with the id ‘vanillajs’ and the second is the div element with the id ‘jqueryjs’.

Main File

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">

$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_print_php.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg;
$("div#jqueryjs").html("<p>" + msg + "</p>");

}

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers = array(‘one’ => 1, ‘two’ => 2, ‘three’ => 3, ‘four’ => 4, ‘five’ => 5);

foreach ($numbers as $key => $number) {
echo “<br/>” . $key . ” – ” . $number;
}

/* Query Sample
$user_id = mysqli_real_escape_string($db,$_POST[‘my_variable’]);
$command = “SELECT * FROM user WHERE id = ‘” . $user_id . “‘”;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_array($result)) {
echo $row[‘FirstName’] . “<br/>”;
}
*/

Example #2

This next example will be very similar to the first example, except the data will be returned as JSON and manipulated with Jquery. If you look closely, the main difference is the addition of the DataType:JSON is the Ajax request and the printed data from the Ajax file uses the json_encode() function.

Asides from those two details explained above, you will see the output is more complicated. With the Ajax file, there are 2 numbers arrays that are created. Thus, each of those transforms into msg[0] and msg[1]. Within each array, there are items which take on indexed values. Thus, The number 2 from the first array is actually msg[0][1]. Always remember keys start at 0 and not 1, thus msg[0][1] is the first array with the second item.

If you look at the HTML and compare with the Jquery inside the success function, you will see why those numbers are what they are.

Main File

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_indexed.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg[0][3];
$("div#jqueryjs").html("<p>" + msg[1][2] + "</p>");
//$( "div#jqueryjs" ).html("<p>Add here</p>");

jQuery.each(msg, function (key, val) {
alert(key + "=" + val);
jQuery.each(val, function (key2, val2) {
alert(key2 + "=" + val2);
});
});
},
dataType: "json"

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers[] = array(1, 2, 3, 4, 5);
$numbers[] = array(6, 7, 8);
echo json_encode($numbers);

Example#3

This final example shows an associative array that is printed in the Ajax file and manipulated in the Jquery from the main file. This example is very similar to the last example since it returns a JSON string. The difference is that the arrays are associative; thus have named keys instead of numerical keys like the ones in the previous example. Like the previous example, there are two arrays that become msg[0] and msg[1]. Therefore, to access any item from the first array can be done by using msg[0] followed by the item key. Thus, the item from the second array with a key of 6 can be accessed in Jquery as msg[1].six. 

Main File 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_multi.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg[0].three;
$("div#jqueryjs").html("<p>" + msg[1].eight + "</p>");
//$( "div#jqueryjs" ).html("<p>Add here</p>");

jQuery.each(msg, function (key, val) {
alert(key + "=" + val);
jQuery.each(val, function (key2, val2) {
alert(key2 + "=" + val2);
});
});
},
dataType: "json"

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers[] = array(‘one’ => 1, ‘two’ => 2, ‘three’ => 3, ‘four’ => 4, ‘five’ => 5);
$numbers[] = array(‘six’ => 6, ‘seven’ => 8, ‘eight’ => 8);
echo json_encode($numbers);

Ajax Security

The previous examples have shown how to use Ajax with simple, limited coding. But, in the real world, security should never be left out during the building process. With Ajax, sessions persist which means you can make files only accessible to authenticated uses. On top of that, you could also track what authenticated users are making Ajax requests, bit, you may find that unnecessary.

In addition, to securing your Ajax requests by using authenticated sessions, you can add a session and a hidden input to eliminate Cross Site Request Forgery since the token in the hidden input must match the session on the server, something a malicious user cannot spoof. In addition to that, you can filter any output with htmlentities() function in order to make sure that potential scripts in database fields cannot be executed.

Returning PHP Objects

This tutorial will use a simple example regarding how to return methods and objects from a class. Although the code is not optimal for production use, it does demonstrate a process for which the class is instantiated, and a database object is used for database queries.

Here is a summary of what is going on. The line below instantiates a new instance of the MyObject class. Since the constructor is triggered first, it runs the $this->set_connection() method.

When that method runs, it makes the property $this->connection to take on the returned value from the PDO_Connect() method.

Thus, the $PDO->connection is used to access the database. For code readability, you would likely just make a simpler connection, like that shown in the page http://fullstackwebstudio.com/locations/coding-blog/pdo-database-connection.html

In addition to the above, you can also access the the database variable using the get_connection() method and that example is at the end of the file.

class MyObjects
{

    public $var1 = "test";
    private $var2 = "test2";
    protected $var3 = "test3";
    public $connection;
    public $PDO;

    function __construct()
    {
        $this->set_connection();

    }

    function PDO_Connect()
    {
        $user = 'root';
        $pass = '';
        $PDO = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
        $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        return $PDO;
    }


    public function set_connection()
    {
        $this->connection = $this->PDO_Connect();
    }

    public function get_connection()
    {
        return $this->connection;
    }

}


$PDO = new MyObjects();
print_r($PDO);
echo "<br/><br/>";
echo "Var1: $PDO->var1";
echo "<br/><br/>";
//var_dump($PDO->connection); //object(PDO)#2 (0) { }
//echo "<br/><br/>";
$PDO = $PDO->connection;

$command = "SELECT * FROM leads";
$result = $PDO->prepare($command);
$result->execute();

echo "<strong>Method A</strong>";

echo "<ol>";

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "<li>Name: {$row['firstname']} - {$row['lastname']}</li>";
}
echo "</ol>";

echo "<strong>Method B</strong>";

$test = new MyObjects();
$db = $test->get_connection();

$command = "SELECT * FROM leads";
$result = $db->prepare($command);
$result->execute();

echo "<ol>";

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "<li>Name: {$row['firstname']} - {$row['lastname']}</li>";
}
echo "</ol>";

PHP to Display Object Information like Sessions, Functions, Variables and Objects

So, there you are, you have purchased a PHP script, or you have found yourself in front of your coding editor with some foreign code and you are trying to piece it together.

For a decent working script, all the coding will have a logical way to mak things work, or it will not function properly. That does not mean it is as organized as you would like.

For example, you may have a script with various files of more than 1000 lines of code and they continue to cross reference methods, classes, and functions from various files.

But, when you have found the spot in your coding where you will want to make changes, alter variables, or work with session values, you can always use a few built in PHP functions to see what variables, functions, objects and sessions are available at the precise line of code.

Within the code block further on in the article, you can see a simple PHP page that has a session, function, class, variables and objects.

The functions below will explain what they do. You can reference the code to see what data they are grabbing.

1.

get_class_vars("GetThem")
Retrieve variables within the class.

2.

get_object_vars($objectvariables)
Retrieve the new object variables that are declared 'outside' of the class.

3.

get_defined_vars()
Retrieve defined variables in a page, but, it won't grab variables within a function unless that is where you use this function.

4.

get_defined_functions()
Retrieve the function in the file. You can view internal and user defined functions.

5.

print_r($_SESSION)
Retrieve the session variables in the page.
session_start();
$_SESSION['test'] = 'test';

function test(){
    $var_in_function = "var in function will not be a defined variable";
    return $var_in_function;
}

class GetThem
{
    public $var = 10;
}

var_dump(get_class_vars("GetThem")); //outputs array(1) { ["var"]=> int(10) }
echo "<br/><br/>";

$objectvariables = new GetThem();
$objectvariables->var = 20;

var_dump(get_object_vars($objectvariables)); //outputs array(1) { ["var"]=> int(20) }
echo "<br/><br/>";

$var_out = test();
print_r(get_defined_vars());
echo "<br/><br/>";

$functions = get_defined_functions();
print_r($functions['user']); // outputs Array ( [0] => test )

echo "<br/><br/>";
print_r($_SESSION); //outputs Array ( [test] => test )


Not Allowing Direct Access To PHP files

You can use several methods to not allow web surfers to access files directly. One method can be done with an Apache configuration or .htaccess and another is to define a constant in a file and include the other file while making sure the constant was defined.

Method #1 Apache and .htaccess

With this method, you name your more sensitive include files with an extension like ‘.inc’, or even better ‘.inc.php’. Then, you add a little code into the .htaccess file so that it cannot be accessed directly through the browser or by bots, etc.

 <Files ~ ".inc"> Order allow,deny Deny from all </Files> 

Method #2 Constants

In one file, you can define the constant my_pdo and include the file you want to protect.

File #1

 define('my_pdo', true); include("file2.inc.php";  

File #2
In the other file, you do a simple check by adding the following code to the top. As you can see, it will die and print out a message if it is accessed directly.

 if(!defined('my_pdo')) {     die('Direct access not permitted'); } 

Custom Keys and Values From a Loop in PHP

With PHP, using the array_push() function and $newarray[] syntax is an easy way to make arrays from a foreach or while loops. However, both methods create indexed arrays and may not be adequate to build the array you want.

For example, you may have a loop that is pulling data from two columns in a database and you just want a simple associative array that contains the matching key and value. 

The $user_array that is commented out is the same array you want from the while loop. As you can see, the value from the the ‘access_level’ column is the key and the value from the ‘name’ column is the value.

//$user_array = array(1 => 'admin', 2 => 'managers', 3 => 'members', 4 => 'public');

$command = "SELECT DISTINCT access_level, name FROM access_level";
$result = $PDO->prepare($command);
$result->execute();

$user_array = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
    $user_array[$row['access_level']] = $row['name'];
}

Using PDO to Connect To mySQL

When using mySQL for PHP applications, you normally connect to a database using a function. Some popular methods are mysql_connect(), mysqli_connect()and PDO objects. This simple example will explain how to do it using PDO.

PDO has all sorts of advantages, such as binding parameters to a query so that mySQL handles the variable separately.

The following examples explain how to connect with PDO and return it from a function.


File: _pdo.php The Function

The function below creates a new object instance and return the $PDO object for making our desired queries. Above the function, the code is used to not allow direct access to the file.

Asides from knowing more code and how it works is always better than just winging it, the only editing you would need to make to the file is to provide your database name, database user and database user password. These values are created when you create a new mySQL user with the command line, or tool like Cpanel.

if(!defined('my_pdo')) {
    die('Direct access not permitted');
}

function PDO_Connect()
{
    $user = 'databaseuser';
    $pass = 'databaseuserpassword';
    $PDO = new PDO('mysql:host=localhost;dbname=mydatabasename', $user, $pass);
    $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    return $PDO;
}


File Connection Calling the Function

The file below defines a constant called my_pdo that will allow you to access the _pdo.php file. Remember from the last example that it is located above the function.

After that, the _pdo.php file is included. Finally, the function is called and the database object is returned. The database object, $PDO is what will be used for making all database queries.

<?php
define('my_pdo', true);
include "_pdo.php";
$PDO = PDO_Connect();

Preventing Cross Site Request Forgery With PHP Applications

Cross Site Request Forgery, aka CSRF and XSRF can be performed by targeting an authenticated web page when a user is logged in to a site, or, the user session(s) are still valid.

A popular method to perform this kind of attack is to draw a user to a webpage, like a forum or blog comment with a link that goes to a post page; such as one that could perform a delete request. Meanwhile, since the user is authenticated via valid sessions, it will perform the task at hand.

If the post page does an automatic update or deletion, or grabs information via the url using $_GET, that makes it even worse; since filtering and other such methods are not implemented.

Now, that you see that the post request is instigated from a foreign url, there are procedures that can stop this behavior in its tracks. The method being shown below uses a class and sessions that can ensure the post from the link will not do damage. This example can be used on pages that are submitted to itself, or, those that are submitted to another page.

Here is how it works.

1. Create a class called csrf and include it on the top of the file.

include("Classes/csrf.php");

2. Add the class code into the file csrf.php.The code below will do the work.

<?php

class csrf
{
    public $csrf;
    public $session;
    public $csrf_array = array();

    public function __construct()
    {
        $csrf = hash("sha1", rand() . time() . rand());
        $_SESSION['csrf'] = $csrf;
        $session = $_SESSION['csrf'];
        $this->MakeToken($csrf, $session);
    }

    public function MakeToken($csrf, $session)
    {
        $this->csrf = $csrf;
        $this->session = $session;

        array_push($this->csrf_array, $this->csrf, $this->session);
        return $this->csrf_array;
    }

}

3. Add the code below into the form file. This code only occurs when you land on a page that is not posted, or if the $_SESSION[‘csrf’] does not exist. If the page was posted from elsewhere, it would not exist, thus, it is created.

For example, if you had a page to delete members and came there securely, it would not have any post variables. Thus, the code below runs and calls the csrf class. In the example below, the class returns the property $csrf->session and uses it to make the $_SESSION[‘csrf’] variable. 

That variable was created using functions in the class.

if (count($_POST) < 1 || !isset($_SESSION['csrf'])) {
    $csrf = new csrf();
    $_SESSION['csrf'] = $csrf->session;
}

4. Wrap the database code into the check. If you are tricked into clicking this link, your page will have the code below to ensure it is not from another site.

Since the code from the previous example will create the session for validation purposes only when the page has no post variables, or it has no $_SESSION[‘csrf’] variable, it will mismatch with the form submitted elesewhere.

Therefore, if it came posted from a form that was submitted from somewhere else(Cross Site) via a form submission or Javascript automatically submitting the form when you click a link, it will arrive at your page and the session variable from your site would invalidate the form because it needs to have the same token from a hidden input field as the one you created from the csrf class.

The code below clearly shows that if there is a match, do the database stuff, and, if not, it prints that there is a token mismatch.     

if (htmlspecialchars($_POST['csrf'], ENT_QUOTES, 'UTF-8') == $_SESSION['csrf']) {
///do database work
 echo "Token matched! This was not cross site!";
} else {
            echo "Token Mismatch! Reload page and start over!";
        }        
            $csrf = new csrf();
            $_SESSION['csrf'] = $csrf->session;

5. Add a hidden field into the form. This line below places a value from the token that was created in the csrf class. It is a number that a fake form would not have in order to match your value from the csrf class.

<input type="hidden" name="csrf" value="<?php echo $csrf->session; ?>"/>

Extras
Now the next question you may have is, “How the heck could someone time my opened session with the link and auto form submission?”

Although this may seem like a very unlikely condition, there are many methods for which this could take place. Clever hackers can figure out what pages are visited on a network, such as wifi cafes. This can provide details about a page or script; especially if it is something common like WordPress.

It could also show details about your email address. Thus, you could be lead from a mysterious email sending you to a page that performs this operation because you feel the need to click the link.

Protect Yourself
Although web applications can be secured from the coding, you can always keep problems minimized by not trusting strange emails, logging out after using an application, and not allowing sessions to stay alive for extended periods of time. If you are logged out, the CSRF attack would have not had even had gone to the checking stage.

The min() function in a mysql query will get the lowest desired value for a given field. The example below will obtain the oldest date between ‘2012-01-02’ and now.

<?php
include('connect.inc');
$db = public_db_connect();
public_db_connect();

$command = "SELECT min(date) as date FROM table_sort WHERE date < now() AND date > '2012-01-01' ";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
    $date = $row['date'];
    echo $date;
}

The two examples will show how to make upper and lowercase strings using PHP and mySQL. With mySQL, it is performed in the query. With PHP, built in PHP functions are used.

<?php
include('connect.inc');
$db = public_db_connect();

$command = "SELECT DISTINCT LOWER(firstname) as first, UPPER(lastname) as last, LOWER(Email) as email FROM table_sort WHERE id >0 ORDER BY last ASC";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
    $firstname = $row['first'];
    $lastname = $row['last'];
    $email = $row['email'];
    echo $firstname . "-" . $lastname . "-" . $email . "<br/>";
}
<?php
include('connect.inc');
$db = public_db_connect();

$command = "SELECT DISTINCT firstname, lastname, email FROM table_sort WHERE id >0 ORDER BY lastname ASC" ;
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)){
    $firstname = strtolower($row['firstname']);
    $lastname = strtoupper($row['lastname']);
    $email = $row['email'];
    echo $firstname."-".$lastname."-".$email."<br/>";
}

The demo will shows how to remove ‘cm’ and ‘lbs’ from strings in a table. For example, there are 2 columns in a table; one for weight and the other for height. The data in each table shows numbers like 180 cm and 175 lbs. But, for our records, we want just the numbers like 180 and 175.

The code does a 2 replacements for height and weight. As you can see, whitespace is removed and so are the ‘cm’ and ‘lbs’.

<?php
include('connect.inc');
$db = public_db_connect();

$command = "SELECT DISTINCT LOWER(firstname) as first, LOWER(lastname) as last, LOWER(Email) as email,  replace(replace(height,' ',''),'cm','') as height, replace(replace(weight,' ',''),'lbs','') as weight, date FROM table_sort WHERE id >0 ORDER BY last ASC";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
    $firstname = $row['first'];
    $lastname = $row['last'];
    $email = $row['email'];
    $height = $row['height'];
    $weight = $row['weight'];
    echo $firstname . "-" . $lastname . "-" . $email . "-" . $height . "-" . $weight . "<br/>";
}

The trim() is very useful to remove whitespace before and after any data; thus your strings will be precise characters. The code below shows a form. When the form is submitted, the $_POST variables are escaped and trimmed of any potential whitespace.

<?php
include('connect.inc');
$db = public_db_connect();
if (count($_POST) > 0) {

    $firstname = mysqli_real_escape_string($db, trim($_POST['firstname']));
    $lastname = mysqli_real_escape_string($db, trim($_POST['lastname']));
    $height = mysqli_real_escape_string($db, trim($_POST['height']));
    $email = mysqli_real_escape_string($db, trim($_POST['email']));
    $age = mysqli_real_escape_string($db, trim($_POST['age']));
    $weight = mysqli_real_escape_string($db, trim($_POST['weight']));
    $command2 = "INSERT INTO table_sort3 VALUES (NULL, '$lastname', '$firstname', '$email', '$height', '$age', '$weight', now()) ";
    $result2 = mysqli_query($db, $command2);
    if ($result2) {
        echo "Successsul Update!";
    }
}

?>
<form method="post" action="">
    Lastname:<input type="text" name="lastname" value=""/><br/>
    Firstname:<input type="text" name="firstname" value=""/><br/>
    Email:<input type="text" name="email" value=""/><br/>
    Height:<input type="text" name="height" value=""/><br/>
    Age:<input type="text" name="age" value=""/><br/>
    Weight:<input type="text" name="weight" value=""/><br/>
    <input type="submit" name="submit" value="Submit"/>
</form>

The following code will grab rows from a table and add the to the $members array. During each loo, the in_array() function checks and makes sure the value from the ‘id’ column is not a duplicate. The ‘continue;’ will restart the loop if a duplicate exists.

This is just a demo. In reality, the ‘id’ field would be a primary key and autoincrement, thus, the array would be unique anyhow.

<?php
include('connect.inc');
$db = public_db_connect();
$members = array();
$command = "SELECT * FROM table_sort WHERE id > 0";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
    $memberID = $row['id'];
    $first_name = $row['firstname'];
    $last_name = $row['lastname'];
//echo $memberID;

    if(in_array($row['id'], $members)){continue;}
    $members[] = $memberID.",".$first_name.",".$last_name;
}

print_r($members);

Here is a simple example that shows how to combine arrays with data queries from two database tables.

<?php
include('connect.inc');
$db=public_db_connect();

// names from table #1
$command = "SELECT * FROM table_sort ";
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)){

    $firstname = $row['firstname'];
    $lastname =  $row['lastname'];
    $array_list[] = $firstname."-".$lastname;
}

// names from table #2
$command2 = "SELECT * FROM table_sort2 ";
$result2 = mysqli_query($db, $command2);

while($row = mysqli_fetch_assoc($result2)){

    $firstname = $row['firstname'];
    $lastname =  $row['lastname'];
    $array_list[] = $firstname."-".$lastname;
}

// names from table #3
$command3 = "SELECT * FROM table_sort3 ";
$result3 = mysqli_query($db, $command3);
while($row = mysqli_fetch_assoc($result3)){

    $firstname = $row['firstname'];
    $lastname =  $row['lastname'];
    $array_list[] = $firstname."-".$lastname;
}

print_r($array_list);

You can use the variable $page_title in the head section to create the page title within the meta tags. The example is shown below.

<?php
//get the url of the page with the curl() function
$my_url = curl();

$findme = 'mysite.com/category/subcategory';
$pos = strpos($my_url, $findme);

if ($pos == true) {

    $my_url_trimmed = str_replace("http://www.mysite.com/category/subcategory/", "", $my_url);

    $command = "SELECT tb1.id, tb1.col1, tb1.col2 from tablename as tb1 WHERE tb1.id='$my_url_trimmed';";
    $result = mysqli_query($db, $command);
    if ($result && mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {

            $space = " ";
            $gap = " | ";
            $location = $row["col1"];
            $page_title = $row["col2"] . $space . $location . $gap;

        }
    }
}

<title><?php echo $page_title; ?> </title>

Why Use Node JS

Throughout the past few years, node.js has caught alot of people’s attention, including myself. So, I hope to explain in my own words, when and how I would use node.js. This is written from the perspective of a web developer who dominantly hand codes PHP, mySQL, HTML and CSS programmer. 

After Googling many different queries about node.js, you often find nothing about node.js vs html. Since basic Bootstrap websites will be more efficient than using a server side language, this can be chalked up as old school technology still being the most effective, especially with caching. So, for a small website with under 8 pages and hardly any future changes, HTML would be unbeatable, at least until someone tells me convincingly different.

With all that said, I spent the better part of a week setting up node applications…including Ghost. After the usual ‘things not going real smoothly’,  I did end up getting everything to work out on an Ubuntu 14 installation and learned the basic ins and outs of the setups; including startup scripts with Linux.

About The Present

When I look at these three links from w3techs.com, it shows how WordPress is still dominating market share and PHP is over 81% of the server side market share. Javascript shows only 0.2% market share and Node.js shows 0.1%.

http://w3techs.com/technologies/overview/content_management/all
http://w3techs.com/technologies/overview/programming_language/all
http://w3techs.com/technologies/details/ws-nodejs/all/all

Back to WordPress. The reason I use the WordPress example is to show that it is increasing in usage and market share. The link http://w3techs.com/technologies/details/cm-wordpress/all/all shows this.

What I am trying to get at here is that from a web developer’s perspective, there are so many WordPress and PHP sites that taking over these works or rehosting them is likely going to happen in the form of their current technology, or from using httrack to convert them to plain, old HTML. Making a makeover to Node will take more time and unlikely be appealing, especially cost-wise to a client.

So, from a typical web developer’s point of view, turning your back on popularity is not an option. On top of that, the race for better hardware is always on the up and up. So, although technology can make leaner, faster code, hardware can do the same.

And, for new websites, lean coding, strong caching(like Smarty Caching with PHP) and Varnish, and the realism that most clients are only capable of so much local traffic, I would likely not go to node.js. No only would the site take longer to build, but, the pros do not outweigh the cons.

Now, where I could use Node would be with the Ghost blogging platform because it is easy to setup, clone, and use. Also, it runs very fast and has decent documentation and templates.


When I Would Use Node JS

To put it bluntly, I would only use node.js to develop a web application that would need the ability to be very fast and handle very many users, or, with the Ghost blogging platform or newer complete applications that have a proven track record.

Typically, a custom node.js application would be a web developer’s dream application that had this potential to grow and prosper. However, realistically, this excludes almost any building of a typical small business website, or web application that would unlikely handle enough users to overload the hosting environment.

As far as custom coding goes, it would take some transition since it reminds me of a new experience with Smarty templating, using a PHP Framework, or trying to customize Joomla for the first time. Since node.js has synchronous and asynchronous ways of doing things, it is best to test and try rather than write code that will cause issues down the road.


Multi MYSQL Database Backup

With Cpanel and the mySQL console it is quite easy to backup a single mySQL database. But, if you have been in a situation where you are backing up a Cpanel account or have another scenario that includes multiple mySQL databases, you may find single mySQL database backups redundant.

Here is what you can do to back them all up in one shot.

Option# 1 Linux Command Line

 root# mysqldump -u root -p --all-databases > /home/username/alldbs.sql 

Option #2

Another option is to use a bash script and run it from the command line. Here is a link to a page that has this info.

Resizing a Fixed Size Virtual Machine Using Virtualbox on Windows

Although it could be a hindsight or a mistake, you could have a Virtual machine that is almost out of disk space and you feel your only option is to resize it. If this is the case, this lesson will explain how you can do that.

The first step is to clone the fixed disk sized Virtual machine. The code is shown below.
In order to do this, you will need to open up the Command Prompt with administrative priviliges. For example, you may find it at All Programs >Accessories >Command Prompt. Just right click to open as an administrator.

Once you have opened it, you will need to navigate to the folder where the VBoxmanage.exe file is located. In this case, it isn located at ‘C:\Program Files\Oracle\VirtualBox’.

 cd C:\Program Files\Oracle\VirtualBox 

The next step is to use the clonehd command to clone a VDI file. The example is shown below and it uses 2 parameters at the end to state the VDI file type and to make it a standard VDI. A standard VDI is dynamic and resizable, unlike the original.

 VBoxManage.exe clonehd "C:\Users\ted\VirtualBox VMs\Ubuntu 14_04 64-bit Clone\Ubuntu 14_04 64-bit Clone-disk1.vdi" "C:\Users\ted\VirtualBox VMs\Ubuntu 14_04 64-bit Clone\Ubuntu 14_04 64-bit Clone-disk2.vdi" --format VDI --variant Standard 

Resizing the Disk Space

The command below can be used to resize the new clone into your desired size. In this case, it was made to be about 10 GB.

 VBoxManage modifyhd "C:\Users\ted\VirtualBox VMs\Ubuntu 14_04 64-bit Clone\Ubuntu 14_04 64-bit Clone-disk2.vdi" --resize 10000 

For more instructions, you can see a previous article about resizing dynamic disks used with Virtualbox.


How To Transfer a Domain From Godaddy To Dynadot

2) Login to your Dynadot account.
2) Select ‘Your Account’.
3) Scroll down the page and look for Transfer Domain on the right hand side.
4) Login to GoDaddy and go to the desired domain you want to transfer. Domain Manager will have your list of domains.
5) Unlock the domain and get your AUTH code emailed to you.
6) Back at Dynadot, add the domain you want to transfer anbd put in the AUTH code.
7) At this point, you can check out the shopping cart with Dynadot.
8) Now, you will get an email from Godaddy to ‘Accept ‘ or ‘Decline’ the transfer. You obviously click ‘Accept’.
9) Finally, you just need to wait out the process.

Executing PHP Queries Within a Class With PHP / MYSQL

I will keep this example short and sweet. The whole idea here is to pass the database connection into a PHP class. Within the class, the queries will execute and the results are returned as a usable string.

The Class

  class MyClass
{
    public $number;
    public $PDO;

    public function __construct($PDO)
    {
        $this->number($PDO);
    }

    public function number($PDO)
    {
        $command = "SELECT number FROM tablename WHERE id > 0 LIMIT 1 ";
        $result = $PDO->prepare($command);
        $result->execute();

        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $this->number = $row['number'];
        }
    }

    public function __toString()
    {
        return $this->number;
    }
}

Using Bootstrap or Skeleton CSS Frameworks Can Make Like Easy For Web Developers

This topic comes from a scenario for which a web developer decides to learn and understand CSS frameworks Like Bootstrap and Skeleton. After 3 years of dominantly programming PHP / mySQL applications and working mostly with static templates at work and some old school fluid templating, I began to build some responsive web applications and a handful of websites that used these frameworks.

Since the css classes were so sensitive, I kept modification of the template simple; such as removing unwanted divs that contained the ‘row’ class.

At first, I was intimidated because I remember someone with weak HTML / CSS skills struggling with it daily. With a quick look under the hood, it was quite different than typical CSS coding and the classes and new tags were unfamiliar and the floating methodology was new at the time.

Although using a CSS framework was a little intimidating at first, a light did eventually go off after coding with them on various occasions. All of a sudden, not only did these responsive frameworks make websites display so conveniently on all devices, but, actually coding a web application with them became easier with them than coding with traditional CSS.

The reason for the simplicity was the modular aspect of a CSS framework and the power of the classes. In many cases, the classes do great work and that minimalizes minor styling touch ups, if not at all. On occasion, you may want to add an id to an element that has a class, add some custom css, then move on.

Suddenly, the layout and each ‘row’ class and its subset of columns was so easy to work with and to use with PHP / mySQL.  

Essentially, the bottom line is that using a Framework like Bootstrap or Skeleton can make your web pages look good and clean without taking a lot of time to achieve this effect. Thus, this allows for many instances to bypass any web design extras, asides from spending $5 here and there on Fiverr, Shutterstock and Fotolia for quality images. 

Alternatively, using a framework can allow you to know how long a web designer should be able to complete tasks, if you decide to use one.

Some of the built in features to CSS frameworks are Font Awesome and icons. Using special class names will provide you with some extra styling as needed. 

Below are some basic links to get you started with Bootstrap.

LINKS

Bootstrap Basics
Bootstrap and LESS Tutorial

Bootstrap Basics

Bootstrap and Skeleton Frameworks help you create responsive websites very quickly and easily. With this brief lesson, you will be shown some very basic tips for creating and working with the Bootstrap framework.

Using the Framework

In order to use the Bootstrap Framework, you need to download it from http://getbootstrap.com/ and move the core folders into your document root. Thus, you will have the three folders;  css, fonts and js.

The next step is to add a link into the head of your HTML file.

<link href="css/bootstrap.min.css" rel="stylesheet">

At this point, you can start using Bootstrap. Since this is a very basic tutorial, I will attempt to explain the very basic classes that can be used to give solid, desirable, responsive results.

Container Class

The container class is the parent class that holds everything together and normally exists after the opening ‘<body>’ tag. It is a one time deal.

<div class="container">
</div>


Row Class

The row class contains a responsive group. Think of it like a class that holds one or more columns and puts them in order for a specific screen size. The first row can be used to create columns and a sidebar for the entire document.

You can have as many row classes as you want and they will present themselves to the viewer in the same order they are coded. Thus, if the first ‘row’ class has two columns and the second class has three columns, you will see all items of the first row class appear before you will see any items of the second ‘row’ class.

For example, on a home PC, you may see the first row class with 2 columns followed by the second row with 3 columns while the mobile phone user may see 7 single columns; all in order as they are coded.

In order as coded means that the first column in the ‘row’ class always appears first, followed by the second and so forth.

<div class="row">
</div>


Column Class

The column class, or classes, are children classes to the ‘row’ class. They are name with ‘col-md-*’. For example, they could named something like ‘col-md-12’, ‘col-md-6’, ‘col-md-4’.

The key to using these classes are to remember that all children classes that are used must add up to 12. For example, If you plan to have two columns, you would have two classes that are both named ‘col-md-6’. Meanwhile, a three column layout would use ‘col-md-4’.

The code belows shows a column that would expand the entire width.

<div class="col-md-12">
</div>

Putting it all together

<div class="container">

    <div class="row">

        <div class="col-md-12">
        </div>

    </div>

</div>

Other Possibilities

With those basics in mind, you can create layouts with multiple columns. To go one step further, you could make custom layouts within a row. Thus, you could have a large column that represents the main body with a class like ‘col-md-8’ and a sidebar with a class like ‘col-md-4’.

Below, is another example to create your main page and sidebar. This example uses the wrapper id, sidebar-wrapper-id and page-content-wrapper id.

<div id="wrapper">

    <!-- Sidebar -->
    <div id="sidebar-wrapper">
    </div>

    <!-- Main Page -->
    <div id="page-content-wrapper">
        <div class="container-fluid">
            <div class="row">
                <!-- Main Body Goes Here -->
            </div>
        </div>
    </div>

</div>

Simple Bootstrap and LESS Lesson

This tutorial will help get you up and running with the popular Bootstrap framework so that you can quickly create ad edit responsive websites using these tools.

Download Bootstrap

1) Download from http://getbootstrap.com/getting-started/

When you arrive here, you have serveral download options. You can download ‘Bootstrap’ and use it right away, or you can download the ‘Source code’ if you want to use LESS. 

The basic download will contain 3 folders; css, fonts and js while the source code will have a folder called ‘less’ which contains the ‘.less’ files for which can be coded using LESS pre-processor.

Although it is very easy to use the basic download that contains CSS files, using LESS has many advantages, especially on some projects where you want to use extra features like variables.

For example, setting a variable like @green : #1ed84a is much easier to reference than trying to remember a color for a new class or using a tool like ColorZilla to find a color.

The code below shows how easy it is to create the variable @green that can be used to represent a typical hex code #1ed84a. Two classes are shown below; one using LESS, the other using a conventional css class. 

@green : #1ed84a  
.my-class-less{color:@green}  

.my-class-conventional{color:#1ed84a;}

Using A Compiler

When you work with LESS files, you have a couple of of options. Option number one is to add links to the document head and the other is to dowload a free compiler and do them on your own PC.

If you compile them on your own PC, they ‘.less’ file extension will get converted to the ‘.css’ format with the same name. Thus, bootstrap.less will be the working file that will create a browser copy called ‘bootstrap.css’. 

 
You will need to download the source code if you want to use LESS and compile it. Working with less is a lot like using SASS or very basic programming using language like PHP, Python or PERL. On a basic level, you can declare variables and nest rules within a class.  
 
 
Using Javascript To Compile Less Files
 
This method allows you to hand code your bootstrap.less file and upload it to the server without having to convert it to the ‘.css’ extension.
 
1) Download less.js from http://lesscss.org/ 
2) Include links in the head to the bootstrap.less and less.js files. The key difference from a css stylesheet is that it has the attribute rel=”stylesheet/less” rather than rel=”stylesheet”.
<link rel="stylesheet/less" href="css/bootstrap.less">
<script src="js/less.js"></script>
Using a Compiler

After you downloaded the Source Code from the Bootstrap website, you can use your compiler right away. This will be covered shortly in detail. 

To keep it simple, create a css folder within the parent folder that contains subfolders like dist, docs, fonts, grunt, js and less. 

 
You can get your free compiler at Winless at http://winless.org/ or Simpless at http://wearekiss.com/simpless.
 
For simpicity, this tutorial uses Winless as the compiler. 
 
To Use and Compile With Winless

1) Open the Winless program. 

2) Add the less folder > Click ‘Compile’. Afterwards, you will see that the css folders now has css files created from those LESS files. 

Bootstrap and Less Tutorial

How to Show and Hide images With Jquery

The goal here is to be able to show and hide images with a single click. The code below will load the pages and its images by default. But, the viewer will have the option to hide them, or re-display them by clicking a button. The code bwlow contains the html with an image and the jquery that shows and hides it.

Jquery

Here is a quickrunover of the code below. When the ‘.hiding_them’ class is clicked, the function is triggered. Then, we check for image visibility. If the image is visible, it becomes hidden. On the contrary, hidden images will show up.

<script type="text/javascript">
       
        $(document).ready(function () {
            $('.hiding_them').click(function () {

                if ($('img:visible').is(":visible")) {

                    $("img").hide();
                } else {
                    $("img").show();

                }

            });
        });

    </script>
       
      

HTML

The input button has the class name ‘hdining_them’. Jquery will repond when that class is clicked.

<form id="myform" action="">
            <input class="hiding_them" type="button" name="hide_images" value="Show | Hide Images"/>

        </form>

Binding PDO Database Parameters With PHP

The purpose of this tiny tutorial is to enforce how to bind parameters properly when using PDO for all of your database queries. For starters, as you have read, binding parameters to prepared statements puts potential SQL injections on the backburner. The process is rather simple. You create a query and use something like ‘:my_parameter’.

The parameter can be any variable. However, if you plan to use $_POST or $_SESSION variables, you must must set a variable equal to their value first. Thus, you plan to use a $_SESSION variable parameter like ‘$_SESSION[‘session_id’]’, you would write the code as shown below.

$my_session = $_SESSION['session_id']; 
$result->bindParam(':my_session', $my_session);

You cannot write it like the code below.

$result->bindParam(':my_session', $_SESSION['session_id']);

One more point to make is that you cannot bind parameters that will not be used. As you see below,  ‘:my_name’ is not used in the mySQL query.

$command = "SELECT DISTINCT id, url FROM urls WHERE enabled='1' AND user_id =:my_session";

    $result = $PDO->prepare($command);
    $result->bindParam(':my_session', $my_session)
    $result->bindParam(':my_name', $my_name);
    $result->execute();
}

Unlike the code above, the code shown below will work since the bindParam() is using all parameters that exist in the mySQL query.

$command = "SELECT DISTINCT id, url FROM urls WHERE enabled='1' AND user_id =:my_session";

    $result = $PDO->prepare($command);
    $result->bindParam(':my_session', $my_session)
    //$result->bindParam(':my_name', $my_name);
    $result->execute();
}

Jquery Removing a Table Row and Updating Backgrounds

This tutorial will show you you can remove a table row from the page and update the alternating background colors.

Until every programming language makes almost as much sense to your first speaking language, you may want to go thorugh the code below and translate it so that you can understand the process. Well, I will even help you with that this time.

Okay, once the submit button with the ‘contacted’ class is clicked, the function does its thing. The submit button exists in each table row. Therefore, the next line basically says remove this submit button’s first table row parent. That will remove the row and that includes the button you just clicked.

Since the original row above could have a blue background and the one below a blue background, the page could look ‘yucky’ since there won’t be that nice alternating color scheme. Well, not worry because the next two lines of code give each even and odd row a new background color so that everything stays nice and uniform.

<script type="text/javascript">
    $('.contacted').click(function () {

        $(this).parents("tr").first().remove();

        /*
         Toggle table rows
         */

        $("tr:even").css("background-color", "#fff");
        $("tr:odd").css("background-color", "#E2E4FF");

    });

</script>

Very Basic PHP and Ajax Tutorial

This tutorial will show a very simple setup to use Ajax with PHP. I will give a brief overview of the process. When the submit button with the ‘contacted’ class is clicked, the function goes to work. The myurl variable has the ‘myurl’ class and takes its value. It is the sibling of the submit button. If you look at the html, you can see the input elements are indeed siblings. 

After that, the Ajax call begins. A post request takes place and the value of the ‘myurl’ variable is transfered to the my_ajax.php file. At this point, the my_ajax.php file has a new post variable called my_variable. So, when you open up the my_ajax.php file, you can write code to do whatever you want with the variable $_POST[‘my_variable’].

Jquery / Ajax

<script type="text/javascript">

    $('.contacted').click(function () {

        var myurl = $(this).siblings('#myurl').val();

        $.ajax({
            type: "POST",
            cache: false,
            url: "my_ajax.php",
            data: { my_variable: myurl },

            success: function (msg) {
//  alert("Success!");
            }
        });
    });
</script>


HTML

<form method="POST" action="">
            <input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
            <input id="contacted" class = "contacted" type="submit" name="contacted" value="Submit"/>
</form>


Post URL

$source_url = $_POST['my_variable'];

Posting a select form On Change With Jquery

With this example, you will see how you can post a form when you change a value from a drop down select element.

Jquery Code

The code below can be translated to mean the following. When the ‘myclass’ class is changed from a user selecting a different option, that form is automatically submitted.

<script type="text/javascript">

    $(document).ready(function () {
        $('.myclass').change(function () {
            $(this).closest('form').trigger('submit');
        });
    });
</script>

HTML Select Element

WThe select element has a class called ‘myclass’ and its name attribute is my_item.

 <select class="myclass" name="my_item">      
    <option value="all">All</option>     
    <option value="1">One</option>     
    <option value="2">Two</option>  
</select>

Run a Windows Program With PHP On XAMP or WAMP

Here is an example of using a Windows Program within PHP. The example will use the software called httrack.

The code belows shows how the PHP exec() function is using the httrack.exe file. 

 exec('C:\Users\username\Documents\AAA\WinHTTrack\httrack.exe http://' . $url . '/  -O "C:\xampp\htdocs\CLONES\' . $url . '"  -%v -%e0 2>&1;'); 

Important:

By default, httrack install to Program Files. That white space between ‘Program’ and ‘Files’ on Windows will cause issues. So, you can copy the entire WinHTTrack folder to a path that has no whitespace. In this case, it was copied into the Documents\AAA folder.

By default, you will be able to use the service now, but, it could time out when cloning a website.

An example of a timeout is:

Fatal error: Maximum execution time of 30 seconds exceeded

To alter the timeout setting,
1. Open the file:
c:\xamp\php\php.ini
2. Change:
max_execution_time=30

Change to:
max_execution_time=120
3. Save the file and restart Apache. See setup, cloning and quick usage in action.


Using Centos To Run Shell Commands With PHP Scripts

Linux has all sorts or neat packages you can install. Luckily, you may want to use one of them from a PHP script. This brief tutorial will explain how to do this.

The code below takes a submittted form and gathers the url into variable called $url. Then, the httrack service is used to clone the desired website.

 shell_exec('/usr/local/bin/httrack http://' . $url . '/  -O "/home/username/websites/     ' . $url . '"  -%v -%e0 2>&1;'); 

Besides PHP, you need to make modifications to the /etc/sudoers file on Linux. The change is shown below. 

 username ALL=NOPASSWD: /usr/local/lib/httrack,/usr/local/bin/httrack 

Now, when you open the folder /home/username/websites/ you will see the new clone.

Here is a simple may to open the new cloned folder with the Linux shell:

 cd *example.com 

ProFTP File Restrictions

With Pro FTP, you can quickly add conditions to an FTP account. There can very a variety of reasons why you would want to limit FTP to certain files types. For example, let’s say you hired a web designer from overseas to work on a project.

Without placing file restrictions, he could potentially transfer PHP, Perl or Python files which could snoop around your system or reveal sensitive data. Or, he could create an ‘.htaccess’ file and do all sorts of undesirable stuff like allow .txt files to be interpreted as php.

With shell access, you can easily restrict the files that can be transfered with ‘PathDenyFilter’. The example below will demonstrate its usage. First of all, the line starting with ”PathDenyFilter’ is added to the file /etc/proftpd.cond. After that, the ftp services is restarted. If you attempt to transfer a file like .htacccess, or one with an extension like ‘.pl’ or ‘.php’ you will fail. 

 <VirtualHost 70.90.148.999>   ServerName ftp.example.com   AuthUserFile /etc/proftpd/example   MaxClients 3 "Sorry, this ftp server has reached its maximum user count (%m).  Please try again later"   DirFakeGroup On ftpgroup   DirFakeUser On ftpuser   DefaultRoot ~    PathDenyFilter "(\\.ftpaccess|\\.htaccess|\.(pl|php))$" 

Using Ubuntu and Debian To Run Shell Commands With PHP Scripts

Linux has many great packages that you can install use with some command line knowledge. However, there may come a time when you run to use a package and execute the commands from a web browser.

Typically, PHP functions like exec() and shell_exec() can be used to run basic commands that can navigate folders and read files.

But, what if you want to use a package and run a command within the browser? To do this, you will need to allow www-data to become sudoer user and allow it to use the package without a password. This article will explain how to do that.

By default, Apache will run with the user www-data. So, open up that /etc/sudoers file and give Apache permission to use the desired service(s). For this example, we will use the service httrack.

 www-data ALL=NOPASSWD: /usr/bin/httrack 

Now, we can run the exec() and shell_exec() functions to use httrack.The sample code would copy the files in root folder and skip the rest of the stuff since it only goes 1 folder deep.

 <?php shell_exec('sudo httrack "http://example.com/" -O "/websites/example.com" -v -s0  --depth=1'); 

Setup mySQL Database

If you want to use the command line to setup a mySQL database without any fuss, you have landed on the right page.


Setup Database With Existing User

The next set of mySQL commands do several things. The first line is used to gain access to mySQL using the root user and password. That command is made in Linux. One authentication is approved, a database is created within the mySQL console. After that, all privileges are granted to the user my_username@localhost.

After that, the the grant tables are reloaded using teh ‘FLUSH PRIVILEGES’ command. Finally, the exit command is used to get back to the Linux command line.

 root# mysql -u root -p  Enter password:  
mysql> CREATE DATABASE my_database;  
mysql> USE my_database; 
mysql> GRANT ALL PRIVILEGES ON my_database.* TO 'my_username'@'localhost'  
mysql> FLUSH PRIVILEGES;  
mysql> exit

Setup Database and User

These instructions are the same as the example above, except that a user is created. It contains only one extra command with the mySQL console.

 root# mysql -u root -p  Enter password:  
mysql> CREATE DATABASE my_database;  
mysql> USE my_database; 
mysql> CREATE USER 'my_username'@'localhost' IDENTIFIED BY 'my_password';  
mysql> GRANT ALL PRIVILEGES ON my_database.* TO 'my_username'@'localhost'  
mysql> FLUSH PRIVILEGES;  
mysql> exit

Once the database is setup, you can use the mySQL console or phpMyAdmin to create, update and delete databases. With phpMyAdmin, you can import sql files to load up the database.

You can also run Linux commands to dump data into it. Here is a page to reference how to dump data with Linux.


Acronis Cloning Errors

Using Acronis True Image is a great way to backup computers for web developers and programmers. Since these types of users often have multiple partitions, specific software for specific systems and perhaps many Virtual machines running on various operating systems, having a good cloning tool can make it easy to avoid the hassle of starting from scratch if s hard drive fails.

Thanks to Acronis True Image, it does have a nice feature to clone a complete disk using its clone tool. In order for this to happen, you need to have a PC with two hard drives; such as a laptop with two hard drive bays.

Although Acronis works very smoothly with Windows and will clone all partitions, including Linux, it can have its hickups when you clone systems other than Windows. But, it can be done. This tutorial will guide you through common problems and how to fix them.

After a cloning operation has completed successfully, Windows or Linux could have booting errors; especially if GRUB is fired up upon boot.

Recently, after cloning a hard drive with Linux and Windows, Linux failed to boot and Windows booted but had an annoying error.

To solve these problems, I had to match the proper UUIDs to each machine. With Linux, things are done a certain way and with Windows setting the UUID was different.

Essentially, with Windows, the UUID was updated by changing the UUID in GRUB, while Linux has a simpler commands which fixed the same problem.

This tutorial will explain how those fixes in detail.

LINUX

When I tried to boot into Linux, I received the error ALERT! /dev/disk/uuid/5467d38a-3517-4b79-9efa-8a4973852mom does not exist.

After that, I booted an Ubuntu Live USB and ran the blkid command to get all partition UUIDS.

kent # blkid
/dev/sda1: UUID=”0e8d4ae6-3943-4955-93c9-7e482fc664d8″ TYPE=”ext4″
/dev/sda4: UUID=”0e7r4ae9-3333-2222-93u9-7e482fc664r5″ TYPE=”ext4″
/dev/sda5: UUID=”6222d38a-3517-4b79-9efa-8a4973855dad” TYPE=”swap”
/dev/sdb1: LABEL=”ACER” UUID=”1AA8B3C0A8B39952″ TYPE=”ntfs”

From that list, Windows was the nfts while Linux was /dev/sda4.

With Ubuntu Live, mount the desired partition just to make sure the fields are the one you expect for the partition that is not booting.

mount /dev/sda4 /mnt
cd /mnt
ls
cd /home

Now that you are absolutely certain about the UUID and the partition, run the command

tune2fs /dev/sda4 -U 5467d38a-3517-4b79-9efa-8a4973852mom

Now, if you run the command blkid a second time, you will see it us updated. Now reboot without the Live cd or USB and Linux should work as expected. If not, you can always update /boot/grub/grub.cfg file for the root partition, which in this case is Linux. So, if you mount the partition witrh errors and open the /boot/grub/grub.cfg file, you can change the UUIDs there. Just find the error UUID and replace it with the proper one from the blkid command.

WINDOWS

For Windows NFTS partitions, another story. You could get this error:

error: no such device: 0741bc23-b3df-4580-8595-0f55d61c0182
Press any key to continue…_

Although you can press a key right away and get the Windows Bootloader, it can seize after time and it is always a good idea to fix a problem anyways. If this is the case, you need to edit /boot/grub/grub.cfg Good idea to make a backup first. After that, use the blkid command again to get the ID of the Windows partition. Then, replace it with the erroneous one. Finally, run the command update-grub.

Now, all errors should be gone and you have can boot without any error messages.


NOWDOC vs HEREDOC With PHP

With PHP, you can use NOWDOC and HEREDOC strings as opposed to traditional single quoted or double quoted strings. Using HEREDOC and NOWDOC strings can make life easier; especially when you have long strings with many single quotes, double quotes and variables.

NOWDOC

The NOWDOC string below starts with <<<‘SQL’ and end with SQL; followed by no whitespace. The name SQL was chosen since this is an SQL string. But, any other matching name like EOF could have been used in its place to yield the same results.

For large mySQL dumps such as resetting a mySQL database, using NOWDOC is an easy method to write a very long or complex query to use with a function like mysqli_query(). An example of this with our code would be:
$result = mysqli_query($db, $my_nowdoc)
.

<?php
$variable1b= 'test1'; 
$variable2 = 'test2'; 
$my_nowdoc = <<<'SQL'
INSERT INTO `tablename` (`blogger_id`, `blog_id`, `cat_id`, `title`, `notes`, `date_posted`, `date_deleted`) VALUES
(1, 286, 4, 'Codes-PHP-', '<p>$variable1b;</p>\r\n<p>$variable2 = 'all';</p>\r\n<p>Here is a new line</p>\r\n<p>Eventually it must cut off.</p>\r\n<p>Cut off.</p>\r\n', '2014-09-18 22:52:45', '0000-00-00 00:00:00'),
(1, 282, 2, 'Images-Width-100-Percent', '<p><a href="http://yahoo.ca">test</a>what</p>\r\n<p style="width:100%"><img src="images/promo.jpg" style="width:100%"></p>\r\n', '2014-08-27 23:37:39', '0000-00-00 00:00:00'),
(1, 303, 2, 'New-Steely-Dan-Post', '<p><img alt=\\"\\" height=\\"auto\\" src=\\"images/how-to.jpg\\" width=\\"100%\\"></p>\r\n', '2014-10-28 12:01:39', '0000-00-00 00:00:00')
SQL;

echo $my_nowdoc;

HEREDOC

The HEREDOC string below starts with <<<SQL and end with SQL; followed by no whitespace. The difference between this example and the one above is that there are no single quotes on the first line since it is those quotes that separate the NOWDOC from HEREDOC. Although the name SQL was chosen, any other matching name like EOF could have been used in its place to yield the same results.

<?php
$variable1b= 'test1'; 
$variable2 = 'test2'; 
//$my_nowdoc = <<<'SQL'
$my_heredoc = <<<SQL
INSERT INTO `raspberry_blogs` (`my_blogger_id`, `blog_id`, `cat_id`, `title`, `notes`, `date_posted`, `date_deleted`) VALUES
(1, 286, 4, 'Codes-PHP-', '<p>$variable1b;</p>\r\n<p>$variable2 = 'all';</p>\r\n<p>Here is a new line</p>\r\n<p>Eventually it must cut off.</p>\r\n<p>Cut off.</p>\r\n', '2014-09-18 22:52:45', '0000-00-00 00:00:00'),
(1, 282, 2, 'Images-Width-100-Percent', '<p><a href="http://yahoo.ca">test</a>what</p>\r\n<p style="width:100%"><img src="images/promo.jpg" style="width:100%"></p>\r\n', '2014-08-27 23:37:39', '0000-00-00 00:00:00'),
(1, 303, 2, 'New-Steely-Dan-Post', '<p><img alt=\\"\\" height=\\"auto\\" src=\\"images/how-to.jpg\\" width=\\"100%\\"></p>\r\n', '2014-10-28 12:01:39', '0000-00-00 00:00:00')
SQL;

echo $my_heredoc;

HTML HEREDOC

The example below shows how to make an HTML page into a HEREDOC string and print it.

<?php
$my_html_heredoc = <<<HTML
			<!DOCTYPE HTML>    
<html>
    <head>
        <title>My Page</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <meta name="description" content=""/>
        <meta name="keywords" content=""/>
        <link rel="stylesheet" href="css/style.css"/>        
    </head>

<body class="right-sidebar">

    <!-- Header Wrapper -->
    <div id="header-wrapper">

        <!-- Header -->
        <div id="header" class="container">

            <!-- Logo -->
            <h1 id="logo"><a href="#">MyTitle</a></h1>
                <!-- Nav -->
    <nav id="nav">
        <ul>
            
            <li>
                <a href="index.php">Blog</a>

            </li>
            <li>
                <a href="about.php">About</a>
            </li>
            <li class="break">
                <a href="help.php">Demo</a>
            </li>
            
            <li><a href="login.php">Login</a></li>
        </ul>
    </nav>

        </div>

    </div>

    <!-- Main Wrapper -->
<div class="wrapper">

    <div class="container">

        <div class="row" id="main">

            <div class="8u">

                <div><h3 class="help-h3"MySubheading</h3></div>

                <!-- BEGIN SEGMENT-->
                <div>
                    <div id="setup"><strong>How It Began</strong></div>
                    <div>Any text can go here.
                    </div>
                </div>
                <!-- END SEGMENT-->            

            </div>
           
        <div class="my-clear"></div>
    </div>


<!-- BEGIN ALL PAGES ON WEBSITE -->
<div class="row features">  
        
        <header>
            <h3>Use On Any Device</h3>
        </header>
        <p>Line #1</p>
        <ul class="actions">
            <li><a href="#" class="button">Next Line</a></li>
        </ul>  

</div>

</div></div>

</body>
</html>
HTML;

echo $my_html_heredoc;

PHP String Functions Cheatsheet

    addcslashes
    -escapes all characters C style

    addslashes
    -escapes some characters with backslashes.

    bin2hex
    -converts a binary string to hexadecimal

    chop
    -removes whitespace from the far right of a string

    chr
    -returns a specified character from a string

    chunk_​split
    -makes smaller chunks out of the specified string

    convert_​cyr_​string
    -used to convert Cyrillic character

    convert_​uudecode
    -used to decode a uuencoded string

    convert_​uuencode
    -used to encode a string with a uuencode algorithm

    count_​chars
    -used to give a count for the number of characters within a string

    crc32
    -used to get the crc32 checksum of a string

    crypt
    -creates a one way hashed password-like string

    echo
    -used for printing

    explode
    -convert a string to an array. Can separate if the string has blank spaces between words or another character like a comma.

    fprintf
    -used to write formatted text to a stream

    get_​html_​translation_​table
    -get html entity translations for htmlspecialchars and htmlentities. Gives a nice readable list in the form of an array.

    hebrev
    -converts text from hebrew

    hebrevc
    -like hebrev function except that it will convert newlines ‘\n’ to “<br>\n”.

    hex2bin
    -converts a string from hexadecimal to binary

    html_​entity_​decode
    -decodes from html entities to the actual character.

    htmlentities
    -creates html entities from various characters; like quotes, html and symbols.

    htmlspecialchars_​decode
    -decodes characters to their actual html code.

    htmlspecialchars
    -translates special characters like html, quotes and symbols into special translatable characters.

    implode
    -converts an array into a string. You specify the character you want to use separate the items that came from the array.

    join
    -alias of implode

    lcfirst
    -turns the first character of a string to lower case

    levenshtein
    -used to calculate ditsnaces between 2 strings

    localeconv
    -used to get numeric formatting information

    ltrim
    -removes whitespace from the beginning of a string

    md5_​file
    -used to get a md5 hash from a specified file.

    md5
    -used to create an md5 hash of a particular string.

    metaphone
    -used to get a metaphone key of a string

    money_​format
    -Get a number formatted for a specified currency

    nl_​langinfo
    - a non Windows function that can receive the laguage and locale info. Can pass a constant into the function.

    nl2br
    -changes ‘\n’ to ‘<br/>’. Useful when going from running a script in the browser vs the Linux command line.

    number_​format
    -specify decimal points in a number

    ord
    -returns the first character in a string as an ascii value.

    parse_​str
    -parses a string into variables. The string that is parsed contains the usual method of writing like var1=value1&var2=value2.

    print
    -prints a string

    printf
    -prints a formatted string

    quoted_​printable_​decode
    -Makes an 8-bit string from a quoted printable string

    quoted_​printable_​encode
    -makes a quoted printable string from an 8-bit string

    quotemeta
    -Returns a string with backslashes around the characters

    rtrim
    -removes whitespace from end of a string

    setlocale
    -used to set locale info

    sha1_​file
    -get the hash value for a file

    sha1
    -create a sha1 string from a specified string. If true, the hash is 20 charaxters; unlike the default 40 characters.

    similar_​text
    -used to calculate the similarity between 2 strings. Matches tghe characters in the first string that are in the second string, including whitespace. Then, divides by total characters.

    soundex
    -used to get the soundex of a string

    sprintf
    -used to return a formatted string

    sscanf
    -used to parse input from string according to the specified format

    str_​getcsv
    -turns a csv into an array

    str_​ireplace
    -find and replace from a string. This is the case insesnitive version of sttr_replace() function.

    str_​pad
    -used to add whitespace or characters to the specified side of the string. By default, it adds whitespcahe to the end of the string. The numerical parameter specifies the total length of the string.

    str_​repeat
    -used to repeat a string the desired amount of times.

    str_​replace
    -find and replace characters from a string.

    str_​rot13
    -transforms string to rot13 version.

    str_​shuffle
    -shuffles all characters to a random position.

    str_​split
    -converts a string to an array. By default, each character is an item in the array. If you add an integer parameter, it will create an array from 0 to the specified number.

    str_​word_​count
    -used to get the word count from a string.

    strcasecmp
    -compares case insensitivity of two strings

    strchr
    -the alias of strstr() function

    strcmp
    -used to compare 2 strings and is case sensitive.

    strcoll
    -string comparison that is locale based

    strcspn
    -compares 2 strings and finds the length of string 1 for which there are no characters from string 2.

    strip_​tags
    -removes html tags. Can alsom specify which pnes you do not want to strip.

    stripcslashes
    -strips backslashes

    stripos
    -find if the string exists in a string. The first parameter is the haystack and second is the needle. Remember that first position is zero. This means you need to compare as identical.  

    stripslashes
    -used to strip backslashes from a string

    stristr
    -the case insensitive version of strstr()

    strlen
    -used to get the length of a string.

    strnatcasecmp
    -case insensitive function that compares strings with a “natural order” algorithm

    strnatcmp
    -compares strings with a “natural order” algorithm

    strncasecmp
    -compares two strings with a desired length.

    strncmp
    -compares 2 strings based on a desired amount of characters

    strpbrk
    -looks for a the desired characters in a string. The new string starts where the first match was made and continues to the end of the string.

    strrchr
    -returns the last occurence of the needle in the haystack and any characters that exist after the last occurrence.

    strrev
    -returns the string with the characters reversed

    strripos
    -finds the position of the last case insensitive occurence of the needle in the haystack.

    strrpos
    -finds the position of the last case sensitive occurence of the needle in the haystack.

    strspn
    -get the length of characters within a string as compared to a mask.

    strstr
    -Look for first occurrence of needle in a haystack. Haystack is the first parameter.

    strtok
    -used to tokenize a string

    strtolower
    -returns the string with all lower case characters

    strtoupper
    -returns the string with all upper case characters

    strtr
    -used to replace substrings

    substr_​compare
    -used to compare 2 strings. Can set how many characters to compare.

    substr_​count
    -find how may times a substring exists in a string

    substr_​replace
    -used to replace a substring with a different set of characters

    substr
    -used to return part of a string

    trim
    -removes whitespace from the beginning and end of a string

    ucfirst
    -makes the first character in a string upper case

    ucwords
    -used to make the first character of each word uppercase

    vfprintf
    -used to write a formatted string to a stream

    vprintf
    -used to output a formatted stream

    vsprintf
    -used to returns a formatted string

    wordwrap
    -wraps a string at a specified length. Can be used to add line breaks at a specific amount of characters.


Cheatsheet for PHP Arrays

The following cheatsheet can be used to remind you of many common array functions that are used with PHP.

   
array_​change_​key_​case
    -changes the array key to upper or lower case
   
array_​chunk
    -makes smaller arrays based on how many items you specify to chunk off. For example, if you have an array of 5 items, it would be two arrays with two items and one array with 1 item.
   
array_​column
    -Can specify a key and it returns an array of only those keys and matching values. The outcome is a single indexed array.
   
array_​combine
    -combines 2 arrays for which one will become keys and the other will become values. The first array will be the keys and the second array will be the values.
   
array_​count_​values
    -counts the number of values in an array. If there are two identical items, that value would be the key and the value would be 2.
   
array_​diff_​assoc
    -returns the different key => value pairs.
   
array_​diff_​key
    -returns ann array of the keys that exist in array 1 that are not present in array 2.
   
array_​diff_​uassoc
    -compares two arrays and returns the differences. Can check keys and values.
   
array_​diff_​ukey
    -compares 2 arrays can return different keys in array 1 that do not exist in array 2.
   
array_​diff
    -compares values of 2 arrays. Keys are not important.
   
array_​fill_​keys
    – turns an array into keys and create a value that you specify.
   
array_​fill
    – create an indexed array with specific keys and create a value for those keys.
   
array_​filter
    – can filter an array to get specific values; like all even or add numbers. By default, it will remove false, NULL and empty values.
   
array_​flip
    -converts the key to a value and vice versa.
   
array_​intersect_​assoc
    -returns the matches for keys and value pairs in both arrays.
   
array_​intersect_​key
    -returns the matching keys of both arrays.
   
array_​intersect_​uassoc
    -returns matching values of two arrays.
   
array_​intersect_​ukey
    -returns matching keys
   
array_​intersect
    -returns values that match in both arrays.
   
array_​key_​exists
    -checks is key exists in an array.
   
array_​keys
    -returns the array keys of the desired array.
   
array_​map
    -Can apply a callback function to perform a function on all items in array. Can use with 2 arrays; like passing 2 values into a custom function.
   
array_​merge_​recursive
    -merges 2 arrays. If the first array and second array have matching keys, the items in the second array will add on to the key from the first array. Then, the other items will be added in sequence.
   
array_​merge
    -Merges arrays. But, if there are matching keys the last one will override. 
   
array_​multisort
    -sort multiple and multidimensional arrays in a desired sequence.
   
array_​pad
    -Adds items before or after the current items. Negative numbers are added before, positive size is added after the current list.
   
array_​pop
    -pops the last item off the array so that you end up with a new array with the popped off item.   
   
array_​product
    -Takes the numbers in array and multiplies them; like removing the comma with a multipication sign.
   
array_​push
    -add items to the end of an array.
   
array_​rand
    -get a random item from an array.
   
array_​reduce
    -reduce an array to a sibgle item using a callback function that can do things like add or multiply all items in an array.
   
array_​replace_​recursive
    -the second array will replace items from the first array. keys from second array will have value override that value from teh first array. Any new keys will be added. 
   
array_​replace
    -Add or replace items from first array.
   
array_​reverse
    -reverses order of array. But, if thhere is an array within the array to be reversed, its values stay as they are.
   
array_​search
    -search for a value and returns the key of that value.
   
array_​shift
    -like array_pop, except the first item is removed from the array.
   
array_​slice
    -remove specified items from array.
   
array_​splice
    -select specified items from an array.
   
array_​sum
    -add all number values in array.
   
array_​udiff_​assoc
    -compare difference in 2 arrays with an index check and by using a callback function.
   
array_​udiff_​uassoc
    -compare difference in 2 arrays with an index check. The data and indexs are compared with a callback function.
   
array_​udiff
    -compare difference in 2 arrays using a callback function.
   
array_​uintersect_​assoc
    -compare the union in 2 arrays with an index check and by using a callback function.
   
array_​uintersect_​uassoc
    -compare union in 2 arrays with an index check. The data and indexs are compared with a callback function.
   
array_​uintersect
    -compare union in 2 arrays using a callback function.
   
array_​unique
    -returns an array without duplicated values. The first value will hold the position in the new array.
   
array_​unshift
    -add items to the beginning of an array.
   
array_​values
    -returns an indexed array with only the values. The orignal keys are lost.
   
array_​walk_​recursive
    -you can apply a function to each key and value in an array. Also works with arrays within arrays.
   
array_​walk
    -you can apply a function to each key and value in an array.
   
array
    -used to lists items of indexed, associative and multidemensional arrays.
  
compact
    -Create an array from variables where the variable name becomes the key and the string value becomes the value.
   
count
    -counts items within an array
   
current
next
prev
end
    -The 4 above functions can be used to grab a specific value from an array. If one is called after another it performs the function based on the last item position.
pos
    -alias of current. Grabs the current value from an array. If this is the first command after an array is set, the current item is the first one.
  
  each 
    -often used with while (list($key, $val) = each($fruit)) { }. This gives key and value of each item in an array.  
    extract
    -turns an array into individual strings where the key becomes the variable name and the value is the same as that from the array.
   
in_​array
    -checks if a string exists in a given array.
   
key_​exists
    -checks if an array key exists.
   
key   
    -gets the key name after checking the value in order to make a match.
   
list
    -makes variables based on values in an array. The names can be anything while the value is the same as the one from the array. If an array had 3 values, you would likely list 3 variables.
   
natcasesort
    -sorts an array based on a ‘natural order’ algorithm. Large case will order ahead of small case.
   
range
    -cerate a new array based on the desired range. For example, you may want items 2-8 in an array with 20 items.
   
reset
    -often used with functions like current, next, prev and end. it repositions to the first item in the array just as though you are dealing with a fresh array that has had no functions applied to it.
   
shuffle
    -shuffles the array and makes it random.
   
sizeof
    -same as count. Returns the number of items in an array. Works recursivley. So, if you have an array with 2 arrays, it returns a count for the two arrays and counts for each sub item.
   
    Various Soring Functions Below
    natsort   
    arsort
    asort
    krsort
    ksort
    rsort   
    sort
    uasort
    uksort
    usort

.htaccess Overriding

With .htaccess, you can override the main configuration you set with Apache. However, you can be very specific with your needs. For example, you can set a domain to have no override options in the root folder, yet, specify which folders you want to have the ability to override the main settings.

The code block below will help simplify this explanation.To make this as simple as possible, there is the default file from an Apache installation on an Ubuntu installation on an Ubuntu server. The file is located in the path /etc/apache2/sites/available/default.

As you can see, there is no option to override anything in the root folder. But, the blog folder will be given the option to override. If you have mod_rewrite enabled, you would see that it will work for all files loaded from the blog folder since it has ‘AllowOverride All’.

So, there you are. Only the files the blog folder will have the abilty to use the .htaccess file.

<Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        <Directory /var/www/blog>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

About mod_rewrite

When you rent a server; shared, VPS or dedicated, it lis likely that mod_rewrite is enabled by default. But, when you build your own you will likely need to enable it. At the same time, you may want to enable mod headers too.

sudo a2enmod rewrite
sudo a2enmod headers


Using .htaccess code with Apache Stanza

For the real security type, you can always keep all rules in a safe place on the server and deny any overriding with .htaccess. The code below shows code within the file called /etc/apache2/sites/available/default.

<Directory /var/www/blog-test>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all

DirectoryIndex static.php index.php index.html

#Expire Header
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
#ExpiresDefault "access plus 2 hours"

#ExpiresActive On
#ExpiresByType image/gif "access plus 1 month"
#ExpiresByType image/png "access plus 1 month"
#ExpiresByType image/jpeg "access plus 1 month"
#ExpiresByType text/css "access plus 1 month"
#ExpiresByType text/javascript "access plus 1 month"
#ExpiresByType application/x-javascript "access plus 1 month"
#ExpiresByType application/x-shockwave-flash "access plus 1 month"

</FilesMatch>

<IfModule mod_rewrite.c> 
Options +FollowSymLinks
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ blog/index\.php?title=$1 [NC]


#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^(.*)\.html$ index\.php?title=$1 [NC]
</IfModule> 

<Files ~ ".inc"> 
Order allow,deny 
Deny from all 
</Files>

<Files ~ \"\\.(inc|sql|...other_extensions...)$\">
  order allow,deny
  deny from all
</Files>

<Files 403.shtml>
order allow,deny
allow from all
</Files>
        </Directory>

Custom PHP Sessions

As a PHP programmer, you could have one of several instances why you want a folder or subfolder to have its own custom session variable path. For one, you could have more than one folder in your public_html folder that uses the same session variables and you want to make sure that only a particular folder must use session variables specified only for that folder. An example of this could be subfolders that belong to each member or an application with a demo folder.

If you let the session variables to be accessed across all folders, the results could be disastrous since any login on the site could be used to validate any visited web page.

With that said, you have multiple options for which you can make sure that sessions cannot jump from folder to folder. Since PHP 5.3, you can place a custom php.ini file into the public_html and other folders to make specific rules. By default, this limits sessions from being used from folder to folder. However, allowing custom PHP configurations is a security risk if the wrong people can make these changes.

If you want to deny any usable custom php.ini file in order to maintain security, you will arrive at the option which allows you to create custom session paths for any folder on a website. All you need to do is add a line to the loaded php.ini file that resides on the server and set the path location where you want to do this.

The exmples below show various paths for a subfolder. Note that the root folder will store the sessions in the default location. But, the subfolder has the option to store them outside the home directory, inside the home directory and outside the public_html folder, and inside a folder within the public_html folder. Since two options are commented out, the actual path where the sessions are saved in the sessions folder with the path ‘folder-custom-sessions/sessions’.

[PATH=/home/username/public_html] 
safe_mode = on  

[PATH=/home/username/public_html/folder-custom-sessions] session.save_path = /home/username/public_html/folder-custom-sessions/sessions 
;session.save_path = /mynewsessions 
;session.save_path = /home/username/mysessions

Use Curl to Post Form Data

Curl is an amazing extension that returns the source code of a desired webpage into a string. This simple tutorial will explain how you can code a simple script so that the actual website will process the form data as though you are a real visitor that submitted the form.

Let’s break down the following code. The desired url is https://example.com/login.php. Since we know the username and password, an array is created so the form can properly validate. After that, curl is initialized followed by a whack of options.

Among other things, these options options provide a referring url which make the request believe that you viewed index.php before filling out the form at login.php.

The CURLOPT_FOLLOWLOCATION is to ensure that you will be redirected to an appropriate page. Sometimes, you login and the PHP script will redirect you to a new page. Without this option, you will not be redirected and could end up with a blank page without any data.

The CURLOPT_HEADER was included so that the string adds the header details.

The CURLOPT_POST and CURLOPT_POSTFIELDS options are required to ensure that this is a post request and that it contains the adequate form fields, which in this case is the username and password. Since curl uses GET by default, it is very important to satisfy all requirements for making a POST request.

The actual string($html), is printed and contains the web page that exists after a valid login. However, if the login was invalid, you would see the page that would be returned if you sent the wrong credentials.

This example was shown with an authenticated login. However, it could be used to send data from any typical form. If you use a tool like Firebug, you can easily retrieve the post fields and create an array for the details you need to send; such as a simple contact form that requires a first name, last name, email address and phone number. On the other hand, you may only need a username, password, validate password and email address to POST to a form for which you want to submit a free membership.

 <?php

$url = 'https://example.com/login.php';
$data = array('username' => 'admin', 'password' => 'my_password');
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'https://example.com/index.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$html = curl_exec($ch);

echo $html;

If you want to see a complete list of curl options, you can find them at http://php.net/manual/en/function.curl-setopt.php.

Converting mysql to mysqli

The time has come and many functions like mysql_query are deprecated and will eventually become totally unusable as PHP evolves from version to version.

With this in mind, you have multiple options for coding or recoding your new and existing applications; especially where mySQL is concerned. For starters, you can use the mysqli extension which offers both an object oriented and procedural approach to doing this. Alternatively, you can use PDO.

If you plan to use the secure PDO or mysqli, you need to have the extension enabled in your PHP settings. It is good idea to have both enabled since you may need to use both of them with various web applications.

PDO

With PDO, you would need to rewrite a lot of code and the conversion would be quite time consuming. For new applications, you may just want to use it as your default means for writing queries.

You can see various select, insert, update and delete statements at:
http://fullstackwebstudio.com/locations/coding-blog/sqlite-vs-mysql.html
http://fullstackwebstudio.com/locations/coding-blog/connecting-to-mysql-with-pdo.html
http://fullstackwebstudio.com/locations/coding-blog/oop-login-class-with-php.html

MYSQLI

With mysqli, it is very easy to convert from functions that use mysql; such as mysql_query(), mysql_fetch_assoc(), mysql_real_escape_string(), mysql_num_rows(). The steps below will you the slight differences to make a successful conversion.

1) Do a search and replace mysql_ with mysqli_

2) Change database connection file; if necessary. The code below will work with mysqli. It is not necessary to use the function mysqli_select_db().

function db_connect() {
    
    $host = "localhost";
    $user = "user";
    $pw = "password";
    $database = "database_name";

    $db = mysqli_connect($host, $user, $pw, $database) or die("Cannot connect to mySQL.");    

    return $db;
}

$db = db_connect();

3) Do a find and search for all mysqli_query in your code. With the mysqli_query() function you need 2 parameters; the database connection and the the query. The order is very important and opposite the mysql_query() function where the query string would be the first parameter and the optional second parameter would be the database variable.

$command = "SELECT * FROM tablename";
$result2 = mysqli_query($db, $command2);

4) Do a search for mysqli_real_escape_string. This function needs 2 parameters; unlike one that is required for mysql_real_escape_string(). The first parameter is the database variable while the second is the string.

You have had some code where this function was written within a mysql query. Now, you could filter the variable with the function outside the query. Then, you simply use the variable within the mysql query.

$password = mysqli_real_escape_string($db, $_POST['password']);

5) If you have any more trouble, you should check for errors. The errors and Google normally help solve the issues. Also, keep in mind that other lesser used functions will need the database variable parameter in order to work properly.  For example, mysql_affected_rows() will need to be mysqli_affected_rows($db).

From .htaccess To Nginx

The purpose of this brief tutorial is to explain how to change an entire PHP application from an Apache server to be used on an Nginx server. The main modifications will alter PHP settings and adding old rules from your .htaccess file. Luckily, both changes only require altering two files; php.ini and /etc/nginx/sites-available/default.

PHP Changes

Open up the loaded php.ini file and change or modify the line to read the following text. The loaded php.ini file could be in a location such as /etc/php5/apache2/php.ini. There is a good change you will see a commented line that looks like ;cgi.fix_pathinfo = 1.

cgi.fix_pathinfo = 0

After that, you need to open the file /etc/nginx/sites-available/default as root. One you have done that, you can add and save the following code block. Note that this code is likely commented out. The code below shows the updated version.

location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #       # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        #
        #       # With php5-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php5-fpm:
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }


.htaccess Changes

The main difference will be transferring the conditions and rules in the .htaccess file to make it work with Nginx. For starters, the bad news is that your .htaccess settings will not work with Nginx. The good news is that you can modify Nginx server config files very quickly and there are online tools that help convert the rules.

To make the new changes, you open the same file that you used to change the PHp settings. Once again, the file is /etc/nginx/sites-available/default. This time, you look for the code block that contains location / { }. 

Finally, you can add the new rules. Two websites that can be a great help are http://www.anilcetin.com/convert-apache-htaccess-to-nginx/ and http://wiki.nginx.org/HttpRewriteModule#rewrite.

The code below shows a the conversion of some mod_rewrite rules from .htaccess to the Nginx methodology.


.htaccess Version

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)--(.*)\.html$ blog/index\.php?id=$1&title=$2 [NC]


Nginx Version

if (!-f $request_filename){
	set $rule_0 1$rule_0;
}
if (!-d $request_filename){
	set $rule_0 2$rule_0;
}
if ($rule_0 = "21"){
	rewrite ^/(.*)--(.*).html$ /blog/index.php?id=$1&title=$2;
}

simplexml_load_file() , simplexml_load_string() and SimpleXMLElement()

Both simplexml_load_file(), simplexml_load_string() and SimpleXMLElement() will allow you to add nodes to an XML file.

One of the main difference between the three are that you need to use the new keyword to instantiate a SimpleXMLElement() object. On the other hand, the simplexml_load_file() and simplexml_load_string() convert the xml to a SimpleXMLElement object.

Another difference between the three is that simplexml_load_file() loads a file while the other two load a string.

The examples below show how each of them can be used to append elements. One example will add the child node and display it in the browser while the other will add the text to the desired xml file. A node will only be added to a file once, regardless of how many times you hit the page.

simplexml_load_file()

Example #1

The below will load an xml file, append another member to the root node and print it in the browser.

<?php

$filename = 'filename.xml';

$doc = simplexml_load_file($filename); // load a file

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

header('Content-Type: text/xml');
echo $doc->asXML();

Example #2

The next example will append a new member to filename.xml.

$filename = 'filename.xml';

$doc = simplexml_load_file($filename); // load a file

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

echo $doc->asXML('test.xml');

simplexml_load_string()

Example #1

This example is just like above, except that the source is a string rather than a file. The PHP functions file_get_contents() and curl() can output a file to a string.

<?php

$filename = 'filename.xml';

$filename = file_get_contents($filename);
$doc = simplexml_load_string($filename); // load a string

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

header('Content-Type: text/xml');
echo $doc->asXML();

Example #2

This little snippet get the contents of the filename.xml file and return a string. After that, a new member is added to it.

$filename = 'filename.xml';

$filename = file_get_contents($filename);
$doc = simplexml_load_string($filename); // load a string

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

echo $doc->asXML('test.xml');

SimpleXMLElement

Example #1

This case will load a string and output the existing and new elements in the browser.

$filename = 'filename.xml';

/* PAIR */
$filename = file_get_contents($filename); // make the file contents a string
$doc = new SimpleXMLElement($filename); // needs a string as parameter

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

header('Content-Type: text/xml');
echo $doc->asXML();

Example #2

This example will load a file and write the new member to the xml file.

$filename = 'filename.xml';

/* PAIR */
$filename = file_get_contents($filename); // make the file contents a string
$doc = new SimpleXMLElement($filename); // needs a string as parameter

$adding = $doc->addChild('member'); // main multiple elements with nested info
$adding->addChild('id', '1234');
$adding->addChild('name', 'Name Here');
$adding->addChild('phone', 'Phone Here');
$adding->addChild('email', 'Email Here');

echo $doc->asXML('test.xml');

PHP Magic Method __toString

The __toString magic method contains the usual double underscore in its front. It does does as its name implies since it strips object characteristics. The next PHP OOP examples should help you understand the details.

Integer Parameter

With the first code block, an integer is passed into the class via the constructor. As you can see, it is an integer before, during and after it leaves the class. But, it is no longer an object and the tests below indicate that.

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

    public function __toString()
    {
        return $this->my_string;
    }
}

$my_array = array('test');
$class = new TestClass(58);
echo $class->my_string;
echo "<br/><br/>";
if (is_object($class->my_string)){
echo "Yes";
}
echo "<br/><br/>";
if ($class->my_string instanceof TestClass) {
   echo "Instance";
}
echo "<br/><br/>";
var_dump($class->my_string);
echo "<br/><br/>";
var_dump((string)$class->my_string);

?>


Browser Output

integer
58
58

int(58)

string(2) “58”

String Parameter

With this example, you can see that if we use the $class->my_string it is a string without any record of its class. But, if you analyze the variable $class, you wil see that it still maintains it association to the class; even though it is a string called my_string with a value of “test”.

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

    public function __toString()
    {
        return $this->my_string;
    }
}

$class = new TestClass('test');
echo $class;
echo "<br/><br/>";
var_dump($class);
echo "<br/><br/>";
echo var_dump($class->my_string);
echo "<br/><br/>";

if (is_object($class)){
echo "Yes";
}
echo "<br/><br/>";
if ($class instanceof TestClass) {
   echo "Instance";
}

echo "<br/><br/>";
var_dump((string)$class);
$success = settype($class, 'string');
echo (string)$class;
echo "<br/><br/>";
if (!is_object($class)){
echo "No";
}
echo "<br/><br/>";
if (!$class instanceof TestClass) {
   echo "No longer an instance";
}
?>


Browser Output

string
test
test

object(TestClass)#1 (1) { [“my_string”]=> string(4) “test” }

string(4) “test”

Yes

Instance

string(4) “test” test

No

No longer an instance

PHP Magic Methods __SET and __GET

With PHP OOP, you can manually set and get properties when you work with your object, or, you can use the __SET and __GET magic methods which are invoked automatically after you instantiate a class.

If you want guaranteed results and plan to set property names outside the class, making your own functions will allow you to manage public, protected and private properties in this manner.

On the other hand, if you want to print or use properties from a class that are protected or private, you cannot override them with __get and __set magic methods.

The following examples should make this a little more clear.


Manual Get and Set Methods

<?php

class Manual {
public $a = "A";
protected $b = array("a" => "A", "b" => "B", "c" => "C");
 
public function set_var($var){
$this->b = $var;
}

public function get_var(){
return $this->b;
}

}

$m = new Manual();
$var = array("x" => "X", "y" => "Y", "z" => "Z");
//$var = "help";
$m->set_var($var);
echo $m->get_var();
echo "<br/>";
print_r($m->get_var());

?>

Now, I will go over this. The variable was set and returned. Even though the variable $b was protected, the property can be overwritten. However, the same cannot be said for the set_var() and get_var() methods since changing any one of them them to protected or private would not work, thus no value would be returned from the get_var() method.

If you uncomment the line with $var = help, you can change the value from an array to a string. As you can see with this method, $protected $b was overwritten.

Now, let’s move on and try this with __get and __set magic methods.

Magic __get and __set Methods

<?php

class magicMethod {
public $one = "A";
protected $two = array("a" => "A", "two" => "B", "c" => "C");

public $mycount = 0;

public function __get($v) {
$this->mycount = $this->mycount +1;
echo "$v";
return $this->two[$v]; 
}

public function __set($variable, $value){

}
}

$test = new magicMethod();
//$test->one = "TEST"; //can change
//$test->two = "foo"; //cannot change because not public scope inside class
echo $test->one.",".$test->two; 

?>

Here is how this example works. The __set magic method accepts 2 parameters. Meanwhile, the __get magic method accepts and passes on a single parameter. As you can see, the magic methods invoked and printed the $v as two. After that, it printed the public property value for $one followed by the returned value of $this->two[$v].

Now, you may have originally thought that the public value of $one would be followed by the followed by the code from the magic method which output two as as $v and $this->two[$v] as the second value of the protected $two array.

But, the magic methods ran first and output the value of $v which was two. After that, $test->one was printed since it was next in line. After that, the returned value was printed. Since $one was public, it bypassed the __set and __get methods.

If you uncomment the $test->one = “TEST” and $test->two lines, you will see that you can alter the public property but have no luck changing the protected property.

PHP Object Interfaces Keyword

Using object interfaces with PHP OOP is useful when you want to make sure a class must contain specific public functions. In other words, if you want to use an interface for a class, the class must use the method from the interface, otherwise an error will occur.

Another key point to remember with interfaces is that the class and interface code blocks must use public methods with the same amount of parameters. Although the parameters must be the same, the actual names in the interface code block is not that important, asides from good type hinting.

To use interfaces, you make a code block with the interface keyword. This is much like declaring a class, but with a different name. To use the interface conditions in a class, you add the implements keyword followed by the name. The example below should make this clear.

Example #1

<?php

interface example
{
    public function set_name($var1,$var2);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();


Browser Output

Peter Paul


Example #2

Here is an example of code that is slightly modified from above. The only difference is the reduction of one parameter from the interface code block. Thus, ‘public function set_name($var1,$var2)’ was changed to ‘public function set_name($var1)’. The code below would trigger an error because the parameters in the class and interface are different.

interface example
{
    public function set_name($var1);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();

Namespaces With PHP 5.3+

PHP Namespaces allow you to make reference points at the top of your file(s) so that your specific files will use the code from the namespaces. If you have matching namespaces in two files, your file will pick up the code from that with the matching namespace.

In addition to using namespaces, you can import them with the use operator.

The code examples below will show two examples. One will be a set of files with the same namespaces while the other set will have a file that imports the namespace from another file. Namespaces are case insensitive; thus my\test1 and my\TEST1 are both okay to use.

Example #1 Matching Namespaces

With this example, your main file, and the file with two constants, a function and a class both have the same namespace. Coding with matching namespaces is just like coding any other two files; except that the top line of the two files use the namespace.
 
Included File With Functions and Class

<?php
namespace my\TEST1;

$variable = 3;
const CONSTANT1 = 'First Constant';
define('CONSTANT2', 'Second Constant');

function my_function()
{
    global $variable;
    return CONSTANT1 . " - " . CONSTANT2 . " - " . $variable;
}

class TestClass
{
    static $test;

    public function set($val)
    {
        $this->test = $val;
    }

    public function myclass_method()
    {
        return $this->test;
    }
}

?>


Main File Executed In Browser

<?php
namespace my\TEST1;

require('file1.php');

echo $variable . "\n";
echo my_function() . "\n";
$test = new TestClass();
$test->set('James');
echo $test->myclass_method() . "\n";
?>


Example #2 Importing a Namespace

When you import a namespace, one file will have the namespace while the other will import it using the use operator. Unlike the previous example, you see that you need to add the namespace you imported when you call functions or instantiate objects.


Included File With Functions and Class

<?php
namespace my\TEST2;

$variable = 3;
const CONSTANT1 = 'First Constant';
define('CONSTANT2', 'Second Constant');

function my_function()
{
    global $variable;
    return CONSTANT1 . " - " . CONSTANT2 . " - " . $variable;
}

class TestClass
{
    static $test;

    public function set($val)
    {
        $this->test = $val;
    }

    public function myclass_method()
    {
        return $this->test;
    }
}

?>


Main File Executed In Browser

<?php
use my\TEST2;

require('file2.php');

echo $variable . "\n";
echo my\test2\my_function() . "\n";
$test = new my\TEST2\TestClass();
$test->set('James');
echo $test->myclass_method() . "\n";
?>


Main File Executed In Browser (Shorthand Version)

Unlike the example above, the code makes a shorthand version of the namespace with ‘use my\TEST2 as S’. Essentially, you just need to use ‘S\’ instead of my\TEST2.

<?php
use my\TEST2 as S;

require('file2.php');

echo $variable . "\n";
echo S\my_function() . "\n";
$test = new S\TestClass();
$test->set('James');
echo $test->myclass_method() . "\n";
?>


Browser Output

3
First Constant – Second Constant – 3
James

PHP array_diff() Function

Simply put, array_diff() compares two arrays. The first parameter is the array the you will compare from. This means that you will find what is different in it than the second array parameter.

If it does not have any unique values that differ from array #2, the result is that there are no differences; regardless of how many items that the second array has that the first array does not have.

That was a mouthful, I hope it makes sense to you.

The easiest way to show this is to provide some examples which are shown below. Both examples consist of two arrays called $first and $second. Then, a $diff variable becomes an array that holds the difference.

Finally, the print_r() function will output the values that are different. For simplicity of explanation, there is only one value in the second array that does not exist in the first array. This makes it easy for you to understand the example.

Example #1

The example below shows array_diff() with the parameters swapped. As you can see, the first print_r() statement is empty but the second print_r() statement has the value ‘grape’.

 <?php 
$first = array('apple','orange','banana'); 
$second = array('apple', 'orange','banana','grape');  
$diff = array_diff($first,$second);  print_r($diff);  
echo "<br/>";  
$diff = array_diff($second,$first);  print_r($diff);

Browser Output

Array ( )
Array ( [1] => grape )

Example #2

This example changes the keys up. As you can see, the array_diff() function only compares values. The keys can be indexed numerically or associative like ‘second’ =>.

The code below shows the same arrays with different keys. As you can see, the results are the same.

 <?php 
$first = array(1 => 'apple', 2 => 'orange','banana'); 
$second = array('first' => 'apple', 'second' => 'orange','banana','grape');  
$diff = array_diff($first,$second);  
print_r($diff);  
echo "<br/>";  
$diff = array_diff($second,$first);  
print_r($diff);

Browser Output

Array ( )
Array ( [1] => grape )

See http://fullstackwebstudio.com/locations/coding-blog/array-diff-php.html for details on how you could use this with data from mySQL queries.

PHP Increment Primer

With PHP, there are many ways to increase or decrease an integer with increments. Although the concept is rather simple, the truth is that not all incrementing behaves the same way. At times, a value can be added instantly, while at other times it only takes place the next time an integer is used. Often, increments are used in loops to add to an existing value each time the loop iterates.

For example, the simple statement ‘echo ++$number’ automatically prints the new number of $number. But, ‘echo $number++’ will not print the new number. In the second case, it will only print the updated number the next time the $number variable is used. A simple way to remember this is ‘increments before update right away’ while ‘increments after update after.

Below are a simple couple of examples which show the updates before and after.

If you find this forgettful, you may want to always create the increment without printing its value. This way, you will always get the updated value when you want to use the variable.

Example

 <?php  
$a = 1; 
echo ++$a ." - " . $a;  
echo "</br/>";  
$b = 2; 
echo --$b ." - " . $b;  
echo "<br/>";  
$a = 1; 
echo $a++ ." - " . $a;  
echo "</br/><br/>";  
$b = 2; 
echo $b-- ." - " . $b; ?>

Browser Output

Obviously, the lines which match are updated right away while those that do not only happen the next time the variable is used.

2 – 2
1 – 1

1 – 2
2 – 1


Other Ways To Increment

Asides from the methods shown above, you can create a variable and just add or decrease a desired number to its existing value. The example below show a simple loop that adds 1 to the variable each time it loops and a second loop that adds 2. The first loop runs 6 times; once each for 0,1,2,3,4,5.

The second loop only loops 3 times because after the first loop $i =2, after the second loop $i = 4 and after the third loop $i = 6. Both loops have a final value of 6.

 for($i = 0; $i <=5; $i++){  
}  
echo $i; //outputs 6    
for($i = 0; $i <=5; $i++){ $i = $i + 1; }  
echo $i; //outputs 6

func_get_args() Function

With PHP, you can pass parameters into a function or you can get them inside a function using the func_get_args() function. Let me take you through the example. There are two functions.

One function will pass in the parameters and create an indexed array with those variables. After that, the $variables array is returned and shown with the print_r() function.

Since the $output variable was made equal to the function, the returned array takes on the name of the variable. Thus, that is why print_r($output) is used to print the array rather than print_r($variables).

The second function will pass in parameters, but, the function will not pass them along since there are none show between the get_parameters(). Remember, the first function passed them inside the function with pass_parameters($a,$b,$c). Hopefully, this difference is very clear for you.

Even though they are not passed into the second function, they can be accessed using the built in PHP function called func_get_args(). With func_get_args(), you will have an array of the parameters.

From calling the function with get_parameters(‘one’,’two’,’three’), the array will be those three strings. Thus, the array $variables in the second function contains those three values.

Like the first function, the array is returned and takes on the name $output. Just like the first example, your array will yield the same results with the print_r() function.

Example

<?php 

function pass_parameters($a,$b,$c) {

$variables = array($a,$b,$c);

return $variables;

}

function get_parameters() {

$variables = func_get_args();

return $variables;

}


$output = pass_parameters('one','two','three');

print_r($output);

echo "<br/>";


$output = get_parameters('one','two','three');

print_r($output);


Browser Output

When you load this page in your browser, you will see the results of each identical array. Now, you have two methods in your toolkit for accessing parameters passed into a function.

Array ( [0] => one [1] => two [2] => three )
Array ( [0] => one [1] => two [2] => three )

PHPINFO and get_loaded_extensions

The functions phpinfo() and get_loaded_extensions() will both let you know what PHP extensions are installed on your system. The code below shows how to see your extensions.

 echo phpinfo(); 

The code below shows how to print an array of extensions with the get_loaded_extensions() function.

 print_r(get_loaded_extensions()); 

sha1() and md5() Functions

With PHP, sha1() and md5() password functions are used in many web applications where passwords are implemented; such as scripts with login and logout functionality. In the modern era, sha1 is often used while md5 can be found in older and some modern applications.

By default, the sha1 function outputs a 40 character string while the md5 string is 32 characters. If you use the functions with the ‘true’ parameter, its cuts down the characters in half; thus sha1 is 40 characters and md5 is 16 characters. With the longer character string, it is a hexadecimal number while the shorter string is a binary number. 

 echo sha1('string_name'); //40 characters echo sha1('string_name, true); //20 characters  
 echo md5('string_name'); //32 characters echo md5('string_name', true); //16 characters 

PHP Integers

Theory About Character Values

Here a little theory about integers with PHP. Although, most applications use regular numbers like 1,2 and 3, you can use other coding means to represent numbers. Three methods shown below are hexadecimal, binary and octal notation. .

Hexadecimal

The hexadecimal format used the characters are (“0”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “A”, “B”, “C”, “D”, “E”, “F”). The f is actually 15. Some sample hexadecimals are 0x0, 0x1 and 0x1B. The actual integer values of each of these hexadecimals are 0, 1 and 27. The 27 comes from the 1 which is 16 and b which is 11. To make this easy tp remember, you can remember to carry the number when it hits 16(which is F).

Binary Values

With binary numbers, all numbers are based on the exponential value of 2. Thus, a value like 11100 is (2 to the power of 4) + (2 to the power of 3) + (2 to the power of 2) + (0*(2 to the power of 1)) + (0(2 to the power of 0)) = 28.


Octal Notation

When you hear octal, you are probably thinking the number 8. Octal notation is based on a 1-8 system and has a zero as the first decimal. To make this more clear, a number like 07 is seven, while 017 is 15. In the latter case, you have one complete 8 plus 7 from the first column. By comparison, the number 0117 if 7 + 8(1) + 8(8) =  79.

Sample

The code below shows a binary number, hexadecimal number, octal number and a regular integer. Then, all the values are added up. As you can see, PHP will out an integer. To use a binary number, you need to add 0b in front of the binary value. The ob has been available since PHP 5.4.

 <?php 
$a = 0b00000110; // Binary Outputs 6 
$b = 0x1F; // Hexadecimal Outputs 31  
$c = 2; 
$d = 011; // Octal Outputs 9 
echo "a=$a b=$b c=$c d=$d<br/>";  
echo $a + $b + $c +$d; // Outputs 48 
?>

Browser Output

The output below is what you will see in your browser.

a=6 b=31 c=2 d=9
48

Remove www From URL with .htaccess

For whatever reason, the time could arrive when you would like to remove www from urls from your root website folder or a subdirectory. If you use the Apache server, mod_rewrite makes it easy for you to do this procedure.

The methods below show one example you could use in your root folder and another you could use in any subfolder which has its own .htaccess file. The examples will have the blocks for both http and https urls.

The first block of code below will be added to any .htaccess file where you want to make the custom rewrite conditions and rules.

The code between the <IfModule mod_rewrite.c> and </IfModule> tags is interpreted if the mod_rewrite module is enabled on the server. Usually, it is always enabled. Although the other blocks of code are outside of the mod_rewrite folder, they will be interpreted.

<IfModule mod_rewrite.c>  
Options +FollowSymLinks 
RewriteBase / 
Options +FollowSymLinks 
</IfModule>

Root Folder

HTTP

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC] 
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

HTTPS

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC] 
RewriteCond %{HTTPS} =on 
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

Subfolder

HTTP

 # remove www 
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] 
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

HTTPS

 # remove 
www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] 
RewriteCond %{HTTPS} =on 
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

For more information about mod_rewrite variables, you can see them at http://www.askapache.com/htaccess/mod_rewrite-variables-cheatsheet.html

More mod_rewrite Theory

Although you can move on and just add the code as it was described above, I will add a little theory into the mix.

The actual file mod_rewrite.c is C source code. You could find this file with command find / -name ‘mod_rewrite.c’ 2>/dev/null. If you wanted to check it out, you can view it with the cat command or load it into an editor. At this point, you may want to have a tuner on the language C, so that you will know more about pointers, global scope, and libraries. It is very different and more head spinning than a scripting language like PHP.


MYSQL NOT IN and NOT EXISTS Comparison Operators

With mySQL, the NOT IN() and NOT EXISTS operators are do the opposite of their counterparts IN() EXISTS() operators. When managing databases, there may come a time when you need to build queries that will check the data in one database table and see if there is a matching value in another column of a different database table.

One example that comes to mind is to find the people that made a purchase for an item. This data could have ended up in a table like purchases_before_paypal. Then, upon purchase, you could record the user ids of the people who actually made a payment with a Paypal account.

So, if you wanted to do a check to see who did not actually pay you could use the NOT IN() or NOT EXISTS() operators to see those who made it the end of the cart without having made the Paypal transaction.

Another example is to have a table that is used to collect data from registered users and another table to check logins. This way, you can calculate who has registered, but has not logged in.

MYSQL NOT IN()

The statement below will grab rows where the id from the tablename1 table where the id from the tablename1 column is not in the userid column from the table called tablename2 table.

 SELECT id FROM tablename1 WHERE tablename1.id NOT IN (SELECT userid FROM tablename2); 

MYSQL NOT EXISTS()

The statement below will grab rows where the id from the tablename1 table where the id from the tablename1 column does not exist not in the userid column from the table called tablename2 table.

 SELECT DISTINCT id FROM tablename1 WHERE NOT EXISTS (SELECT userid FROM tablename2 WHERE tablename2.userid = tablename1.id); 

PHP Trim and MYSQL Trim Functions

Often, when working with PHP / mySQL, you will use data that was sent from forms and data from the database. While the data is often correct, you could end up with errors and surprise output if there happened to be any whitespace before or after you string.

With a mySQL database, it can be hard to detect if a string actually has whitespace attached to it. Luckily, PHP and mySQL have functions that can be used to trim whitespace.

If you plan to insert and retrieve data from a database, using mySQL’s TRIM() function is the way to go.

Meanwhile, any of the PHP functions, trim(), ltrim and rtrim() can be used to remove whitespace from strings or retrieved data. Personally, I like to use mySQL to do the work if that is where the data is coming or going from.


MYSQL Style

 INSERT INTO tablename (id, input, date) VALUES (NULL, TRIM($input_string), now());  

SELECT TRIM(input) FROM tablename where id > 1  

UPDATE tablename set input = TRIM($input_string) where id = '$id'

In addition to trimming whitespace, you can command mySQL to trim text, commas and other unwanted data from the left, right or both ends of a string. The example below shows how to remove a trailing, leading and trailing and leading commas from a database field.

TRIM(TRAILING ',' FROM columnname) 
TRIM(LEADING ',' FROM columnname) 
TRIM(BOTH ',' FROM columnname)

More examples of using the mySQL trim function can be found at http://fullstackwebstudio.com/locations/coding-blog/MYSQL-TRIM-Function.html. In addition to the TRIM() function, the replace() function with mySQL can be used to change anything you want from a string; including removing whitespace and replacing it with nothing. More details about the mysql replace() function can be found at http://fullstackwebstudio.com/locations/coding-blog/mysql-rerplace-function.html.

Yet, there is even another method to deal with trailing whitespace in a VARCHAR column. You can remove it through a two step process:
1) alter column type to char
2) alter column type back to varchar.

PHP Style

$trimmed = trim($string);  
$trimmed2 = htmlspecialchars(trim($string));  
$trimmed_left = ltrim($string);  
$trimmed_right = rtrim($string);

MYSQL Database Backup

The purpose of this tutorial is to create a backup of a mySQL database. The tutorial will two methods for which this can be accomplished; one using a GUI tool called Cpanel and the other using the Linux command line. Although both methods have pros and cons, using the command line and getting to know it well will allow you to easily work on any Linux server and accomplish your goals very quickly.

Database Backup With Cpanel

To backup a database,
1) Select ‘Backup Wizard’.

MYSQL Database Backup Wizard

2) Select Backup.

Cpanel MYSQL Database backup

3) Select ‘mySQL Databases’.
4) Select a Database.
Note: You can click ‘Databases’ to order the databases in alphabetical order. This can become handy as you have 20-100+ databases.
5) Click OK

Download MYSQL Database

Non GUI Backup

Although using a GUI makes it nice and easy to backup databases. The code below can be used to backup a mySQL database and save it in a desired folder. After that, the public-html folder is made into a tar file which has all of the files and database. This type of backup can take place as a weekly cron so that you have a n updated backup of the files and database.

 root# mysqldump -u root -p mydatabase > /home/username/public_html/backup.sql 
Enter Password: 
root# tar -cvf mybackup.tar /home/username/public_html

One more method to backup mySQL databases is to copy them from their folder.

 root# cp -R /var/lib/mysql/* /home/username/backups/

MYSQL Remove duplicate Rows

Removing duplicate rows with mySQL could be something you need to do for various reasons. One reason could be that you want to clean up your database and have unique entries. The script below is written in PHP / mySQL and can be used to remove those unwanted entries.

First, I will show the code. For those with decent PHP / mySQL skills you can just edit the mySQL statements so that they find, count and delete the duplicates from your desired table. For those who need to understand what is going on, you can see the explanation about removing the duplicate rows with mySQL.

<?php 
 include('connect.inc');
 $db = public_db_connect();
if($_POST['submit']) {
 
$command = "SELECT id, firstname, lastname, count(*) as cnt from table_sort group by firstname, lastname having count(*)>'1' order by cnt DESC ";
 
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$cnt = $row['cnt'];
 
$firstname_array[] = $firstname;
$lastname_array[] = $lastname;
$mix[] = $firstname.",".$lastname.",".$cnt;
} 

$mix = array_unique($mix);
 
foreach ($mix as $item) {
$both = explode(",",$item);
$myfirst = $both[0];
$mylast = $both[1];
$number = $both[2];
$delete_amount = $number - 1;
 
$commandb = "DELETE FROM table_sort WHERE firstname='$myfirst' AND lastname ='$mylast' LIMIT $delete_amount ";
$resultb = mysqli_query($db, $commandb);
if($resultb){
echo "$myfirst - $mylast deleted Successfully!<br/>";
}
 
} 
}
?>
<div style="display:block; float:left; width:45%;">
 
<div style="float:left; width: 150px;">Check Names<br/><br/></div>
</div><div style="clear:both;"></div>
<div><form action="<?php echo $_SERVER['PHP_SELF'].'?'. $_SERVER['QUERY_STRING'] ; ?>" method="post" style="display:visible;">
<input name="submit" type="submit" value="Delete All Duplicates"></form></div>
</div>


Code Explanation

The file ‘connect.inc’ is included. It contains a function to connect to the database and return the $db variable which will be used with the mySQL queries. Then, there is a condition that takes after a form is submitted. When the form is submitted, it simply runs the code to remove the duplicate mySQL rows.

The first query gathers the rows which have a duplicate first and lastname. So, the id, firstname, lastname and count of rows is gathered in the query. In simpler terms, all rows of duplicate data are retrieved.

The mix[] array will be the duplicates. The mix array is a new comma separated string which has every duplicate row. It contains the firstname, lastname and amount of duplicates. So, if there are two rows with John Smith, the $row[‘cnt’] would be the same for each of them. In fact, the entire comma separated string would be the same.

After the mix array is built from the while loop, a unique mix array is made to remove any duplicates from the array. Then, a foreach loop is run and iterates over each and every value from theb mix array. The explode() function is used to create another array from the comma separated value that was stored in the mix array. This allows you to have the firstname, lastname and count of duplicates. The firstname takes on the string called $myfirst while the lastname would be $mylast and the amount of duplicates would be $number.

Now, the delete query removes all the duplicate mySQL rows except one since $delete_amount is equal to the number of duplicate rows minus 1. Thus, if there are 3 duplicate rows, only 2 will be removed.

The HTML at the bottom of the code block starting with <div style=”display:block is the HTML code that shows a form so that the duplicates can be removed.

After Removing Duplicates

Once you remove the duplicates, you may want to make a custom index so that the table will not insert any entries with duplicate firstnames and lastnames. The code below shows how to do this with a simple mySQL query.

alter table table_sort add unique index(firstname, lastname);

Using Varnish With WordPress

So, you love the speed you get with Varnish, but, have suddenly noticed that you cannot login and make any changes. Although you could manage the site with phpMyAdmin, you more than likely want to login to the backend and make changes; like the high majority of WordPress users.

Well, with a little adjustment to you default.vcl file, you can easily keep those web pages in the cache while your wp-login and wp-admin pages will not be cached. If you do not make changes to your default.vcl file, you cannot login.

When you open your default.vcl file with an editor like Vim or Nano, you will add a small statement to the sub vcl_recv and sub vcl_fetch methods. The vcl_recv method takes the request once a web surfer has viewed a page, and decides what to do with that request. Of course, it depends whether or not it finds it in the cache.

If varnish finds it, it hits the cache and serves the file. If not, Apache takes over and serves the request. Once the file is retrieved, the request runs through vcl_fetch. If the file came from the cache, it is served and not cached again. If the file was a miss and delivered by Apache, it is cached and delivered.

The following examples show how exclude the wp-login and wp-admin pages from being cached.


sub vcl_rec

Here is a quick briefing about the following code. If the domain name is example.com or www.example.com and the wp-login or wp-admin pages are served, use the specific backend ip for that account. In this case, we use default2, which is a dedicated ip address.

Extra Note:
If you wanted to cache pages, you would have unset req.http.cookie; on a line above set req.backend = default2; Using unset removes cookies so Varnish can cache the object. If a page has cookies and unset is not in place, it would not cache.

 elsif(req.http.host ~ "^(www\.)?example\.com" && req.url ~ "/wp-(login|admin)"){ set req.backend = default2; } 


sub vcl_fetch

Hers is a quick synopsis about vcl_fetch. There is no time defined to cache an object. Therefore, Varnish will not cache the wp-login or wp-admin pages.

Extra Note:
If you did want to cache these pages, you would need to use a line between {} that says something like set beresp.ttl = 86400s;
This line tells Varnish to cache either of those pages for 86400 seconds, which is 1 day. After a day, the page would be removed from the cache. 

 elsif(req.http.host ~ "^(www\.)?example\.com" && req.url ~ "/wp-(login|admin)"){ } 


Conclusion:

Now that you know how to use Varnish with WordPress, you can easily exclude the backend from caching while maintaining the cache on the frontend. Once you have Varnish up and running, you may want to configure it to cache everything, and make exclusions as you need them. For example, you will want to make conditions for all or some backends.

OOP Login Class With PHP and PDO

This OOP login class has a parent class called login and two child classes called Posted and Verified. The ‘Posted’ class checks and validates posted data while the ‘Validated’ class checks for a valid session session value. The classes exist in one file while the main file which appears in the browser instantiates objects based on conditions.

The codes are shown in their entirety. You can set up the databases, copy the code and should be good to go as long as php on your server can use PDO data objects.

include("class-login-PDO-form2.php");
session_start();
$_SESSION['id'] = $_SESSION['id'];
$_SESSION['login'] = $_SESSION['login'];
$_SESSION['timestamp'] = $_SESSION['timestamp'];

$username = array();
$password = array();
$myarray = array();
$myuser = array();
$mytime = array();
$my_check = array();

if ($_POST['username'] && $_POST['password']) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $my_posted = new Posted($username, $password);

} else {
##VERIFY SESSION

    $mytime = $_SESSION['timestamp'];
    $myuser = $_SESSION['id'];

    $my_posted = new Verified($myuser, $mytime);

}

echo "Is there an active session username: " . $_SESSION['login'];
echo "<br/>";
print_r($my_array);
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Username:<br/>
    <input type="text" name="username" value=""/><br/>
    Password:<br/>
    <input type="password" name="password" value=""/><br/>
    <input type="submit" name="submit"/>
</form>


Example #1 Login, Posted and Validated Classes

class Login
{
    private $host = "localhost";
    private $user = "username";
    private $pw = "password";
    private $database = "databasename";

    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}

class Posted extends Login
{

    private $username;
    private $password;

    function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;

        $login2 = new Login();
        $db = $login2->db_connect();

        $command = $db->prepare("SELECT * FROM logins_test WHERE login =:login AND password = password(:password)");
        $command->bindParam(':login', $this->username);
        $command->bindParam(':password', $this->password);
        $command->execute();
        $result = $command->fetchAll();

        foreach ($result as $row) {
            $my_array[] = $row;
        }

        if (!empty($my_array)) {
            $_SESSION['id'] = $my_array[0]['id'];
            $_SESSION['login'] = $my_array[0]['login'];
            $_SESSION['timestamp'] = time();
            echo $_SESSION['id'] . " - " . $_SESSION['login'] . " - " . $_SESSION['timestamp'];
            echo "<br/>Success<br/>";

            $mytime = $_SESSION['timestamp'];
            $myuser = $_SESSION['id'];
            $command = "INSERT INTO logins_validate VALUES (NULL,:user_id, :time_current)";
            $command1 = $db->prepare($command);
            $command1->bindParam(':user_id', $myuser);
            $command1->bindParam(':time_current', $mytime);
            $command1->execute();

        } else {
            echo "Wrong username or password!";
        }

    }

}

class Verified extends Login
{

    private $mytime;
    private $myuser;

    function __construct($mytime, $myuser)
    {
        $this->mytime = $mytime;
        $this->myuser = $myuser;

        $login3 = new Login();
        $db = $login3->db_connect();

        $command = $db->prepare("SELECT * FROM logins_validate WHERE user_id =:login AND time_check = :mytime");
        $command->bindParam(':login', $this->myuser);
        $command->bindParam(':mytime', $this->mytime);
        $command->execute();
        $result = $command->fetchAll();

        foreach ($result as $row) {
            $my_check[] = $row;
        }

        if (!empty($my_check)) {
            echo "<br/>Session is validated!";
            ## ADD CUSTOM CODE HERE
        } else {
            echo "<br/>Session is not validated!";
            ## ADD CUSTOM CODE HERE
        }
    }

}


Example #2 Login, Posted and Validated Classes

The example below is very similar to the example above, except that it has a stronger object oriented approach. Go over both code blocks to see understand the varying syntax. After all, OOP if fun.

class Login
{
    private $host = "localhost";
    private $user = "username";
    private $pw = "password";
    private $database = "database_name";

    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }
}

class Posted extends Login
{

    private $username;
    private $password;
    private $result;
    private $my_array;

    function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;

        $this->login2 = new Login();
        $this->db = $this->login2->db_connect();

        $command = $this->db->prepare("SELECT * FROM logins_test WHERE login =:login AND password = password(:password)");
        $command->bindParam(':login', $this->username);
        $command->bindParam(':password', $this->password);
        $command->execute();
        $result = $command->fetchAll();
        $this->result = $result;

        //var_dump($result);
        $my_array = array();
        foreach ($this->result as $row) {

            $my_array[] = $row;
        }

        $this->my_array = $my_array;
        if (!empty($this->my_array)) {
            $_SESSION['id'] = $this->my_array[0]['id'];
            $_SESSION['login'] = $this->my_array[0]['login'];
            $_SESSION['timestamp'] = time();
            echo $_SESSION['id'] . " - " . $_SESSION['login'] . " - " . $_SESSION['timestamp'];
            echo "<br/>Success<br/>";

            $this->mytime = $_SESSION['timestamp'];
            $this->myuser = $_SESSION['id'];
            $command = "INSERT INTO logins_validate VALUES (NULL,:user_id, :time_current)";
            $command1 = $this->db->prepare($command);
            $command1->bindParam(':user_id', $this->myuser);
            $command1->bindParam(':time_current', $this->mytime);
            $command1->execute();

        } else {
            echo "Wrong username or password!";
        }

    }

}

class Verified extends Login
{

    protected $mytime;
    protected $myuser;
    private $result;
    private $my_check;

    function __construct($myuser, $mytime)
    {
        $this->myuser = $myuser;
        $this->mytime = $mytime;

        //echo $this->mytime . "<br/>";
        //echo $this->myuser . "<br/>";

        $this->login3 = new Login();
        $this->db = $this->login3->db_connect();

        $command = $this->db->prepare("SELECT * FROM logins_validate WHERE user_id =:login AND time_check = :mytime");
        $command->bindParam(':login', $this->myuser);
        $command->bindParam(':mytime', $this->mytime);
        $command->execute();
        $result = $command->fetchAll();

        $this->result = $result;

        $my_check = array();
        foreach ($result as $row) {
           $my_check[] = $row;
        }

        $this->my_check = $my_check;

        if (!empty($this->my_check)) {
            echo "<br/>Session is validated!";
            ## ADD CUSTOM CODE HERE
        } else {
            echo "<br/>Session is not validated!";
            ## ADD CUSTOM CODE HERE
        }
    }

}


Create The Databases

CREATE TABLE IF NOT EXISTS `logins_test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `login` varchar(12) NOT NULL,
  `password` varchar(42) NOT NULL,
  `activation` varchar(40) DEFAULT NULL,
  `date_deactivated` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;




CREATE TABLE IF NOT EXISTS `logins_validate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `time_check` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

PHP OOP Login Class

The PHP OOP login code comes in two parts. One file is the class that connects to the database while the main file uses PDO objects to select and insert data.

Here is rundown of how it works. You have two main conditions; you have posted a login or you have not. If you post data by logging in, you will be successful or not. The code creates output based on success and failure.

Now, if there are no posted variables, you will either have a valid session or not. Validity is checked by matching the unix timestamp of your session variable against that of the value in the database. This way, only a valid timestamp will allow you to access sensitive code. Since PHP is more secure on some servers than others, this approach to check is taken.

Main File

include("class-login-PDO-form.php");
session_start();
$_SESSION['id'] = $_SESSION['id'];
$_SESSION['login'] = $_SESSION['login'];
$_SESSION['timestamp'] = $_SESSION['timestamp'];

$login = new Login();
$db = $login->db_connect();

//var_dump($db);
$username = array();
$password = array();
$myarray = array();
$myuser = array();
$mytime = array();
$my_check = array();

if ($_POST['username'] && $_POST['password']) {

    ##QUERY Sample#1
//$username = mysql_real_escape_string($_POST['username']);
//$password = mysql_real_escape_string($_POST['password']);
//$command = $db->prepare("SELECT * FROM logins_test WHERE login ='$username' AND password = password('$password')");

    ##QUERY Sample#2
    $username = $_POST['username'];
    $password = $_POST['password'];
    $command = $db->prepare("SELECT * FROM logins_test WHERE login =:login AND password = password(:password)");
    $command->bindParam(':login', $username);
    $command->bindParam(':password', $password);
    $command->execute();
    $result = $command->fetchAll();

    foreach ($result as $row) {
        $my_array[] = $row;
    }

    if (!empty($my_array)) {
        $_SESSION['id'] = $my_array[0]['id'];
        $_SESSION['login'] = $my_array[0]['login'];
        $_SESSION['timestamp'] = time();
        echo $_SESSION['id'] . " - " . $_SESSION['login'] . " - " . $_SESSION['timestamp'];
        echo "<br/>Success<br/>";

        $mytime = $_SESSION['timestamp'];
        $myuser = $_SESSION['id'];
        $command = "INSERT INTO logins_validate VALUES (NULL,:user_id, :time_current)";
        $command1 = $db->prepare($command);
        $command1->bindParam(':user_id', $myuser);
        $command1->bindParam(':time_current', $mytime);
        $command1->execute();

    } else {
        echo "Wrong username or password!";
    }
} else {
##VERIFY SESSION

    $mytime = $_SESSION['timestamp'];
    $myuser = $_SESSION['id'];

    $command = $db->prepare("SELECT * FROM logins_validate WHERE user_id =:login AND time_check = :mytime");
    $command->bindParam(':login', $myuser);
    $command->bindParam(':mytime', $mytime);
    $command->execute();
    $result = $command->fetchAll();

    foreach ($result as $row) {
        $my_check[] = $row;
    }

    if (!empty($my_check)) {
        echo "<br/>Session is validated!";
        ## ADD CUSTOM CODE HERE
    } else {
        echo "<br/>Session is not validated!";
        ## ADD CUSTOM CODE HERE
    }
}

echo "Is there an active session username: " . $_SESSION['login'];
echo "<br/>";
print_r($my_array);
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Username:<br/>
    <input type="text" name="username" value=""/><br/>
    Password:<br/>
    <input type="password" name="password" value=""/><br/>
    <input type="submit" name="submit"/>
</form>

Login Class

class Login
{
    private $host = "localhost";
    private $user = "username_goes_here";
    private $pw = "password_goes_here";
    private $database = "database_name_goes_here";

    /* function __construct()
    {

    }*/

    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}

Databases

The two databases used in this exercise can be created with code below.

CREATE TABLE IF NOT EXISTS `logins_test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `login` varchar(12) NOT NULL,
  `password` varchar(42) NOT NULL,
  `activation` varchar(40) DEFAULT NULL,
  `date_deactivated` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;




CREATE TABLE IF NOT EXISTS `logins_validate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `time_check` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

This simple tutorial has a very small class and lots of procedural code. Click this link if you want to see some more advanced PHP OOP Login classes.

Returning Variables From Functions

If you want to return a variable from a function, you have choices. The two methods discussed in this tutorial will be returning a global variable and returning a non-global variable.

Here is how the first code snippets works. The subtract function is called and it passes in 2 parameters. Then, the global modifier is used to make the $total variable have a global scope. After that, the $total variable is given a value, and finally, it is returned. As you can see, the variable behaves just as though it was created outside of the function and both echo statements are printed. If you did not have the global scope, the variable $total would be undefined and nothing would print.

function subtract($x,$y){
    global $total;
    $total = 101;

    return $total;

}

//prints the total
subtract(1,2);
echo "<br/>";

//prints the total
echo $total."<br/>";

if ($total == 101){
    echo "Hi";
}


Output

101
Hi


Returning Non-Global Variable

With example below, a variable is created and it is equal to the function and its parameters. In this case, the variable takes on the returned value from the subtract function.

function subtract($x,$y){
   // global $total;
    $total = 101;

    return $total;

}

//prints the total
$total = subtract(1,2);
echo "<br/>";

//prints the total
echo $total."<br/>";

if ($total == 101){
    echo "Hi";
}

Now that you have had some fun, you may want to expand on more PHP variable scope with PHP OOP.


PHP = and PHP ==

The PHP ‘=’ equal sign is commonly used to create variables and arrays. Asides from that, you will you often encounter the ‘==’ equal sign which is often used in statements and to compare values. If you ever receive an error with unexpected ‘=’, you should check for the mispelling. A tip to avoid errors is to use a good PHP IDE like PHPStorm. These editors are smart and they can find errros that you can change before you even test the script in your browser.

Anyways, the example below shows an error. It also shows code that causes the error and how to fix it.

Parse error: syntax error, unexpected ‘=’ in /home/user/public_html/folder/file.php on line 98

The error above is the impropper usage of a ‘=’ sign. One such error could be in an if statement when ‘=’ should have been ‘==’.

For example:

if($var=22) {do this}

should be

if($var==22) {do this}


Atutor LMS

Atutor is an LMS built with PHP mySQL. Technically, LMS is an abbreviation for Learning Management System. Two examples of learning management systems are Moodle and ATutor. that can be used to manage students and teachers. Atutor is a good choice for your learning management system since it starts you off strong built-in features; such as messaging, creating courses and almost unlimited expandability options.

Atutor can be hosted on servers which use php and mySQL. During installation, Atutor does a check for your server and shows any compatibility issues you may have. Chances are, you will be okay.

To use Atutor,

1) Download the zip file from atutor.ca
2) Unzip the file.
3) Upload the folder to its desired location.
4) Create a database and user for Atutor.
5) Open the website; such as example.com/ATutor.
6) Follow installation instructions.
Note: You may need to manually create a content folder.

Atutor Theming

The lighweight PHP / mySQL application called Atutor LMS can be used for your learning management system. The themes can be found in your themes folder. Many other files which you may want to edit are located in the include folder.

The files which may require editing are header.tmpl.php and footer.tmpl.php. Themes can easily be altered and edited with a little css know-how. The file style.css, which is located in the theme’s folder is where you may want to alter the layout. Neveretheless, there are two more files which have significant affect on the website; header.inc.php and footer.inc.php. These two files are located in the ínclude ‘folder’.

ATutor Changing Folder Names or Directories

By default, ATutor upzips with the name Atutor. You can FTP the folder into a desired website or folder. However, there are a couple of small changes that need to be made for the website to function properly.

Changes:

1) Open include/config.inc.php2)
Change:
define(‘AT_CONTENT_DIR’, ‘/home/user/public_html/example.com/ATutor/content/’);

Change To:
define(‘AT_CONTENT_DIR’, ‘/home/user/public_html/example.com/newname/content/’);

3) Open mysql database table AT_config

Change the session path:
ie)

Change:
/ATutor/

Change to:
/newname/

Making / Building ATutor Modules

Building modules with ATutor is a straight forward process. They have a module called ‘Hello World’ can than can be used as an example.

Here are a few notes to creating an ATutor module:

Basically find and replace module names:

For example, you would open the files below and change HelloWorld, helloworld, hello_world to mymodulename. Just keep the cases in tact and it you have a module with a new name in a couple of minutes.

Lower Case changes:
change module.sql
module_delete.php
module_install.php
module_uninstall.php
module.xml
module_cron.php
module_backup.php
index_public.php
index.php

UPPER CASE
index_instructor.php

BOTH CASES
module.php
index_mystart.php
index_admin.php

To start using the module,

1) FTP the folder into the modules folder.

2) Install the folder as an admin.

3) Enable the module.

4) Edit the module. Custom PHP scripts and coding can be used to give almost any desired feature you want to add.

After you have a new module, you will more than likely make changes to all index files; like index_mystart.php and index_admin.php. The module.php file is used to add pages which can be accessed through links, etc. The module.sql file can be edited to add custom database tables and data.


Find Duplicate Entries MYSQL

There could come a time when you want type a quick query that will find duplicate values in a column. For example, you could have multiple values for an IP address or you could be checking how many times a user has logged into an account.

The code below can be used to find duplicate email addresses in a table where the column name is email. The query below searches for the records that exists more than once. Simply change the number 1 to a higher number for filtering.

 SELECT * FROM tablename WHERE email IN (SELECT email FROM tablename GROUP BY email HAVING count(email) > 1) ORDER BY email ASC; 

If you just want to make a quick count of the duplicates in a column, you can use the one-liner shown below.

 SELECT COUNT(*), columname FROM tablename GROUP BY columname HAVING COUNT(*) > 1 

PHP Sort Array

Sorting arrays in PHP can be done with various functions. A multitude of sort functions can be found at PHP.net. One very common function to sort an array is with the simple sort() function.

Use PHP sort() function in its own line to sort an array. For example, date and datetime entries could be sorted by ascending. The sort function is placed on a line on its own after the original array is made. As you can see below, the array is sorted in alphabetical order.

$myarray = array("one", "two", "three"); 
sort($myarray); 
print_r($myarray);   //yields Array (     [0] => one     [1] => three     [2] => two )

Depending upon your needs you may need to use a different sort function; since some will sort by key and some will sort by value. For example, take a look at the associative array below.The example below is sorted by key using ksort().

 $myarray = array("one" => "first", "two" => "second", "three" => "third");  
ksort($myarray); 
print_r($myarray);     //yields Array (     [one] => first     [three] => third     [two] => second )

PHP Switch Statement

PHP Switch is a method that outputs a specific case depending on the value of a variable. It is another method which is similar to using if, else if and else statements.

The switch statement below looks for the value of the variable $var which is the variable $run which is ‘running’. Since the case is ‘running’, the output is ‘hello’.

$var = 25;
$run = 'running';
$var = $run;
switch ($var) {
    case 25:
        echo "hi ";
        break;
    case 'running':
        echo "hello ";
        break;
    default:
        echo "default";
        break;
}

MYSQL Copy Table

So, you have a mySQL table and you want to copy it. Although there are various methods to copy a table, the one shown below will demonstrate how to copy a mysql table in its entirety, including all data and structure.

Not only will the code below preserve the data, it will maintain the autoincrement field if it exists.

create table tablename2 like tablename1;  
insert into tablename2 select * FROM tablename1;

PHP File exists

The file_exists() function can be used to determine if a file exists. Once you know the condition, you can execute the code based on that result.

The code belows checks to see if there is a file called login.inc that is located one directory down from the current directory. If the file exists, it is included. Otherwise, the file login.inc that is located in the same directory is included.

$login_file = '../login.inc';
if (file_exists($login_file)) {
include('../login.inc');
}else{
include('login.inc');
}

PHPMYADMIN Collation Error

When you use mySQL databases and manage them with phpMyAdmin, you must be careful about the collation. If you try to do a join and the collation is different with two tables, you can get an error and will have to change one of the table’s collation in order to receice your expected mySQL query results.

The example below shows the phpMyAdmin error which explains that the collations are an illegal mix. After that, it is explained that you could change the collation of the utf_general_ci table to utf_unicode_ci. For simplicity, it is always easiest to design all of your database tables and indexed columns with uniform collations in order to avoid errors.

 PHPMYADMIN ERROR #1267 - Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation   Solution Collate the tables   ie) Change utf_general_ci to utf_unicode_ci 

PHP array_diff() Function

The array_diff() function in PHP is used to compare two arrays. After two arrays are compared, you will have an indexed array of results with all of the items that only belong to one of the two compared arrays.

## GET FIRST ARRAY
$command = "SELECT * FROM table1 ";
$result = mysqli_query($db, $command);
while($row = mysql_fetch_assoc($result)) {
$id = $row['ID'];
$ID1[] = $id;
}
 
## GET SECOND ARRAY
$command2 = "SELECT * FROM table2 ";
$result2 = mysqli_query($db, $command2); 
$rows_count = mysqli_num_rows($result2); if($rows_count >0) { while($row = mysqli_fetch_assoc($result2)) { $id = $row['id']; ## MAKE AN ARRAY OF ALL $id2[] = $id; } } else{ $id2[]=0; } ## COMPARE THE DIFFERENCE OF THE 2 TABLES AND GET THE DATES NOT FILLED IN FOR EACH ID $result_final = array_diff($1id, $id2);

PHP Properties Basics

The code below is about as simple as it gets to show how public, protected and private properties can be accessed.

As you can see, the parent class ‘tag’ has a public, protected and private property. After the $test object is instantiated with the line $test = new Form(); the constructor runs. As you can see, it only outputs the public and protected properties. On the bottom of the page, only the public property ‘$test->name’ will print.

class Tag
{

    public $name = "Peter";
    protected $name2 = "Paul";
    private $name3 = "Mary";


}

class Form extends Tag
{

    function __construct()
    {
        echo $this->name;
        echo $this->name2;
        echo $this->name3;
    }


}

$test = new Form();
echo "<br>";

echo $test->name. " \n";
echo $test->name2. " \n";
echo $test->name3. " \n";

PHP OOP Accessing Protected Properties

When you are using protected properties, they can be accessed with subclasses. However, if you want to print a protected variable from its parent class after you instantiate an object, you will receive a warning message.

The easiest way to explain this is to show the following example. As you can see, if you instantiate an object in the subclass and run a protected method from its parent, you will have access to all properties in the parent class and be able to return it. The reason for this is that the subclass has access to the method of the parent class. Then, the parent class method has access to all properties. However, if the method was private, you would not be able to use the method from the child class.

Besides that, you can output a property from the parent class using echo $test->name;. But, you will not be able to print a protected or private property from the instantiated Form() object. Therefore, printing $test->name2 gives you nothing.

All in all, the usage of public, protected and private properties and methods are what make OOP PHP such a well, organized technique for writing disciplined code.

class Tag
{

    public $name = "Peter";
    protected $name2 = "Paul";
    private $namethree = "Mary";
    private $myvar = "test";

    public function fromparent()
    {
        echo "hey public";
    }

    private function fromprivateparent()
    {
        echo "hey private";
    }

    protected function fromprotectedparent()
    {
        echo "Hey protected variable called: ";
        //$this->myvar = "testin";
        return $this->myvar;
    }

}

class Form extends Tag
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->fromprotectedparent();
        return $this->myvar2;
    }


}

$test = new Form();
echo $test->myvar2 . " \n";
echo "\n";

echo $test->name. " \n";
echo $test->name2. " \n";

PHP OOP Protected Functions

The whole essence of this brief tutorial is to emphasize that fact that protected functions cannot be used by an unrelated class. However, they can be used by a child class. With that said, the block of code will allow you to see a public function that is displayed in another class but the protected function will not. If you changed the line of code protected function from_unrelated_protected() to public function from_unrelated_protected() you will see that the function would work and display output since it is public.

class Tag
{

    public $a;
    public $b;
    public $c;

    public function from_unrelated_class()
    {
        echo "hey public";
    }

    public function from_unrelated_public()
    {
        echo "Hey public variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }

    protected function from_unrelated_protected()
    {
        echo "Hey protected variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }


}

class Form
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->from_unrelated_public();
        return $this->myvar2;
    }

    function get_protected(){
        $this->test2 = new Tag();
        $this->myvar3 = $this->test2->from_unrelated_protected();
        return $this->myvar3;
    }


}

$test = new Form();
echo $test->myvar2;
echo $test->get_protected();


Output

OOP Protected Functions PHP

If you do change the line of code:
protected function from_unrelated_protected()
to:
public function from_unrelated_protected()
you will see that the function will display output.

Hey public variable called: testin
Hey protected variable called: testin

PHP OOP Protected Properties

Properties and methods come in the form of public, private and protected. Public means any class can use them. Meanwhile, private properties can only be used by the class where they are declared and protected properties can be used by the class that defines them and their subclasses.

The code below shows how a subclass can call a protected function from its parent class from the constructor. The property from the parent class is returned from the function. After that, this variable is returned. The code near the bottom $test = new Form(); instantiates the object. The property is printed using echo $test->myvar2;

<?php

class Tag
{

    public $a;
    public $b;
    public $c;

    public function fromparent()
    {
        echo "hey public";
    }

    private function fromprivateparent()
    {
        echo "hey private";
    }

    protected function fromprotectedparent()
    {
        echo "Hey protected variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }

}

class Form extends Tag
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->fromprotectedparent();
        return $this->myvar2;
    }


}

$test = new Form();
echo $test->myvar2;

?>


Output

Hey protected variable called: testin

PHP call_user_func

With PHP, you can use call_user_func to call a function and use its parameters. The example below will demonstrate how it can be used with the str_replace() function. Under that, you will see how to use str_replace() to retrieve the same results.

In the first block, you will see that the function ‘str_replace’ is the first parameter, while the second, third and fourth parameters are those used by the str_replace function.  So, if you use str_replace() on its own, your parameters are find, replace, from string while the call_user_func() is the function name, find, replace, from string.

$a = 'testin'; 
$replaced = call_user_func('str_replace', 'in', '', $a); 
echo $replaced . "\n";   
$a = 'testin'; 
$replaced = str_replace("in", '', $a); 
echo $replaced . "\n";


Example #2

Here is a another example that uses a custom function called my_test(). Again, like the example above, it shows a tradition way to receive the desired results and the technique using call_user_func(). With this example, one variable is passed into the function and the same variable is returned with a new name. Finally, the variable is printed.

function my_test($input){ 
return $input; 
}  
$input = my_test('Bohemia'); 
echo $input . "\n";  
$example = call_user_func('my_test', 'Bohemia'); 
echo $example . "\n";


Example #3

This example is similar to the one above, except that two parameters are into the function; one called ‘Bohemia2’ and the $example variable that was created from the previous example.

function my_test2($input, $second) { 
return $input . $second; 
}  
$input2 = my_test2('Bohemia2', $example); 
echo $input2 . "\n";  
$example2 = call_user_func('my_test2', 'Bohemia2', $example); 
echo $example2 . "\n";


Output

test
test
Bohemia
Bohemia
Bohemia2Bohemia
Bohemia2Bohemia

Fiverr SEO

I am not sure what got into me one week, but, I sure had Fiverr fever. At the time, I was focusing on SEO and decided to see what five bucks would buy me. After reading various blogs and forums, I obviously did not expect much since more reviews were on the negative side. But, curiosity got the better of me, so I pulled out that credit card and made many back to back payments. I bought some PR 8 and PR 9 backlinks links, 150 edu backlinks and two SEO reports.

If you are still reading, you may wondering, how did things go? Well, the advertised handmade made links looked almost authentic, but not quite. The links were the same in all sources and looked machine generated, aside from the link address. I though he was using some auto mechanisms for slamming out so many $5 specials. But, they were ok.

The large volume .edu links were horrible; everything from not looking natural to a spinner that had no idea what it was talking about. After seeing the result, I only hoped my ranking would not be jeopardized. Never again would I use that service, even if I was paid to do so.

Fiverr SEO Reports

I did pay $10 for 2 SEO reports from top sellers and recommended vendors. One vendor, who had ranked well gave me an excel file that looked like it was made very quickly with Google Adwords, then, added a few columns based on the output. This was a waste and nothing that I do not do often myself. Another $5 down the tube.

Let Ther Be Light

However, I did find one vendor that provided a good detailed report. All I had to do was give them 1-3 keywords. They sent me a report of my website and the main competitors. This was done with decent software which can be moderately costly. I would certainly use this vendor again, unless there came a time when I wanted to pay $70 / month for similar software that analyzed my website and the competition. So, if you will need less than 15 reports a month, this can be a very valuable service since you obtain good results.

Returning Values With PHP OOP

When you use classes and OOP, you have various ways to return values. Asides from using OOP, you can also call functions and execute them without object scope.

With the Form class below, the values returned are ‘added’, ‘test2’, ‘gedit’, ‘test2’ and ‘apple’.

The first value ‘added’ was passed into the be() method and echoed within the function. The second value ‘test2’ was returned from the be() method. Both of these values are delivered from the code echo $test->be(‘added’); 

The third value ‘gedit’ came about from the set_var() and get_var() methods. The line echo “<br/>New Value: ” . $test2->get_var(); caused it to be printed.

The fourth value ‘test2’ came about by using the instance name and its property name. Thus, $this->b used within the class can be output as $test2->b from outside the class; as long as there is an instance $test2. The $test2 instance was instantiated with $test2 = new Form();

Finally, ‘apple’ was printed using Form::be(‘apple’); If you look at the image, you will see a warning because this method has no object scope; thus return $this->b; does nothing. From a procedural programmers point of view, using the scope resultion operation is similar to using a regular procedural PHP function. Note, if you comment Form::be(‘apple’); you will see that you can return a variable from the class just as you would with procedural PHP. The line $procedural = Form::be_procedural(‘orange’); will return the variable.

class Tag {

    public $aa = "";
    public $bb = "";
    public $dd = "";

   }

class Form extends Tag {

    public $a = "test";
    public $b = "test2";
    public $d = "testd";

    public function be($c) {
        echo $c . "<br/>";
        return $this->b;      
    }

    public function be_procedural($c) {
        echo $c . "<br/>";
        return $c;      
    }
        
    public function set_var($value) {
        $this->new_value = $value;
    }

    public function get_var() {
        return $this->new_value;
    }
   
}

$test = new Form('one', 'two');

echo $test->be('added'); 
echo "<hr>";


$test2 = new Form();
$test2->set_var('gedit');
echo "<br/>New Value: " . $test2->get_var();
echo "<br/>B Function: ". $test2->b."<br/>";
?>
<hr>
<?php
//NO OBJECT SCOPE
Form::be('apple'); 
$procedural = Form::be_procedural('orange');
echo $procedural;
?>

Browser Output

 

Matching Exact String With mySQL

MYSQL allows you to use several methods to find a precise string in a database column. A quick method is to use the LIKE ‘%mystring%’. This method will return any string which begins or ends with mystring. This can be quite useful for searching, but, if you want to output data that only has the precise match of ‘mystring’ in a sentence, then, you will need to find a regular expression.


REGEXP

The sample coding below will be used to modify all characters in a column to lowercase while the REGEXP operator will then find the match. The object of this exercise is to gather all articles from two categories that contain the text ‘OOP’ or ‘object oriented programming’ and display them with links back to their articles.

As you can see, mySQL uses ‘[[:space:]]’ as whitespace; unlike the usual \s* you would use in PHP or PERL. You may want to note that if you added ‘[[:space:]]’ in front of the word ‘object’, you would not select the data from the fulltext field if there were html characters in front of the object word. An example of characters in front would be an article that had a link on the words object oriented programming.

$command = "SELECT bc.id, bc.title, bc.alias as alias, bc.created as created, pl.permalink as permalink FROM prefix_content as bc, prefix_categories as bcat, prefix_myblog_permalinks as pl WHERE bc.sectionid='6' AND bc.catid IN(70,83) AND bcat.id=bc.catid AND (LOWER(bc.fulltext) REGEXP '[[:<:]]oop[[:>:]]' || LOWER(bc.fulltext) REGEXP 'object[[:space:]]oriented[[:space:]]programming' ) AND bc.state = 1 AND pl.contentid=bc.id ORDER BY bc.created DESC";
$result = mysqli_query($db, $command);

PHP Class To Parse Json String

This class can be used to output desired data from a Json string. Here is how it works. The Json string is fed into the constructor within the ParseJson class. Then, the public convert_to_array() function is called while passing in the $this->jsonString property.

Within the function, the Json string is decoded and array is returned. The array takes on the instance name and becomes $my_json->myarray. Thus, the loop which resides outside of the class parses the array using $my_json->myarray as $key => $val.

Class ParseJson
{

    public $jsonString;

    function __construct($json_string)
    {
        $this->jsonString = $json_string;
        $this->convert_to_array($this->jsonString);
    }

    public function convert_to_array($json_string)
    {
        // The second parameter in json_decode has a value of true. This is required to end up with an array.
        $this->myarray = array(json_decode($json_string, true));
        return $this->myarray;

    }


}

$json_string = '[{"A":"MyName","B":"www.example.com","C":"www.example.com/2/"},{"A":"MyName","B":"www.example.ca/","C":"www.example.ca/2/"}]';

$my_json = new ParseJson($json_string);

//print_r($my_json->myarray);

$i = 0;
foreach ($my_json->myarray as $key => $val) {
    $i = $i + 1;

    foreach ($val as $key2 => $val2) {
        echo $key2 . "-" . $val2['B'] . "<br/><br/>";
    }
}
?>

Parsing a Json String With PHP

There could come a time, when you have a Json string and you want to parse it as a regular array. There are many reasons why you could have this particular Json string.

For example, recently, I was examining the links of some high ranked websites for specific keywords and wanted to make an attempt to compete for those keywords. After analyzing their titles, content, keywords, headings and other factors, I finally came to the dreaded links. I was able to gather all of their incoming links, but, they were contained in a Json string.

So, at this point, I made a quick parser that could decode the Json string to a PHP array. Then, the array is parsed with PHP. Actually, I used a nested foreach loop to parse the value from a specific key.

The snippet below shows how easily this can be done.

<?php
error_reporting(0);
$var = '[{"A":"MyName","B":"www.example.com","C":"www.example.com/2/"},{"A":"MyName","B":"www.example.ca/","C":"www.example.ca/2/"}]';

// The second parameter in json_decode has a value of true. This is required to end up with an array.
$myarray = array(json_decode($var, true));

//print_r($myarray);

$i = 0;
foreach ($myarray as $key => $val) {
    $i = $i + 1;

    foreach ($val as $key2 => $val2) {
        echo $key2 . "-" . $val2[B] . "\n";
    }
}
?>


Browser Output

0-www.example.com

1-www.example.ca/


MYSQL Join Tutorial

Learning how to do mySQL joins is essential to anybody who needs to use mySQL on a regular basis. Since many web applications use joins in the coding, knowing what is happening is essential to troubleshooting and saving time when you need to make a customization.

A MYSQL join is a very simple concept. If you want to tie database tables together, they need matching keys. As long as every table has at least one key that matches another table, you can join data from one table to another and voila, you have custom output.


Where will I find mySQL Joins?

Web applications like Worpdress, Magento, Open Cart, Prestashop, Joomla, Drupal and so many more use mySQL joins. If you ever advance to the point where you can write custom PHP / mySQL applications using procedural code or OOP, you will more than likely write lots of mySQL queries. With practice, you will be able to avoid mistakes and understand the coding. It will make your workflow much easier and you will know read the code more as though it is your first speaking language.

If you cannot make sense of joins or do not care to improve your mySQL, you could end up spending a lot of time to do a simple task. An example of this is when someone installs a WordPress website with very little coding skills. One day, a client could want to make some larger upgrades that involve coding mySQL joins and you will be lost. You could lose the client too if he senses your lack of skills.

MYSQL JOIN EXAMPLES

Here are some examples of mySQL joins in this blog:

PHP / MYSQL Joins and Loops

PHP Hand Coding

Optimize Join Queries


How To Develop A Website

This article will explain how to develop a website. The methods explained may not be suitable for all users, but, the could enable you to start with a blank editor at point A and end up with a completed website at point B which loads at example.com.

To build a web site will need a domain name, the website files and database(if using a database) and hosting. The domain name must point to the location where the website is hosted. For example, you can point the nameservers for example.com to ns1.example.com and ns2.example.com.

Those are the basics to having a website on the web. However, I could go on about hosting and files until you would be so bored reading this you would be missing the good stuff which is about to come. 

how to develop a website
 


The Files

As far as the files go, they could be written from a professional programmer or they could be a commercial template with the words and images swapped. This area is wide open and the skill range can be huge. The coding could be php, C#, Java, Python, html, css, Jquery and mySQL… to name a few. For a noob, you may only use a template and edit the HTML files and swap images.

The Hosting

Cheap is a good way to start since traffic needs to be earned and it can take quite a while to have so much that you need a better service.

Full Stack Web Developer

Getting to the expert zone of things, you would have an overall grasp of the Linux server, SEO, programming in multiple languages and some graphic design skills. Of course, you may have weaknesses. 

As a full stack web web developer, you possess the skills to oversee all parts of a project and manage all who are involved.

For example, you could be a Linux and PHP / mySQL expert that does the heavy lifting and website set up. At this point, you have many options to complete a project. You could use a system like Smarty templating and outsource the design work. You can put the jobs up for bid, or use a service like Fiverr. You could send a rough image to graphic artist on Fiverr and get a $5 job that is a good as a local web designer who thinks it is worth $50.

Since the web design work and imagery has so many options for you to use, the full stack web developer can pick and choose what SEO and design work to hire that will save lots of time and yield good results. This is efficiency.

 

Simple Database Connection Class With PHP

This tutorial is a bare bones login class that can be used to connect to a database so that you can execute custom queries. It consists of two files; one contains the actual Login class while the other file will instantiate a new object and gather a variable from that class.

Rundown

The login class has four private properties; $host, $user, $pw and database. The class also uses the constructor which accepts the four arguments. These argumments are set as the properties.

The non-class file sets values for the variables that are passed into a new instantiated object. The code for this is $login = new Login($host, $user, $pw, $database);

Finally, the $db variable is returned using the db_connect() method. Now, the $db variable can be used to query the database. An example query shows how this occurs.

Login Class(class-login.php)

class Login
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


 function db_connect() {
 
 $host = "localhost";
 $user = "user";
 $pw = "password";
 $database = "database_name";

 $db = mysqli_connect($host, $user, $pw, $database) or die("Cannot connect to mySQL."); 

 return $db;
}

}

Other File(login.php)

include("class-login.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new Login($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = "SELECT * FROM tablename ORDER BY id ASC LIMIT 1";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
    echo substr($row['name'], 0, 1000);
}

PHP Database Connection Class Using PDO(PHP Data Objects)

The purpose of this two small code snippets is to provide a very lean, simple database connection class that you can use to query your mySQL database using PDO(PHP Data Objects). The coding consists of a pair of files; one of which is the class and the other which is the file which instantiates an object that provides a useful $db variable which can be used to make the queries.

Overview

A new object is instantiated and the database parameters are passed into the constructor. After the parameters are passed in, the db_connect() method is called and it returns the $db. The class does the work of creating a new instance of the PDO object and then returns it with the name $db. Now, $db can be used to do select, insert, update and delete statements. Since you are using a PDO object, you stick with the various methods that are available with the class; such as the execute() method. 

Class File

class DatabaseConnect
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}


Other File

include("class-login-PDO.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new DatabaseConnect($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = $db->prepare("SELECT * FROM cms");
$command->execute();
$result = $command->fetchAll();

foreach ($result as $row) {
    $my_array[] = $row;
}

print_r($my_array);

Using Memcache With Your Ecommerce Application

So there you are, you have setup that ecommerce store with a platform like Magento, Prestashop or Open Cart. After some time using and testing your website, you may have noticed you would like to upgrade the performance.

On the other hand, you may be researching your platform and want to know how to make a website that is fast and handle lots of traffic. Out of the box, Open Cart could be a great solution since it seems to run very fast right out of the box. Meanwhile, Prestashop and Magento, both of which have great features, may be slow loading and need fine tuning for a good, production website.

With that said, the rest fo the tutorial will explain how to upgrade the performance using PHP Memcache and the Linux Memcached server. For starters, this tutorial assumes you have them both working. if you do not, you can complete those steps at the web page http://fullstackwebstudio.com/locations/coding-blog/php-memcache-and-linux-memcached.html.

Magento

After Memcache is working, you can make Magento use it by altering the local.xml file in the /app/etc folder. An example snippet can be found at siteground.com/tutorials/supercacher/magento_memcached.htm. For Magento, that is all there is to do.

Prestashop

To use Memcache with Prestashop, login as the administrator. Then, select Advanced Parameters >Performance. After that, you add the server IP address and port and Save it. That is all there is to it.

Prestashop Memcached
 

Open Cart

Open Cart has many commercial Memcached options. You simply pay a few dollars, install a plugin and follow instructions from the plugin developer. Plugins can be found at http://www.opencart.com/index.php?route=extension/extension&filter_search=memcache.

Although the plugins are not free, do not let that discourage you from using Open Cart. It has its own caching system you can use when you install it and it is a very fast ecommerce application. Until you receive an abundance of traffic, you may never even need to consider using the Memcached server.

If you grow into a situation where your store receives so much traffic that you want to use Memcached, $25 should not break the bank.

Monitoring Memcached

The Linux command shown below can be used to view hits and other Memcached data.

 root# memcached-tool 127.0.0.1:11211 stats 

Google Crawl Page Quickly

If you have a new page that you want crawled you can speed up the process using Google Webmaster Tools. At one time, a typical webmaster may have built a static or dynamic web page, or blog post and wondered how long it will take for Google to crawl the page. Often, it can be just a matter of days; especially if you are adding fresh content on a regular basis.

However, if you use Google’s webmaster tools, you can have that page indexed within minute(s). The simple steps for doing this are shown below. All you need to do is login to Webmaster Tools before performing the following sequence of events.

Once you have logged in to Webmaster Tools, you click the website link. In this case, the link is fullstackwebstudio.com/locations/coding-blog.

Google Webmaster Tools Home Page
 

After the next page opens, you select ‘Crawl’ > ‘Fetch as Google’. 

Fetch as Google
 

Finally, you add the url into the input box and select ‘Fetch’. After you select ‘Fetch’, you click the ‘Submit to Index’ button that is displayed after you select ‘Fetch’. Once you have done that, select the radio button “Crawl only this URL” and click ‘Go’.

At this point, you can begin to browse Google for your new web page. 

Submit to Index
 

Make A Restful Service With PHP

This tutorial is a simple, lean-coded rest service that can be used to allow users to access specific data. Like other APIs from Flickr and other websites, you can sign up for an API that you can use on your own website. Normally, you add your username and password into a file and you are good to go.

Often, your API can accept an input and return an array of results. This tutorial will show how an authenticated user can access an array of data from your website using this rest service. It consists of three files; a client script, your server script and an .htaccess file.

Here is what is happening. When the client runs the file, it sends a curl request to the restful.php file. See the htaccess file below if you are confused why it is this file. It uses this file because the ‘s’ in the url becomes a $_GET variable. Once curl hits the page, it checks for the $_GET string and post variables.

Then, the condition is met and the output array is delivered by via an encoded JSON variable. Since curl returns a string, encoding the data with JSON and decoding in the client script will allow you to keep the array intact. 

As you can see, the client can parse the array and do whatever he wants with it. In a real world rest service, you could query a database and return an array of results to a client based on the member’s privilege.

In addition to that, the client could have a search box where they input strings of text for searching. Then, the restful.php file could create an array or an error based on the input.   

Client File

$url = 'http://example.com/foldername/s';
$curl = curl_init($url);
$curl_post_data = array(
    "username" => 1,
    "password" => 'password1',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);

$array = json_decode(trim($curl_response), TRUE);
print_r($array);


Server File

$var = array();
$var = htmlentities($_GET['name']);
if ($var == 's') {
    if ($_POST['username'] == 10 && $_POST['password'] == 'password1') {
        $myarray = array(1, 2, 3, 4, 5, 6, $var);
        echo json_encode($myarray);
    } else {
        $myarray = array(100, 101, 102, 103, 104, $var);
        echo json_encode($myarray);
    }
} else if ($var == 'st') {
    if ($_POST['username'] == 10 && $_POST['password'] == 'password1') {
        $myarray = array(1, 2, 3, 4, 5, $var);
        echo json_encode($myarray);
    } else {
        $myarray = array(100, 101, 102, 103, $var);
        echo json_encode($myarray);
    }
}


HTACCESS File

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([a-zA-Z_-]+)$ restful.php?name=$1 [nc,qsa]
RewriteRule ^([A-Za-z_0-9]*)$ restful.php?name=$1 [nc,qsa]

Memcache With PHP and Linux Memcached

Using Memcache with PHP programming allows you to cache output and mySQL queries. Essentially, you can cache whatever you want. There are obvious benefits to caching; like retrieving web pages mush faster while using less server resources. If you dig some data up around the web, you will see that some very large websites use memcached.

In order to use memcache with php you need to install the memcached server on your Linux system and you need to install memcache module for PHP. There are zillions of tutorials which explain how to do this. You can Google your operating system and find the method for your chosen Linux distro.

Installing memcached server from source can be a solution if quick installation methods like ‘sudo apt-get install memcached’ or ‘yum install memcached’ fail. One tutorial can be found at http://www.cyberciti.biz/faq/howto-install-memcached-under-rhel-fedora-centos/. Another memcached server method is shown below. Be patient and you will have a successful installation.

Sample Memcached Server Installation

root# Install memcached pecl
root# yum install memcached php-pecl-memcache

Once you have memcached installed and working you can start and stop its services with the following commands:

root# /etc/init.d/memcached start
root# /etc/init.d/memcached stop
root# /etc/init.d/memcached restart

In addition to running the service, you can use chkconfig to start it upon boot.


To add the service to chkconfig,

root# /sbin/chkconfig --add memcached

To see if the service was added to chkconfig,

root# /sbin/chkconfig --list memcached
memcached           0:off   1:off   2:off   3:off   4:off   5:off   6:off

To add the service to start upon boot,

root# /sbin/chkconfig memcached on

To check that the service was changed with chkconfig,

root# /sbin/chkconfig --list memcached
memcached           0:off   1:off   2:on    3:on    4:on    5:on    6:off

Installing memcache for PHP can also be done via the command or using EasyApache with Web Host Manager.

Alternatively, you can install memcache from source. An example installation is shown below. The ‘foldername’ is one you choose and the path can be added to the php.ini file; which will be explained later in this tutorial.

root# mkdir tmp
root# cd tmp
root# wget http://pecl.php.net/get/memcache-2.2.7.tgz
root# tar -zxvf memcached-2.2.7.tgz
root# cd memcached-2.2.4
root# phpize && ./configure --enable-memcache && make
Find where php stores it modules from php.ini ie) /usr/local/lib/php/extensions/foldername
Copy modules/memcache.so to /usr/local/lib/php/extensions/foldername
root# cp modules/memcache.so /usr/local/lib/php/extensions/foldername

Once you have installed memcache you may have to add the extension to your php.ini file. Below are two methods that will point to the memcache.so file; one uses a typical path and the other uses the absolute path. In some cases, you will need to use the absolute path in order to make it usable.

extension = "memcache.so"
extension = "/usr/local/lib/php/extensions/foldername/memcache.so"

To see if memcache is usable you can use the command echo phpinfo(); and find memcache in the list.

PHP Memcache and Linux Memcached

Finally, if you are still with me, you try some simple scripts below to test your memcache. To make things easy, the cache is only set for 30 seconds so that you can see your data does in fact cache. If you hit a page on the first go, you should receive the first query from mySQL.

On the second go, you should receive the query from memcache. After 30 seconds, you can try again and it should hit mySQL again. On a production site, you probably want to set the cache for longer time periods.

Code

include('../public.inc'); //include the file that connects to database
session_start();
$db = connect();


/**
 * First Simple Example
 */

$mem = new Memcache();
$mem->addServer('localhost', 11211);
$mem->set('key', 'my_cached_string', 0, 30);
$test = $mem->get('key');
var_dump($test);
echo "<br/>";


/**
 * Second Simple Example
 */

$mem_instance = new Memcache();
$mem_instance->addServer('localhost', 11211);

$query = "SELECT * FROM tablename ORDER BY id ASC LIMIT 1";
$command2 = mysqli_query($db, $query);
$my_key = "KEY" . sha1("CAN BE ANYTHING. DUMMY FUNCTION SO THE GET METHOD WON'T FAIL");
//GET QUERY KEY
$result = $mem_instance->get($my_key);

if (!$result) {
    $command = "SELECT * FROM tablename ORDER BY id ASC LIMIT 1";
    $result = mysqli_query($db, $command);
    $row = mysqli_fetch_assoc($result);
    // SET QUERY KEY
    $mem_instance->set($my_key, $row, 0, 30);
    echo "Result from mysql<br/>";
    return false;
}

echo "Result from memcache:<br/>";
echo var_dump($result);
return 0;

?>

In a addition to memcached, you can use the mysql query cache to cache queries too. On top of all of this, you can use the Varnish cache which will bypass all of this and pull a cached Varnish page.

Troubleshooting Memcached Server

If you are testing the memcached server, you may want to flush the cache. The snippet below explains how to clear it.

telnet localhost 11211
flush_all
quit

Smarty Templates and Angular JS

Angular JS is a Javascript framework that fits in well with Smarty templates. To use the Angular JS framework, all you need to is alter the <html> tag tag to <html ng-app>, add the script angular.min.js into the head and add ng-model tags to your form elements. 

To use Angular JS with Smarty has a little twist from a basic html page. You will use literal tags around the angular js tags which look like {{ng-model value goes here}}. So, with the example below, an html file would write the output of the first name by using  {{first_name}} while Smarty will look like {literal}{{first_name}}{/literal}. A you can see, the tags for Angular JS are very similar to Smarty which makes them very easy to use with Smarty templates.

The example below will show the complete usage.

.php File

<?php
if (count($_POST) > 0) {
// die("Works");
    print_r($_POST);
    echo $_POST['first_name'] . " - " . $_POST['last_name'];
}

include("libs/smarty.class.php");
$smarty = new Smarty ();

$smarty->display("includes/header.inc.tpl"); //compile and display output
$smarty->display("angular.tpl"); //compile and display output
$smarty->display("includes/footer.inc.tpl"); //compile and display output
?>

.tpl File

<!doctype html>
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.min.js"></script>
</head>
<body>
<div>
    <form name="job_form" method="post" action="{$smarty.server.PHP_SELF}">
        <p>First Name:</p>
        <input type="text" ng-model="first_name" name="first_name" placeholder="">

        <p>Last Name:</p>
        <input type="text" ng-model="last_name" name="last_name" placeholder="Last Name Here">
        <input type="submit" name="submit" value="Submit"/>
    </form>
    <hr>
    <h2>Direct output:</h2>

    <p>My name is {literal}{{first_name}}{/literal} {literal}{{last_name}}{/literal}!</p>
</div>
</body>
</html>

Browser Output

Add Content HereAdd Header Code Here

First Name:

Last Name:

  Submit 


Direct output:

My name is John Smith!

Add Custom Footer


Convert to Linux FROM Windows XP or Windows Vista

If you have a computer with a faulty Windows installation, or a pc that just runs too slow with Windows, you may want to give Linux a try. Two distributions which have a modern look feel and functionality are Ubuntu and Linux Mint. Generally speaking, you can download the iso and write the image to a USB stick or CD. Then, you allow your BIOS to boot from USB or CD and go through a typical installation.

Installing Linux does have many advantages beyond having a working system. For example, I have a desktop PC with dual hard drives. One hard drive has Windows Vista and the other Linux Mint. The performance is night and day. The Windows Vista is slower all the way around; from boot to general usage. Meanwhile, the performance of Linux Mint on that 1GB memory PC can be compared to my higher end Laptop when it runs Windows 7. The performance of Ubuntu partitions and Virtual machines on the same laptop is much faster too.

With those details in mind, you should have renewed hope with your older, malfunctioning computer. Alternatively, if you are a web developer and need a decent working machine you could skim some costs and turn somebody’s junk into your own treasure.  

The key with installing Linux could be patience. In some cases, the drivers or graphics could limit your installation. For example, I recently installed Ubuntu on an old HP DV9000 and the graphics did not look desirable at first. After some tweaking, I could get my desired resolution, but the system had a few errors. Being impatient and finding this buggy, I immediately decided to install the latest Linux Mint.

This failed, even though the same version installed fine on my desktop PC. So, I decided to install the previous version of Linux Mint. Ten minutes later, all went well. So, if you don’t want to get down and dirty with command-lining, but just want a usable faster Internet surfing device, it should not take you long to be up and running.

Another area where you could have issues with Linux is networking. In some cases, your pc will work upon installation, while at other times the Internet connectivity could cause issues. If you want to be up and running with Ethernet or wireless, a no-brainer solution is to buy USB wireless or USB network adapters that are plug and play compatible with Linux. Then, you can just plugin them in and go.

Otherwise, you may need to find and install drivers. Personally, I find ordering a few of each on Ebay for around $5 each is worth the savings of hunting down and installing drivers. Another option, if you have at least 1 wireless network adapter, is to connect to the Internet and hopefully download your desired driver.  

So there you go. The above lesson for converting the Windows machine to a Linux machine had been covered. I would like to remind you that the key points you should remember are to install a Linux installation that works perfectly upon installation. The only minor change you should have to make is to alter the screen resolution. If this is not possible or you have errors, move on and find one that does work better. In addition to that, having external wireless or ethernet adapters will make your Internet connections painless experience. 

Include Files With Smarty Templating

Smarty templates allow you two methods to include files. One method would be to use your ‘.php’ file and the other is to use the ‘.tpl’ file.

Method A

.php File

include("libs/smarty.class.php");
$smarty = new Smarty ();

$smarty->display("includes/header.inc.tpl"); 
$smarty->display("include.tpl"); 
$smarty->display("includes/footer.inc.tpl"); 


.tpl File

<p>
Here is some text from the main file. 
</p>


Method B

.php File

include("libs/smarty.class.php");
$smarty = new Smarty ();

//$smarty->display("includes/header.inc.tpl"); 
$smarty->display("include.tpl"); 
//$smarty->display("includes/footer.inc.tpl"); 


.tpl File

{include file='includes/header.inc.tpl'}
<p>
Here is some text from the main file. 
</p>
{include file='includes/footer.inc.tpl'}


Same Browser Output From Both Methods

Add Header Code Here

Here is some text from the main file.

Add Custom Footer

Functions and Smarty Template Tutorial

Whether you build a simple website or web application with Smarty, you want to use functions. With Smarty, you have two options for which you can use them.

For one, you can code them into your existing ‘.php’ file and use them from there since a function will will either output a print statement, or return a string or array.

Your second option is to call them from within the design(.tpl) file. You are able to successfully call and use functions using the Smarty {insert} tag. An example is shown below.

Function

This simple function will print the text Hello World, create a variable called $new_world and return it from the function. All functions will have ‘smarty_insert_‘ precede the actual function name, which in this case is called hello_world.

 <?php  
function smarty_insert_hello_world(){ 
echo "Hello world"; 
$new_world = " is returned "; 
return $new_world; 
}

.php File

The ‘.php’ file includes a template header, main file and footer file. The function.tpl is the one which is relevant for this tutorial and its usage will explained.

include("libs/smarty.class.php"); 
$smarty = new Smarty ();  
$smarty->display("includes/header.inc.tpl"); 
$smarty->display("function.tpl");  
$smarty->display("includes/footer.inc.tpl");  
?>

.tpl File

The {insert} tag below will call the function hello_world from the file functions.inc. After that, the returned variable will take on the name {$function_tag_name}.

 <p> {insert name="hello_world" assign="function_tag_name" script="functions.inc"} {$function_tag_name} from the function. </p>

Output

The second line of output came from the ‘.tpl’ file. The top and bottom lines are just the header and footer file where the main menu and footer file can be created for all pages of the web application.

Add Header Code HereHello world is returned from the function.

Add Custom Footer

Using Configuration Files With Smarty Template

Smarty templates allow you to declare and use variables with various methods. two popular methods are to use the assign() method within the ‘.php’ file or to use a configuration file. Since this tutorial will explain how to use a configuration file to create variables and create syntax to output them with the ‘.tpl’ files, it is assumed that you have some familiarity with the assign() method. If not, you can find some details at http://fullstackwebstudio.com/locations/coding-blog/smarty-template-for-php.html that show how to assign variables with the assign() method.

Using a configuration file is simple. You declare all of your global variables and section variables. When you access variables from the config file, you use the syntax {config_load file=’config.conf’} or {config_load file=’config.conf’ section=’mySection’}. When you output variables from a configuration file, they use the syntax {#variableName#}, unlike {$variablename} that is used with the assign() method.

config.conf File

This file has 3 global variables. In addition to that, there are two distinct sections that have their own variables; my_section1 and my_section2. The examples below show various ways for which you can assign variables. Like Python, Smarty allows you to declare variables without the need for a semi-colon at the end.

# global vars
var1 = "Double Quotes No semicolon"
var2 = 'Single Quotes No semi-colon'
var3 =  'Single and semi-colon';

#Section vars
[my_section1]
var4 = 500
var5 = "String in my_section1";

[my_section2]
var6 = "String in my_section2";

config.tpl File

This file shows three different loads for the configuration file. To show how it works, The code is used to output all variables from all sections. As you can see in the first example using {config_load file=’config.conf’}, only the global variables will output.

When the next load {config_load file=’config.conf’ section= “my_section1”} takes place, all the global variables and the variables from my_section1 can be accessed.

Finally, when {config_load file=’config.conf’ section= “my_section2”} is loaded, you see all variables. This may, or not be what you expected. But, since all variables had been loaded with the {config_load} tag, they are all usable.

{config_load file='config.conf'}
<p> Here are all variables:<br/><ol><li>{#var1#} <li>{#var2#}</li> <li>{#var3#}</li> <li>{#var4#}</li> <li>{#var5#}</li> <li>{#var6#}</li></ol></p>
As you can see, only the global variables output. Variables var4, var5 and var6 must have their section added to the config_load. The example below shows the opposite. It will only display variables that belong the appropriate section.
<hr>

{config_load file='config.conf' section= "my_section1"}
<p> When you declare a section, you can output all global variables and variables that belong to that section. <br/><br/>Here are all variables in in my_section :<br/><ol><li>{#var1#} <li>{#var2#}</li> <li>{#var3#}</li> <li>{#var4#}</li> <li>{#var5#}</li> <li>{#var6#}</li></ol></p>
<p>As you can see, var6 has no value since it belongs to my_section2.</p>  
<hr>Finally, here is the usage of two sections.<br/>

{config_load file='config.conf' section= "my_section2"}
<br/><ol><li>{#var1#} <li>{#var2#}</li> <li>{#var3#}</li> <li>{#var4#}</li> <li>{#var5#}</li> <li>{#var6#}</li></ol>

Here is how the output is displayed in the browser.

Add Header Code Here

Here are all variables:

  • Double Quotes No semicolon
  • Single Quotes No semi-colon
  • Single and semi-colon

As you can see, only the global variables output. Variables var4, var5 and var6 must have their section added to the config_load. The example below shows the opposite. It will only display variables that belong the appropriate section.


When you declare a section, you can output all global variables and variables that belong to that section.

Here are all variables in in my_section :

  • Double Quotes No semicolon
  • Single Quotes No semi-colon
  • Single and semi-colon
  • 500
  • String in my_section1

As you can see, var6 has no value since it belongs to my_section2.


Finally, here is the usage of two sections.

  1. Double Quotes No semicolon
  2. Single Quotes No semi-colon
  3. Single and semi-colon
  4. 500
  5. String in my_section1
  6. String in my_section2

Add Custom Footer


Backup and Restore With Linux

Moving updated files from one server to another server can be done with few Linux commands. To move or backup files to another server, you could create a tar or zip file on one server. Then, you can use SCP to move the tar or zip file to the foreign server. After it reaches its destination, you extract it.

From a backup point of view, it only makes sense to backup the folder to a new server when the files change. In this case, you can run a cron job that checks for file modification, and only creates and sends the backup when there are updated files. You could make this check at any desired interval that you want; from hourly to daily to weekly.

The server which will store the backups can have a cron job that checks for a new backup tar or zip file within a specific directory. Then, if its date is within a specified time interval, you can run a command to extract the tar or zip file.

Make the Backup on Host Machine

The one-liner below shows how to check and make a backup tar ball for all of the new files within 1 day.

root# find /home/username/public_html/foldername -type f -mtime -1 | xargs tar -czf foldername.tar


Moving tar file to New Server

root# scp -P 22 /home/username/Desktop/foldername.tar test@example.com:/home/username/public_html/foldername.tar


Restore the Backup On Slave Machine

The line below shows how to extract the tar file from the machine which stores the backups. It will only overwrite the old files which have been modified and leave the rest intact.

root# tar -xvf foldername.tar

Alternatively, you could run the following code with a cron job. It will look for the file to see if it is less than 1 day old. If it is, the tar file is extracted. If it is not, output is redirected to the black hole ‘> /dev/null 2>&1’. With this bash command, the find command is run. After that, the ‘&&’ operator represents the if statement and the ‘||’ operator represents the else statement.

//Test
root# [ `find /home/username/public_html/foldername.tar -type f -mtime -1` ] && tar -xvf  /home/username/public_html/foldername.tar || echo "File is within 1 day"

//Production
root# [ `find /home/username/public_html/foldername.tar -type f -mtime -1` ] && tar -xvf  /home/username/public_html/foldername.tar || > /dev/null 2>&1


One more method to check the file created date and extract it if it is within 1 day old is shown below. This technique uses a single command. It looks for the file that was created within one day, then runs the ‘-exec’ action which is another linux command. 

root# find /home/username/public_html/foldername.tar -type f -mtime -1 -exec tar -xvf  /home/username/public_html/foldername.tar \;

The steps above can be used to backup and move new files. But, to do it automatically, you need to run cron jobs that use these commands as bash scripts. Also, you need to use SSH keys to transfer the files via SCP without a password or the transfer will not happen.


Web Designer Access With Smarty Templates

One of the main reasons you may have chosen the Smarty template engine with PHP is that you want to separate the logical coding from the design coding. For example, the logic may be coded by your trusted developer, but, you want the flexibility with your options for the web design. Since you may outsource the design work to one or more people, your system could adapt into one for which you would limit file access to each individual with restricted access.

Smarty templates is perfect for this situation since you could create a folder with the file permissions of 750 for the designer. With Linux, it is done with the simple command chmod 750 myfolder. These permissions mean that the designer can edit and upload files, but, the files will not run in the browser because the ‘world’ does not have this permission.

However, the logic ‘.php’ file that exists in another can be executed in the browser and will be in a folder with the usual, adequate permissions of 755; which is the default for any new folder you create in a public_html directory or www. With that said, Smarty will compile the templates as you expect and you will see the output you would expect.

Checklist:
Logic Coder(.php files): 755
Design(.tpl) files: 750

Now that you have made arrangements for the designer to have designated folders for which to keep working files, you could run a simple cron job to track any changes that have occured in the folders. This way, you can keep tabs on work progress and security. You could use a tool to view the changes from previous work too.

Regardless of all the arguments about using a template engine like Smarty, separating logical coders from designers is one large benefit that can have multiple advantages for increasing productivity and file security. If everything you read thus far in this article is not enough to convince you of Smarty’s advantages, I will add a few more examples where it can have value.

Case #1 Outsourcing Design

From a web development point of view, more than 90% of all websites are completed by a company within 80 km. This number was published in the ‘Web Design Business Kit’ from Sitepoint. This means, being local has its advantages since people want to be close to those who do their work.

Now, for the advantage. There are many new companies who come and go in the web design business and many low-balling companies that work on the cheap. With this mind, you can remain competitive by coding high performance web pages and applications, while outsourcing the design work. Now, you can maintain a high performance website while cutting costs on design.

Case #2 SEO

Now that a project is up and running, you always have the option to outsource the SEO work to another person or company; especially if the modifications are made within the ‘.tpl’ files.

Backup and Restore a MYSQL Database

This tutorial will show the steps that can be used to backup a mySQL database, move it to a new server and restore it. Although this can be done very quickly with GUIs like Cpanel and phpMyAdmin, the tutorial explanations use the Linux command line. After all, if you want to do synched backups automatically with Cron jobs, the GUI cannot do that for you.

Simple One Time Move

//Copy It
username# mysqldump -u root -p mydb > mydb.sql 
or with password
useraname# mysqldump -u root -pAddPasswordHere mydb > mydb.sql

Move It
scp -P 22 /home/username/Downloads/mydb.sql test@example.com:/home/test/public_html/mydb.sql

//Restore it
Create database, if necessary
mysql -u root -pAddPasswordHere -e "create database mydb"

//Add the tables 
mysql -u root -pAddPasswordHere mydb < mydb.sql

Continual Backups

This setup can be used if you want to empty and overwrite existing databases. Unlike the example above, the -e flag allows you to write single or multiple mySQL commands. With the example below, the database is destroyed, recreated and dumped with a fresh set of data.

You could run a cron job on one host that will move the sql file to the new server. Meanwhile, you could run a cron job on the foreign host so that it dumps the desired data at your preferred time(s). In addition to these commands, you will need to use ssh keys so you can SCP the file without using a password.

//Copy It
username# mysqldump -u root -p mydb > mydb.sql 
or with password
useraname# mysqldump -u root -pAddPasswordHere mydb > mydb.sql

//Move It
scp -P 22 /home/username/Downloads/mydb.sql test@example.com:/home/test/public_html/mydb.sql

//Restore it
mysql -u root -pAddPasswordHere -e "drop database if EXISTS mydb; create database mydb;" ;mysql -u root -pAddPasswordHere mydb < mydb.sql 

Although this article is targeted at copying and restoring mySQL databases, moving files to another server can be done with similar methods. For example, you could create a tar or zip file on one server, SCP the file to another server and extract it when it reaches its destination.

Object Oriented Programming With Smarty

Using OOP with the Smarty template engine can be done with relative ease; especially if you have a decent understanding of OOP to begin with. If words like scope, public, private, constructor, inherit, class, methods and properties do not strike a chord, then, you may want to strengthen your OOP skills before you go one step further and adapt them to Smarty templates.

Now for the fun part. Let’s create some classes within the ‘.php’ file and make them output as expected using Smarty’s advanced features. Again, like previous examples, it is easier if you can see the codes and test your pages with your browser. The two files are shown below.

.php File

Here is the file which does the heavy lifting. The file starts with the usual instantiation of the Smarty class. Then, there are the two classes; Tag and its child class called Form. Underneath both classes, an object for each class was instantiated using the new() operator. For example, the Form class was instantiated with $test = new Form(‘one’,’two’,”);.

After that, the assignByRef() was used to allow us to assign an objects named my_object and my_tag. The second parameter contains the recent object that was created. In our example, the second parameters are $test and $test2. Unlike OOP without Smarty, the $test object now will be used with the ‘.tpl’ file under the new name $my_object.

So, if you are to use pure PHP, you would just write $test->be(‘add input here’) whereas in the .tpl file it will look like $my_object->be(‘add input here’).

Change the return value form the be() method to see your various values which you can output.

<?php include_once("libs/smarty.class.php"); 
$smarty = new smarty();  

class Tag {      
public $a = "test";     
public $b = "test2";     
public $d = "testd";      

function __construct($a, $b) {              
}          

public function fromparent(){         
echo "hey public";     
}          

private function fromprivateparent(){         
echo "hey private";     
}           

protected function fromprotectedparent(){         
echo "hey protected";     
}  
}  

class Form extends Tag {      
function __construct($a, $b) {         
parent::__construct($a, $b); 	
$this->a = $a;         
$this->b = $b; 	
} 	 	
public function be($c) {         
//return $this->b;           
//return $this->d;		 	  
return $c;     } 
} 	 

$test = new Form('one','two','');  
$test2 = new Tag('required','also required');  
$smarty->assignByRef('my_object', $test); 
$smarty->assignByRef('my_tag', $test2); 
$smarty->display("object.tpl");


.tpl File

Here is the file which will output data from the classes. As you can see, they use special tags. The tags below will output two methods from the two classes.

 <html> 
<head> 
<title>Job Application Form</title> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
<body>  
{* output assigned object *} 
{$my_object->be('from template')} <br/> 
{$my_tag->fromparent()}  
</body> </html>

Why Every Web Developer Should Write or Blog

This might come as a surprise to write such an article, but it could help with your journey as a web developer / programmer. The main reason I would even suggest such a title or this advice can be put in the next simple sentence. All coding can be learned much more effectively if it is presented to you in a form that you learn best.

Before we get to your writing, let’s start with something you can relate to… good teacher and bad teacher. For example, I remember taking Calculus back in the day when one teacher was in his own world and nobody really knew what he was talking about. To make things worse, the text book he chose was written by an author who just could not get through to the masses.

After the semester, I switched to a professor that was great communicator that kept everyone interested. In addition to that, he wrote the textbook which just made sense. Now, the outcome should be obvious and I will state the obvious. Since the second teacher had made learning easier and enjoyable, the concepts stuck and my grade was significantly better.

So, with that said, I will continue explaining why your should blog or write. The main reason is that your notes and methods probably make the best fit for your learning. Therefore, if you read or learn from another source and it is off the grid from your normal methodology, you may want to create a better resource you can always come back to. Here is where you can create a code snippet and great blog post that not only will help others and yourself, but, it will save you time in the future when you need to use it again. If there is one thing a web developer will do in the future it is doing something very similar to what he had already done. 

Asides from structured learning and a better resource, your blogging and writing could help supplement your career choice and drive targetted traffic your way.

Although writing and blogging can accelerate your skills, it does not mean that other sources are invaluable.. just the opposite. It is always good to learn how to see through the eyes of another and know what the coding does. The more code you read from other sources, the better you will be at handing all sorts of coding from various web applications, frameworks and content management systems. Eventually, the coding suprises will become fewer and far between and your production will skyrocket.

Essentially, your writing should be an accellerator and your reading and curiosity should better your knowledge.

Tutorial For Smarty Forms

This Smarty form will contain some of the usual form elements like input text, radio buttons, text boxes, select drop down menus and a submit button. This sample is a mock for a job application form. If you go through both files, you can see how the variables, arrays and code is set in the ‘.php’ file and how to display it with the ‘.tpl’ file.

In addition to outputting the code, this job application form also includes some Jquery usage. So, when someone clicks on a city, it will automatically choose the appropriate state or province and country. This will give a little insight into building a custom form.

The easiest way to see what is going on is to view the page in a browser like Firefox while using Firebug. Then, you can look at these codes and match up each form element with its PHP code. For example, as you can see, the value for a drop down option is the key in the array. Also, the Smarty tag ‘ {$smarty.server.PHP_SELF}‘ is the PHP equivalent of <?php echo $_SERVER[‘PHP_SELF’]; ?>.

.php File

<?php
if(count($_POST) > 0){
// die("Works");
print_r($_POST['skills']);
echo $_POST['email'];
}

include_once("libs/smarty.class.php");
$smarty = new smarty();

$smarty->assign("name", "Add Name Here");
$smarty->assign("email", "");

$smarty->assign("phone", "");

$cities = array("California" => "Los Angeles", "Texas" => "Houston", "New York" => "New York", "BC" => "Vancouver", "Alberta" => "Edmonton");
$smarty->assign("cities", $cities);

$countries = array("United States", "Canada");
$smarty->assign("countries", $countries);

$states_provinces = array("California" =>"California", "Texas" =>"Texas", "New York" =>"New York", "BC" => "BC", "Alberta" => "Alberta");

$smarty->assign("states_provinces", $states_provinces);
$smarty->assign("state_province", NULL);

$ages = array("18-24", "25-30", "30-36", "37-45", "46-50", "50-65");
$smarty->assign("ages", $ages);

$smarty->assign('salaries', array(
1 => '$20000-$30000',
2 => '$30000-$40000',
3 => '$40000-$50000',
4 => '$50000+'));
$smarty->assign('salary_selected', 4);
$smarty->assign('skills', array('Technical / Content Writer', 'Web Designer', 'Web Developer', 'Full Stack Web Developer / Linux Admin'));
$smarty->assign("skill", array(0,3));
$smarty->display("jobs.tpl");
?>

.TPL File

<html>
<head>
<title>Job Application Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">
{literal}
body, label {font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
}
{/literal}
</style>

<script src="jquery.js"></script>
</head>

{literal}
<script type="text/javascript">

$(document).ready(function() {
$( "#email" ).click(function() {
  alert("Hey2");
});

    $("#city option").filter(function() {
        return $(this).val() == $("#state option").val();
    }).attr('selected', true);

    $("#city").live("change", function() {
	
	if($(this).val() == 'New York' || $(this).val() == 'Los Angeles' || $(this).val() == 'Houston'){
	$("#country option:selected").val("US").html("USA");
	}else{
	$("#country option:selected").val("CAN").html("CAN");
	}
        $("#state").val($(this).find("option:selected").attr("value"));		
		
    });
});

</script>
​{/literal}


<body>
<p><strong>Job Application Form</strong></p>
<form name="job_form" method="post" action="{$smarty.server.PHP_SELF}">
<table>
<tr>
<td width="165">Name: </td>
<td width="158"><input name="name" type="text" id="name" value="{$name}"></td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email" type="text" id="email" value=""></td>
</tr>
<tr>
<td>Phone: </td>
<td><input name="phone" type="text" id="phone" value=""></td>
</tr>
<tr>
<td>City: </td>
<td><select name="city" id="city">
{html_options options=$cities}
</select></td>
</tr>
<tr>

<tr>
<td>State: </td>
<td><select name="state" id = "state">
{html_options options=$states_provinces selected=$state_province}
</select></td>
</tr>

<td>Country: </td>
<td><select name="country" id="country">
{html_options options=$countries}
</select></td>
</tr>


<tr>
<td valign="top">Available Start Date: </td>
<td style="min-width:500px;">{html_select_date}</td>
</tr>

<td>Ages: </td>
<td><select name="age" id="age">
{html_options options=$ages}
</select></td>
</tr>

<tr>
<td valign="top">Salary Expectations: </td>
<td>{html_radios name="salary" options=$salaries selected=$salary_selected separator="<br />"}
</td>
</tr>
<tr>
<td valign="top">Skills: </td>
<td>
<p>{html_checkboxes name="skills" options=$skills selected=$skill separator="<br />"}</p>
</td>
</tr>
<tr>
<td><input type ="submit" name = "submit" value = "Submit" /></td>
</tr>
</table>
</form>

</body>
</html>

Using PHP {literal}{/literal} Tags

Literal tags which use the syntax {literal}{/literal} can be used to take the code literally within the ‘.tpl’ file, thus, not interpreting it. Two common places where you would use the literal tags are with CSS and Javascript.

CSS

<style type="text/css">
{literal}
body, label {font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
}
{/literal}
</style>

Javascript

In this example, the literal tags go around the Javascript.

{literal}
<script>

$(document).ready(function() {
$( "#email" ).click(function() {
  alert("Hey2");
   });

});

</script>
​{/literal}

Using Smarty {php}{/php} Tags

Smarty templating with PHP gives you more than one file for which you can add PHP code. The first, and obvious choice is to use code raw PHP code directly into the ‘.php’ file. However, you can code PHP into the template’s partnering ‘.tpl’ file.

Since Smarty 3.1, you must instantiate an instance of the SmartyBC class in order to be able to code PHP in the ‘.tpl’ file using the tags {php}{/php}. Essentially, your main file with the ‘.php’ will now have similar coding at the top of the file. The example snippet below shows that you will use the SmartyBC class instead of the default smarty class.

If you have done enough research, you may have read that it is not recommended to use {php}{/php} tags with the ‘.tpl’ file since the front end coder can now use them. In fact, it seems to defeat the purpose of using Smarty to begin with, which is to separate PHP coding from the design code.

.php File

 //include_once("libs/smarty.class.php"); //$smarty = new smarty();  // allow php tags in the tpl file require_once('libs/SmartyBC.class.php'); $smarty = new SmartyBC(); 

.tpl File

Now that you can use the {php}{/php} tags in the “.tpl” file, here is an example that prints “Hello World”.

 {php} echo "Hello World"; {/php} 

Starting a Service at Boot With Centos or Red Hat

The chkconfig command will allow you to start a service upon a boot or reboot. In most cases, it is very necessary to set this up properly so that everything will work as you want it to after a reboot. If it is not, services like Apache and mySQL will not start unless they are not instructed to do so.

With that said, the following simple set of steps can be used to start a service automatically when the Linux VPS or dedicated box is booted. The example will show how to add the service for checking, list its settings, make it start at boot time and remove it from starting at boot time.


To add the service to chkconfig,

 root# /sbin/chkconfig --add monit

To see if the service was added to chkconfig,

 root# /sbin/chkconfig --list monit monit           
0:off   1:off   2:off   3:off   4:off   5:off   6:off

To add the service to start upon boot,

 root# /sbin/chkconfig monit on

To check that the service was changed with chkconfig,

 root# /sbin/chkconfig --list monit monit           
0:off   1:off   2:on    3:on    4:on    5:on    6:off

Note: The values have for 2,3,4 and 5 are now on and this service will not run automatically upon a reboot. Those run levels of 2,3,4 and 5 are the relevant ones for the matter at at hand.

To remove the service from starting upon boot,

 root# /sbin/chkconfig monit off

How To Test PHP Applications With PHPUnit

PHPUnit is a testing framework that can be used to find coding errors and mistakes. On simpler level, you may have had some times when you have used echo, print and die() to track down errors and bugs in your code.

Although using these techniques can help you find problems, using PHPUnit can be applied to help find issues and problems with a much broader analysis. PHPUnit has many built-in methods that you can use to find problems. Then, you can run the command line to read its output. At this point, it will help pinpoint a target of concern.

If your company or testing platform can be accessed by various users, one coder could be writing the code while the lead developer could run tests with PHPUnit to find and fix the problems of the junior developer.

When you are testing with PHPUnit, your test file will need to make a class that extends the PHPUnit_Framework_TestCase class. An example is shown below.

class MyTest extends PHPUnit_Framework_TestCase
{ }


With that said, I will now show you how to install and use PHPUnit on Linux and windows. This tutorial is intended to help getting you setup and testing in no time at all. Since using and understanding PHPUnit can take some time to use effectively, you will probably want to move on to more documentation and perhaps further reading from books. 

Linux

The easiest method to use PHPUnit is to download the ‘.phar’ file and run it on your test file.

To download the phpunit.phar file,

wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar


After the file is downloaded, you can run it from any folder and on any test file. A very easy way to use it is to move it to the folder with the test file(s). Then, open that folder with the Linux terminal and run the command.

php phpunit.phar my_test.php
or
php phpunit.phar /var/www/test.php


Using Pear

sudo pear channel-discover pear.phpunit.de
sudo pear install -a phpunit/PHPUnit
whereis phpunit
/usr/bin/phpunit
username@username-VirtualBox:/usr/bin$ phpunit --version
PHPUnit 4.0.17 by Sebastian Bergmann


Windows 

To use PHPUnit on Windows, you only need to download the phpunit.phar file and move it into the PHP folder for your Wamp server. In this example, the file path is ‘C:\wamp\bin\php\php5.3.13’.

Then, the command is the same as described above for using Linux.

php phpunit.phar filname.php

 


A Few Tips

Typically, PHPUnit uses 1 file that will run checks on another file. You can use the require_once() function to include the file for testing. When you are testing classes, the file being tested will have a unique class name while the test file will use a class with the same name that will include the word Test at the end of it.

In the example below, the file for our application uses the class name ‘MyClassName’ while the testing file uses the class name ‘MyClassnameTest’.

Example Test File

<?php

require_once('FileToTest.php');

class MyClassnameTest extends PHPUnit_Framework_TestCase
{
  public function setUp(){ }
  public function tearDown(){ }

  public function testMyTestingIsValid()
  {
    // Make assertions here
  }
}
?>

Example File(FileToTest.php) and Its Class 

<?php
class MyClassname
{
public $variable = "Test";
    
  public function returnSampleObject()
  {
    return $this->variable;
  }
}
?>


When you PHPUnit, you will use built-in methods like:

public function setUp(){ }
and 
public function tearDown(){ }

On top of that, you may use one or more test methods such as;

public function testMyTestingIsValid(){}


Under normal OOP programming, these methods would not be used unless the method is called. The examples below show how the typical method is used.

$this->testMtTestingIsValid();
or
$my_new_object = new ClassName();
echo $my_new_object->testMtTestingIsValid();


But, with PHPUnit, all functions in your test file will run automatically if they have the keyword test in front of the function. So, a public method like testMyTestingIsValid() just runs and does the adequate checks on the file you included.

When you make a test, you will create an object from the class you are testing. Then, you can use assertion functions to test your results. Many assertions can be found at http://phpunit.de/manual/4.1/en/appendixes.assertions.html.


How To Test PHP Applications With PHPUnit

PHPUnit is a testing framework that can be used to find coding errors and mistakes. On simpler level, you may have had some times when you have used echo, print and die() to track down errors and bugs in your code.

Although using these techniques can help you find problems, using PHPUnit can be applied to help find issues and problems with a much broader analysis. PHPUnit has many built-in methods that you can use to find problems. Then, you can run the command line to read its output. At this point, it will help pinpoint a target of concern.

If your company or testing platform can be accessed by various users, one coder could be writing the code while the lead developer could run tests with PHPUnit to find and fix the problems of the junior developer.

When you are testing with PHPUnit, your test file will need to make a class that extends the PHPUnit_Framework_TestCase class. An example is shown below.

 class MyTest extends PHPUnit_Framework_TestCase { } 

With that said, I will now show you how to install and use PHPUnit on Linux and windows. This tutorial is intended to help getting you setup and testing in no time at all. Since using and understanding PHPUnit can take some time to use effectively, you will probably want to move on to more documentation and perhaps further reading from books. 

Linux

The easiest method to use PHPUnit is to download the ‘.phar’ file and run it on your test file.

To download the phpunit.phar file,

 wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar 

After the file is downloaded, you can run it from any folder and on any test file. A very easy way to use it is to move it to the folder with the test file(s). Then, open that folder with the Linux terminal and run the command.

 php phpunit.phar my_test.php or php phpunit.phar /var/www/test.php 

Using Pear

 sudo pear channel-discover pear.phpunit.de sudo pear install -a phpunit/PHPUnit 
 whereis phpunit /usr/bin/phpunit 
 username@username-VirtualBox:/usr/bin$ phpunit --version PHPUnit 4.0.17 by Sebastian Bergmann 

Windows 

To use PHPUnit on Windows, you only need to download the phpunit.phar file and move it into the PHP folder for your Wamp server. In this example, the file path is ‘C:\wamp\bin\php\php5.3.13’.

Then, the command is the same as described above for using Linux.

 php phpunit.phar filname.php 

 

A Few Tips

Typically, PHPUnit uses 1 file that will run checks on another file. You can use the require_once() function to include the file for testing. When you are testing classes, the file being tested will have a unique class name while the test file will use a class with the same name that will include the word Test at the end of it.

In the example below, the file for our application uses the class name ‘MyClassName’ while the testing file uses the class name ‘MyClassnameTest’.

Example Test File

 <?php  require_once('FileToTest.php');  class MyClassnameTest extends PHPUnit_Framework_TestCase {   public function setUp(){ }   public function tearDown(){ }    public function testMyTestingIsValid()   {     // Make assertions here   } } ?> 

Example File(FileToTest.php) and Its Class 

 <?php class MyClassname { public $variable = "Test";        public function returnSampleObject()   {     return $this->variable;   } } ?> 

When you PHPUnit, you will use built-in methods like:

 public function setUp(){ } and  public function tearDown(){ } 

On top of that, you may use one or more test methods such as;

 public function testMyTestingIsValid(){} 

Under normal OOP programming, these methods would not be used unless the method is called. The examples below show how the typical method is used.

 $this->testMtTestingIsValid(); or $my_new_object = new ClassName(); echo $my_new_object->testMtTestingIsValid(); 

But, with PHPUnit, all functions in your test file will run automatically if they have the keyword test in front of the function. So, a public method like testMyTestingIsValid() just runs and does the adequate checks on the file you included.

When you make a test, you will create an object from the class you are testing. Then, you can use assertion functions to test your results. Many assertions can be found at http://phpunit.de/manual/4.1/en/appendixes.assertions.html.


Install Joomla 3.3

Installing Joomla 3 can be simple. This tutorial shows the complete setup of Joomla 3.3.

1) Download Joomla from Joomla.org.
2) Extract the zip file and move the files and folders to your desired location.
3) Create a database. It can be any name you want.
4) Open the root folder for the website in your browser. You should see the installation instructions.

 

5)Setup the database.

 

6) Check over and select install.

 

Let it install

 

You should receive a successful image. If you have a problem, you can open the installation/sql/mysql/joomla.sql file in a text editor and do a search for ENGINE=InnoDB and replace it with ENGINE=MyIsam.

 

Here is the installed website at http://localhost.

 

Here is the administrator backend at localhost/administrator.

 

Do Not Allow Joomla Extensions To Be Installed For Joomla 1.5 -3.X

When you develop a website and allow a user to have Administrator or Super Administrator privileges, you may want to alter the back end so that Extensions cannot be installed at a later date. You may have various reasons for doing so. For one, an insecure or vulnerable extension can cause problems.

Therefore, not allowing extensions to be installed can remove that threat to the file system. In addition to removing the ability to install extensions, FTP or any other protocol to connect to the host should not be allowed to the client either. Many people do not take security seriously and just see the hosting as a free for all. Then, when something goes wrong, they blame you.

To remove the ability to install extensions ,

1) Open administrator/components/com_installer with FTP >Rename or folder or back it up on another device or path on the server.


To remove the installation from showing up in the menu for Joomla 1.5,

2) Open administrator/modules/mod_menu/helper.php and comment the following line
//$menu->addChild(new JMenuNode(JText::_(‘Install/Uninstall’), ‘index.php?option=com_installer’, ‘class:install’));


PHP CMS Website

When you begin a new web project using PHP(and likely mySQL), it makes real sense to use the right tool for the job. In this situation, the tool refers to the application that will be the heart of the project. Since the project at hand will be a CMS, I will exclude any PHP Framework like Symfony or Zend, and focus entirely on content management systems.

Now that the discussion has narrowed to a CMS, this can be split between open source, commercial and proprietary.

Open Source

In general terms, most open source content management systems(CMS) are free and include household names like WordPress, Joomla and Drupal. They are all very popular and can be used to create websites both large and small. If you plan to specialize and use one of them for multiple projects; you can become efficient with using them. However, you could find that they are not coded as lean as you would like and can actually cause more hours of work for smaller projects.

As time went on and my experience with these systems had passed, I began to notice many undesirable reasons for using these systems. For one, the web had too many bots that would hit or target these systems; before and after exploits had been exposed. Bots do slow a site down and many will hit urls that will update your database or send email to you from comments and registrations. You will have to make customizations to keep out the crap.

In addition to that, the filesystems were so huge and changed so frequently that they became a good hiding place for malicious files. In other words, if a malicious file could access a database or the filesystem, it could be hard to find in the rat’s nest of a large installation. At this point, you would have to monitor them yourself with custom scripts. So, when you receive the email from your ISP about a Joomla or WordPress exploit, your unforeseen workload could stare you right in the face. 

As a hand-coding PHP developer, I preferred to just code PHP and mySQL without having to create plugins and extensions. When one file could do the job, I could have ended up making four. I did not like doing more than I had to. 

Now, for something really undesirable. As time marches on, a CMS version will die and not have any more security updates. In addition to that, new PHP updates on the server will spring errors on pages since the CMS site could be using obsolete PHP functions. Now, there is some serious update work. For some, this could be a good resource to pull more dollars from the clients, while others will find this horribly inconvenient. Also, as versions are updated, old installed extensions and plugins could fail too.

Although the above spiel can sound a little negative, it is something to consider for the short and long run. If you plan to build a website with endless possibilities and so that your clients can update the website, you may want to go that course. If the website will not grow immensely and needs specific coding, you may want to go a custom route.

Although some performance specs had been mentioned above, you could always tune your server and use a strong caching system or a proxy like Varnish or Squid. Varnish will help to make a slow site very quick.

Finally, if you still plan to a CMS like WordPress or Joomla for your website, you could custom code PHP / mySQL. With WordPress, you can create a template file and add pure PHP / mySQL into that template. With Joomla, you could copy the source code from your web page and place it in a subfolder. Then, you could code anything you want into the ‘.php’ file.  

Commercial CMS

A commercial CMS is a product like Expression Engine. They cost a few dollars and come with support. Some can cost under $100 and some run over $10,000.

Proprietary CMS

A proprietary CMS is an in-house coded CMS that is used by a company. It can take quite some time to code, but it can have many advantages such as performance, faster completion times and allows you to code within your desired style. By contrary, an open source CMS will have its own methods for customizations and you would need to work within these limits.

From experience, I was lead to the path of creating a custom proprietary CMS since I wanted much better performance and a system that could build a web page in record time, and be easier for a client to use. In addition to that, I wanted to be able to move an HTML / CSS / JS website into a CMS very quickly. Since CMS’ like WordPress and Joomla were my previous systems of choice, I would make sure that the results I wanted would be much simpler with an in-house solution.


Making Custom Header and Footer Files With Smarty Templating

When you code small or larger web applications and websites from scratch, one of the first things you do is create a custom header and footer file. In addition to that, you could create a custom sidebar as well. The custom files allow you to eliminate redundancy since your single header and footer file will be displayed on each and every page. So, if you decided to add a page on the main menu, you simply add it to the header file.

Making these files with Smarty is very simple. For starters, let’s assume you already have a single logic(.php) and a single presentation(.tpl) file which dispalys the entire web page. At this point, you will still use both files. But, you will need to create the new header and footer file. Both of these files will use the (.tpl) extension. Now, all you have to do call the display() method within the logic file in order to display the custom header and footer.

The code snippet below comes from the bottom of the logical file called main.php. This code can be added to any new page for which you will want to resuse the same header and footer file. The includes directory was created inside the root folder for the website.

 $smarty->display("includes/header.inc.tpl"); //display output $smarty->display("main.tpl"); //display output $smarty->display("includes/footer.inc.tpl"); //display output 

The ‘includes’ folder can also be used for functions and classes. Or, you could make and use any folders for which you find neat and tidy, or necessary based on the complexity of the application. For example, one person may only want the includes folder, while another would have an includes, functions and classes folder.


Arrays With Smarty Templating

When you use Smarty templates, you could be hard coding or retrieving arrays from a database query. In most situations, your logic ‘.php’ file will create the arrays and the ‘.tpl’ file will be used for presenting the arrays within HTML. The easiest way to show how this can be done is to show you a sample ‘.php. file and a ‘.tpl’ file.

The example uses 4 arrays; $leads, $myarray, $myarray1, $myarray2 and $myarray3. After all arrays have been created, they are assigned Smarty template variables. This must be done or the ‘.tpl’ file cannot use them. Once they are assigned, the display() method calls the ‘.tpl’.

Since the variables can now be used with the ‘.tpl’ file, several foreach loops are created for each array. As you code and test the examples, you will gain some methods for which you can display arrays in foreach loops.

Logic(.php file)

require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();

$leads = array("John","Paul","George");

$myarray = array("key" => "Blue Jays", "key2"=> "Giants", "key3" => "Rangers");
$myarray2 = array("Blue Jays", "Giants", "Rangers");
$myarray3 = Array(Array ( "id" => "1", 
    "lastname" => "Smith", "firstname" => "John", "email" => "js@example.com", "phone" => "5555666" , "subject" => "A", "notes" => "Lots", "date" => "2012-01-01" ), Array( "id" => "2", 
    "lastname" => "Jones", "firstname" => "Paul", "email" => "paul@example.com", "phone" => "5555555" , "subject" => "B", "notes" => "None", "date" => "2012-01-02" ));

$smarty->assign("leads",$leads); 
$smarty->assign("myarray",$myarray); 
$smarty->assign("myarray2",$myarray2); 
$smarty->assign("myarray3",$myarray3); 
$smarty->display("smarty.tpl"); //compile and display output


Presentation (.tpl file)

{foreach item=lead from=$leads}
<div style="width:40%;">
<strong>Profile of {$lead}</strong>

</div>

{/foreach}
<br/>
{foreach from=$myarray key="key" item="value"}
<div style="width:40%;">
<strong>Item is {$key}{$value}</strong>

</div>

{/foreach}
<br/>
{foreach from=$myarray2 key="key" item="value"}
<div style="width:40%;">
<strong>Item is {$key}{$value}</strong>

</div>

{/foreach}


Browser Output

Profile of John
Profile of Paul
Profile of George

Item is keyBlue Jays
Item is key2Giants
Item is key3Rangers

Item is 0Blue Jays
Item is 1Giants
Item is 2Rangers

Profile of John Smith
First Name:     John
Last Name:     Smith
Phone:     5555666
Email:     js@example.com

Profile of Paul Jones
First Name:     Paul
Last Name:     Jones
Phone:     5555555
Email:     paul@example.com

 

Sqlite or mySQL

Sqlite and MYSQL are two excellent options for your next database. Although the two do more or less the same thing such as select, update, insert and delete data from a database, they each have commands that are unique and portability differences. I will get to the command details later.

For now, I would like to focus on portability because it makes a huge difference. In fact, the portability makes an Sqlite database as a great option for both Android apps and web applications.

Android App

For example, you could create an app for Google Play that uses an Sqlite database. This means, the client can download your app and use the database on their phone. Although a mySQL database can connect to a host from a mobile web page, using an Sqlite database is obviously the way to go for an Android app.

Web Applications

If you want to create a web application that will deal with many users and plenty of traffic, mySQL would likely be an option you would consider. But, if you want to make a micro application that can be easily downloaded and used quickly by the client, an Sqlite database makes this possible.

Usage

This section will detail the usage for using Sqlite and mySQL. It will focus on writing code that is compatible for both databases and expanding on some slight differences. From a PHP scripting point of view, you can easily write the same queries for both, as long as you use PDO.

The main differences in usage will be at the command line. Although the select, update, insert and delete statements will be the same, the other commands like using a database and showing tables will be different.

Below, are examples of statements that could be used in a PHP script that connects to a mySQL or Sqlite database.

Connect to Database

   function connect()
{
    global $dbh;
    $user = 'root';
    $pass = "password";

    // MYSQL CONNECT
    //$dbh = new PDO('mysql:host=localhost;dbname=mydatabase', $user, $pass);

    // SQLITE CONNECT
    $dbh = new PDO('sqlite:db/mydatabase.sqlite');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    return $dbh;
}


Select

   $command = $dbh->prepare("SELECT * FROM tablename");
    $command->execute();
    $result = $command->fetchAll();
    
	foreach ($result as $row) {
	$my_array[] = $row;
	}

Update

 $command = "UPDATE tablename SET var1=:var1, var2=:var2, var3=:var3 WHERE id=:id";
    $command2 = $dbh->prepare($command);
    $command2->bindParam(':var1', $var1);
    $command2->bindParam(':var2', $var2);
    $command2->bindParam(':var3', $var3);
    $command2->bindParam(':id', $id);
    $command2->execute();


Insert

    $command = "INSERT INTO tablename VALUES (NULL,:id, now())";
    $command1 = $dbh->prepare($command);
    $command1->bindParam(':id', $id);
    $command1->execute();

Smarty Template(s) With PHP

The Smarty Template engine is a library that PHP programmers can use so that they can separate logic from design. This quick Smarty tutorial should help minimize the confusion while you try to grasp the methods for using Smarty.

Why Separate Logic From Design?

Although separating logic from design has many benefits, one of the main benefits is that a project or page can be split between different individuals. In a workplace setting, you often have a front end web developer or web designer that will alter the ‘look’ of the website. Therefore, it makes that person’s job easier if he only edits and tests the design and avoids any data between Smarty’s {} tags.

Meanwhile, the web developer will write and alter the code that is displayed in the logic file with the ‘.php’ extension. Now, both can do their work at the same time without worrying about who is working on the file. Obviously, if both the heavy lifting backend developer and front end designer need to use the same file, there could be issues like overwriting and losing work. Simply speaking, two people on one file is not efficient, especially is both people want to work on it at the same time.

Asides from Smarty being convenient and friendly between logical and design users, it can also help maintain control of an application from a temporary front end web designer. For example, if you plan to work primarily as a web developer and outsource the design to a stranger or part time worker, you may not want the designer to have access to all the logical code and heart of the page. This way, the designer’s code is rather useless for other projects based on the current scripting.

All in all, the outsourced individual could not sabotage or steal a project; especially if he only has write access or an upload privilege on the exact design files you had contracted him to work on.

Since the spiel mentioned above explains why Smarty is beneficial, you may already be thinking when using Smarty could be overkill. Essentially, if one individual will be creating and maintaining a small PHP project, it could be much quicker to use only one file for the logic and presentation. At this point, it could be a matter of preference since one person may like minimize the files while another would like to work with two smaller files with the logic in one file and the presentation in the other file.

The Basics

To make this sound easy, I will try to explain a traditional PHP file vs using a Smarty template. A PHP file allows you to code PHP, HTML, CSS, javascript, Jquery all in one file that has the ‘.php’ extension.

Smarty, on the other hand, is used with a pair of files; a ‘.php’ file which includes the Smarty library and PHP coding and a matching ‘.tpl’ file which contains the html(and other coding like Jquery).

To keep things simple, the ‘.php’ and ‘.tpl’ files can have a matching name so it is easy to know which files belong to which without having to find the line that references the ‘.tpl’ file within the ‘.php’ file. Make sense? The ‘.tpl’ file that is used and compiled is done with the $smarty->display() method. For example, the logical PHP file called filename.php could use the filename.tpl file for output.

 $smarty->display("filename.tpl");


Getting Started

To be able to use Smarty, you follow a few steps.

1) Download and unzip the file from Smarty.net.
2) Moves the files into your root folder or somewhere else on your server and write the path in your .php.ini file or in your files which will use Smarty.

The first method can be done in less than a minute. All you need to do is extract the download and move the libs folder into the location where you will create your working files. Often, this is in the public_html or example.com folder. The second method can keep the library in a more secure place; such as the /usr/local/lib/php folder.

The second method also allows all hosted domain names to have access to the library which eliminates redundant installations. The example below shows how to setup Smarty on Linux so all domains can use it.

 root# cd /usr/local/lib/php root# wget smarty.net/files/Smarty-3.1.18.tar.gz root# tar xvfz Smarty-3.1.18.tar.gz root# cp -r Smarty-3.1.18/libs/* /usr/local/lib/php/smarty root# rm -R Smarty-3.1.18

3) Create a .php file and instantiate the Smarty object.

require_once("libs/smarty.class.php"); 
$smarty = new Smarty ();

If you plan to access Smarty from /usr/local/lib/php/Smarty you will need to add an extra line into the ‘.php’ file to create a constant that points to the path and you need to alter the require_once() function so it access the Smarty class from the adequate directory.

define('SMARTY_DIR', '/usr/local/lib/php/smarty/'); require_once(SMARTY_DIR . 'Smarty.class.php'); 
$smarty = new Smarty ();

Alternatively, you could also use the simple coding shown below.

require_once('/usr/local/lib/php/smarty/'); 
$smarty = new Smarty ();


Beyond The File Pairing

When the PHP file is requested in the browser, the ‘.tpl’ file is compiled and output. Although they are two different files, the key to working with them is to remember that all variables in the ‘.php’ file can be assigned and passed into the ‘.tpl’ file. In addition to that, you should note that any code passed into the ‘.tpl’ can be interpreted with… let’s say Smarty coding. I will make a quick list below which shows how some php code from the ‘.php’ file can be interpreted with the ‘.tpl’ file.

Setting a Variable With Logic and Output To Presentation

Variable (index.php)

$my_string = "Here is my string."; 
$smarty->assign("my_string",$my_string);

Variable Output (index.tpl)

 <p>{$my_string}</p>


Where To Go From Here

From the simple examples shown above, you can now use Smarty and display simple variables in the presentation file which contains the ‘.tpl’ extension. If I could sum up how to use Smarty from here on, I will attempt to do so in 1 sentence.

Variables, loops, objects and functions can be used within the ‘.tpl’ file with special syntax; often nested within curly{} brackets. I will attempt to elaborate on the one-liner. If you made an array called $myarray within the ‘.php’ file, you could run it through a foreach loop within the ‘.tpl’ file.


Foreach Loop (index.tpl)

{foreach item=myitem from=$myarray} 
<p> {$myitem} </p> 
{/foreach}

Calling a Function

The example below shows how to call a function and return a value. Functions called with the ‘.tpl’ are not cached. For simple practice, doing all logic code in the ‘.php’ file and only outputting in the ‘.tpl’ files makes using Smarty very simple and organized.
Functions file (my_functions.php)

function smarty_insert_my_function() 
{ 
return "This is returned from the function"; 
}


index.tpl

 {insert name="my_function" assign="my_returned_value" script="my_functions.php"} <p>{$my_returned_value}</p> </body>

Built-in PHP Functions

Smarty allows you to use built-in functions within the ‘.tpl’ file. There are many so I will not go into the details. But, I will show an eaxmple of the ‘.php file and ‘.tpl’ file changing the string to lower case letters.

 .php $string = "AbCdE"; $string = strtolower($string); //ouputs abcde
 .tpl {$string|lower}

More examples can be found at http://www.smarty.net/docs/en/language.modifiers.tpl

Extras To Get You Going

Two important factors worthy of consideration when using Smarty are its built-in functions. Although there are many, two which deserve utmost attention are {php} and {literal}.

The PHP tags {PHP}{/PHP} allows you to write good, old PHP within a the ‘.tpl’ file, while code within {literal}{/literal} will not be translated and that allows you to write plain, old HTML, Javascript and CSS within these tags. More important functions can be found at http://www.smarty.net/docs/en/language.function.php.tpl.

More Examples

The tutorial above can be used as a simple cheatsheet for using Smarty. The next set of examples are more tutorials regarding its usage.

1. Different Arrays and Foreach Loops With Smarty
2. Custom Smarty Header and Footer Files
3. Using PHP Inside “.tpl” file
4. Using CSS and Javascript Within TPL Files Using Literal tags
5. Smarty Forms and Elements
6. Object Oriented Programming With Smarty
7. Smarty Limiting File Access
8. Smarty Template Configuration Files
9. Using Functions
10. Include Files


Learning Python For PHP Programmers

As an individual that spends the majority of time programming PHP / mySQL, I had wanted to see what all of the Python hype was about. I have heard so many positive remarks about it for custom scripts and web programming.

However, the main reason that put it on my list for learning was the Raspberry Pi. Since python has a GPIO library, it was a great tool for taking input and delivering output with the Raspberry Pi. In fact, any tutorial I can remember that would do this used Python and the GPIO library.

Shortly after I decided to learn C, I decided to dive into Python. So, there I was, using Gedit and running code blocks on Ubuntu. Immediately, I was impressed with its lean and clean presentation.

Coming from a PHP background, I will attempt to summarize the differences I experienced.

  • Does not use $ to declare strings
  • The lines do not end with a semi-colon (;)
  • Printing is a lot like C or sprintf with PHP
  • You import libraries you need at the top of the file
  • The syntax for arrays is different. Also, the author called an array a ‘list’
  • The loop syntax is different. This should be easy to interpret; especially if you run a code sample.
  • Curly brackets {} are not used in loops, functions, classes
  • Using methods from libraries is very similar to using Jquery

If you have fairly strong PHP skills, you will find you can convert to a Python mindset rather easy. Even though I like Python’s simple, clean syntax, I do not plan throw away everything I have done with PHP. In fact, I would continue with PHP for web applications since I have been hand coding it for a long time and its usages makes coding a dynamic website very quick and easy. But, a new programmer could easily become efficient with Python.

However, if I ever plan to integrate a Raspberry Pi into a web page on a remote server, I would not hesitate to take advantage of its GPIO library and its ability to read or write to files or a database. This allows for many more possibilities to the creation of dynamic websites.


Learning C For PHP Programmers

PHP / mySQL programmers may spend most of their time using languages that contribute to the web application. In general, this could include PHP, mySQl, Javascript(Jquery), HTML and CSS. Although these languages detail the users experience, the PHP programmer could reach a point where he would like to program with the language for which the hosting machine was created. For Linux users, that would mean C.

After one develops a keen interest with Linux and the command line tools like bash, Sed and Awk, it could be natural progression to learn C.  After all, Apache and varnish were written in C. I found this the case.

Meanwhile, university students often learn C and C++ to build the strong foundation for learning other languages and it should come as no surprise why many employers seek those programmers with these skills. When I decided to learn C, I had several years with other languages like PHP, SQL and CSS. and a 775 page book about programming.

So, there I was diving into C to learn this language. After all, I had a little spare time to do this and focus on the language. Although knowing other languages and toying around with others helped in the understanding, there was some very distinct concepts and features that were new. However, many of the new concepts were minor adjustments to the base knowledge.

When going from PHP to C, many of the details were declaring variables before using them, structures, pointers, compiling code, printing text(more similar to sprintf with PHP), different loop syntax, importing C libraries, different commenting, different variable syntax and actually assigning real memory values to strings, arrays, etc. I may have left some more details out, but, the previous examples have left a string impression.

After a strong week of comittment, coding and compiling, it was well worth it. Not only was it beneficial to be able to create and have a better understanding to those C programs that will be edited, but, it helped fill in many of the holes for reading Java and Python too.


Web Development Skills

The definition for a web developer is rather broad and the skills needed to become a web developer can be very, very diverse too. Nevertheless, I will attempt to explain the skills that could be implemented by a web developer.

Please note that larger companies often hire specific people to do various coding and graphic design for a website. Therefore, defining this term ‘web developer’ can be a little more difficult. But, if the company is a freelance web developer, it can be more easily to define since one person would oversee and maintain the projects. Since a web developer will be doing and managing all entire projects, the developer is often referred to as a ‘Full Stack Web Developer’.

For the remainder of the article, the description for a web developer will be related to one freelance web developer who maintains all the websites.

Web Developer Skills
 


Introducing Typical Progression For a Web Developer

Normally, a future web developer starts off by making basic static websites with html code. Then, other client side languages like Javascript and Jquery are introduced. After that, making dynamic websites with a server side language like PHP and a database like mySQL is implememted and PHP / mySQL is used. However, some people actually build a website based on these languages using a tool like WordPress, but, they have no idea about the code under the hood. Not having a deeper understanding will cause big limitations for building custom websites.

Once a person has strong skills with the coding previously described, he may move on to knowing more about the system where the files are stored. More often than not, that is a Linux distribution. Knowing how to navigate the file system and commanding it will really help a web developer.

Apart from the website, a web developer may want to have the ability to create mobile applications for Android and the iphone. in addition, custom apps for other web sites like Facebook could be added to the toolkit too. 

For the next level, knowing a low or medium level compiling language like C can make it easy to edit and create custom Linux packages. The next section will detail the steps of progression.

The stages of progression to be able to code secure applications and edit and run the Linux system can take a while. However, persistence and a strong desire to be able to have a large array of web development tools will help make the journey an enjoyable process.

On top of all of the code and systems that will be used, a web developer will need to be able to analyze content, SEO and Google Adwords accounts. Traffic is always important and it is an ongoing procedure. There are many tools that will help the web developer analyze and deliver the desired results. 

The rest of this article will go into more detail onto the topics that had been previously mentioned. 

Web Development Skills 

Website Coding Skills

On a basic level, a web developer should have the skills to create and maintain a database driven website. This would include knowledge of the file system and all coding for the website. For example, a website could contain PHP , mySQL, Html5, CSS, XML, Javascript and JQuery.

Meanwhile, another web developer could maintain a similar website but that person uses ASP, MSSQL, Html5, CSS, XML, Javascript and Jquery. As you can see, the main differences here are the scripting language and database. 

Asides from the actual languages, there are many programmed applications that have graphical user interfaces and you may want to become familiar with them. For example, content management systems like Joomla, WordPress and Joomla and shopping carts like Magento and Prestashop use PHP , mySQL, html and css; but you actually create pages with a ‘point and click’ system. Then, you may dig into the source code for web pages and make alterations. Therefore, using these systems efficiently can be important to completing projects quickly.

Beyond The Website

Email

After there are websites, you often have the need to create and modify email accounts. An email server will run on the hosting accounts and it will be used so that people can send and receive email from the website address.

Traffic Analysis

Once websites have been built, the web developer can use tools that analyze visitor log files (ie Awstats) or add Javascript to the website files to monitor traffic with Google Analytics. Google Analytics can allow you to view where the visitors came from, what pages are being viewed and much more.

Google Web Master Tools

Google Webmaster Tools is very valuable for users to view their impressions from organic traffic and upload sitemaps for the websites. It also has many other useful tools like ‘Fetch as Bot’ so you can see what the Google bot receives when it hits your web pages. Spam can be injected into pages and this tool can let you know if Google is receiving clean pages. Also, there are tools to check for infected pages too.

Google Adwords

Using Google Adwords can be used to bring in desired traffic and help find beneficial paid and organic keywords. Many large companies gain most of their revenue from this service.

Coding Beyond The Website

As times goes forward, it is very likely your skills will too. So, if you acquire significant traffic to your website, or find a need for which you need a custom web server setup, there will probably come a day when you will need to migrate from a shared or cloud host to a VPS or dedicated server. When this happens, your whole world as you knew it could change since you will have root access to the Linux operating system and will need to take care of this system. If you don’t want to care for the operating system, you will need to pay someone to do that for you.

With that said, having Linux System Administrator skills will mean that you will like need a decent skillset with Bash, Sed, Awk and knowledge of the Linux file system. There are courses that will teach these skills.

On top of that, you may come to a point where you will be regularly editing installed Linux packages like the Apache server and Varnish. Like a lot of Linux packages and system files, they are written in C. So, learning C would not hurt as well. If you have a fairly strong background with PHP or Perl, you will find editing C files sort of straight forward. In addition, learning C will give the deeper understanding to your Unix based operating system too.

If you want to create your own C programs and packages for Linux, building them with C is an option. After you build and compile them, you can run them like any other package.

Conclusion

As you see, the toolbox for a web developer can be rather broad. You may find a person calling himself a web developer that builds basic web pages with html / css that are stored on a shared host, or you could find one that has a more well rounded skillset using the LAMP(Linux, Apache, mySQL and PHP) stack.


Fix Hacked Joomla Website

Although Joomla can be a convenient platform to develop websites, it can be a rats nest to fix after code had been injected into your website. For this reason, it is often easiest to start over, rather than chasing after the files which are doing the damage.

In a nutshell, the procedure to fix a hacked Joomla website is shown below.

1) Back up all files and database.

2) Install a fresh Joomla package.

3) Use the original or create a new database.

4) Dump the data from the old database to the new database.

5) FTP the old template folders into the new installation. Before doing so, it is a good idea to check over all of the code and look for strange files or code blocks.

6) Reinstall the extensions you need.

The excessive file system which is used by Joomla and other content management systems is one reason why it can be better to hand code applications and websites.

If you have a high performance website that uses limited files, it is much easier to track down malicious code. With Joomla, it can be rather easy to disguise blocks of code and backdoor scripts; especially if the website owner is uncertain about secure coding practices.

Varnish Cache Set Up and Usage With Centos

Varnish an http accelerator that can be installed on any Linux distro. Varnish allows your website files to be pulled from the cache if they exist. If the files do not exist, Apache, mySQL and PHP do their regular requests and load the files into the browser.

Although Varnish seems like the ultimate caching system, becoming familiar with its configurations, logging and commands can be quite a committment; especially if you run multiple dynamic websites and applications like Joomla, WordPress, Magento and custom php / mySQL scripts. However, asides from getting around those details, it kicks butt. You could see that slow loading Joomla or Drupal site loading as if it is plain html / css static files from a dedicated server. Once you see how well it performs, you probably never want to go back; unless you have some web applications that you absolutely don’t want to cache.

Installing Varnish on Centos

root# yum install varnish


Configuring Varnish

After you have installed Varnish, there are two main configuration files that you will edit; ‘/etc/varnish/default.vcl’ and ‘/etc/sysconfig/varnish’. The former file would take up most of your time, while the latter file may be rarely edited. The file ‘/etc/sysconfig/varnish’ is where you set varnish to cache to memory or disk, set the cache size, set the port for Varnish to listen on, and set the Varnish admin port. By default, many of these settings are usable. But, you will probably want to make adjustments. A lot of tips for Varnish can be found here https://www.varnish-cache.org/docs/trunk/tutorial/putting_varnish_on_port_80.html.

The other file, ‘default.vcl’ can end up getting very long and specialized. When you use the default.vcl file, you will want to make entries for every ip that is used on your server. You will also make very specific caching rules. Some examples are shown below.

The first major change that takes place is changing Apache’s default port 80 to something else which is usable.

Ip Address setup

The backends and acl will vary from server to server. Here is an example below. Another example can be found at https://gist.github.com/jeremyjbowers/1542949

backend default {
  .host = "ip#1";
  .port = "<apache new port number>";
}
backend default2 {
  .host = "ip#2";
  .port = "<apache new port number>";
}
backend default3 {
  .host = "ip#3";
  .port = "<apache new port number>";
}


 acl afirst_ip_quad_block {
"ip#1";
}
acl asecond_ip_quad_block {
"ip#2";
}
 acl athird_ip_quad_block {
"ip#3";
}

Customizations

The example below allows PHP to grab an ip with the variable $_SERVER[‘HTTP_X_FORWARDED_FOR’]. By default it is $_SERVER[‘REMOTE_ADDR’].

As a general rule, all conditions that are set in the sub vcl_recv {} and vcl_fetch() blocks. You will do most of the changes here. A good method for changing the default.vcl file is to back it up and reload it with the ‘/etc/init.d varnish reload’ command or restart varnish with ‘/etc/init.d/varnish restart’.

sub vcl_recv {
remove req.http.X-Forwarded-For;
set req.http.X-Forwarded-For = client.ip;
if (server.ip ~ afirst_ip_quad_block) {
set req.backend = default;
#return(lookup);
}


Unset a cookie and cache all images with the given extensions

if(req.http.host ~ "^(www\.)?example\.com" &&  req.url ~ "\.(jpg|jpeg|png|gif|css|js)$" ) {
unset req.http.cookie;
set req.backend = default2;
}


Do Not Cache Certain Pages

elsif (req.http.host ~ "^(www\.)?example\.com" && (req.url ~ "^/member\.php" ||
      req.url ~ "^/signup\.php" ||
      req.url ~ "^/newsletter\.php"
    )) 
{
#     return(pass);
#remove req.http.cookie;
   }

Testing Varnish

With varnish, you can set custom headers and test to see if it hits or misses. A good example can be found at https://www.varnish-cache.org/trac/wiki/VCLExampleHitMissHeader.

After you have added this block, you can use Firebug with Firefox or use the network tab after inspecting the element with Google Chrome. Now, you can see the new headers and examine the hits, misses and amount of hits from the cache for that page.

Rebooting Varnish Script

The script below can be set as a cron job to restart Varnish at your desired internal.

#!/bin/bash

# Check if gedit is running
if ps aux | pgrep varnish >/dev/null 2>&1
then
    echo "Running"
else
    #echo "Stopped"
        /etc/init.d/varnish start
fi


Monitoring Varnish

You can check the activity of Varnish using the ‘varnishstat’, ‘varnishncsa’ and ‘varnishlog’. After seeing these, you can see visitors logs and see how well it caches. Once the ‘varnishncsa’ process is running, you can also write its output to your own custom log file. The command for that is varnishncsa -a -w /var/log/varnish/access.log. You can check the logrotate settings in ‘/etc/logrotate.d/varnish’ to make sure it creates rotated logs.

If you want to make sure Varnish stays up and running, you can use a service like Monit or Munit to monitor its process and make sure it goes up if somehow is not running.

Working With Varnish

If you have many websites and domains, you may find that you will edit files and want them refreshed. In order to do this with varnish, you will continually need to flush the cache for a specific url while you are conducting web maintenance.

The first line below would clear the entire cache for example.com. the second line would only remove the ‘.jpg’ files from the cache.

root# varnishadm "ban req.http.host ~ example.com"
root# varnishadm "ban req.http.host ~ example.com && req.url ~ .jpg"



Monitoring Apache and MYSQL With Monit Using Centos

Monit is a linux package that can be used to monitor and restart processes automatically if they go down. This brief article will explain how to install and configure Monit.


Installing Monit

 root# yum install monit 

Now that you have installed Monit, the fun begins. The main files you will access and configure are the main configuation file located at /etc/monit.conf and its log file located at /var/log/monit. All editing will take place with configuration file while the log files will show you what it has been doing and can be used for troubleshooting. 

Configuring Monit

The main configuration file is located at ‘/etc/monit.conf’. You can open it in your desired editor like Vi or Nano. A shortened configuration file is shown below. This file only checks for the Apache and mySQL services. More often than not, one of these two services would be the likely culprit that brings down your website(s). Take a look at the configuration file. After the file, there is a description about ‘how it works’. When you make any changes to the monit.conf file, you need to reload the configuration file with the ‘reload monit‘ command or restart it with the ‘/etc/init.d/monit restart‘ command.

 root# vi /etc/monit.conf 
## Start monit in the background (run as a daemon) and check services at
## 2-minute intervals.
#
set daemon  120
#
#
## Set syslog logging with the ‘daemon’ facility. If the FACILITY option is
## omitted, monit will use ‘user’ facility by default. If you want to log to
## a stand alone log file instead, specify the path to a log file
#
set logfile syslog facility log_daemon
#
#
###############################################################################
## Services
###############################################################################
#
#
  check file apache_bin with path /usr/local/apache/bin/httpd
    if failed checksum and
       expect the sum 8f7f419955cefa0b38a2ba316cba3657 then unmonitor
    if failed permission 755 then unmonitor
    if failed uid root then unmonitor
    if failed gid root then unmonitor
#    alert security@foo.bar on {
#           checksum, permission, uid, gid, unmonitor
#        } with the mail-format { subject: Alarm! }
    group nobody
#
#
## Check that a process is running, in this case Apache, and that it respond
## to HTTP and HTTPS requests. Check its resource usage such as cpu and memory,
## and number of children. If the process is not running, monit will restart
## it by default. In case the service was restarted very often and the
## problem remains, it is possible to disable monitoring using the TIMEOUT
## statement. This service depends on another service (apache_bin) which
## is defined above.
#
  check process apache with pidfile /var/run/httpd.pid
    group apache
    start program = “/scripts/restartsrv httpd”
    stop program  = “/scripts/restartsrv httpd”
    #restart = “/etc/init.d/httpd restart”
    #if cpu > 60% for 2 cycles then alert
    #if cpu > 80% for 5 cycles then restart
    #if totalmem > 200.0 MB for 5 cycles then restart
    #if children > 250 then restart
    #if loadavg(5min) greater than 10 for 8 cycles then stop
    if failed host 127.0.0.1 port 80 protocol http
       then restart
    #if failed port 443 type tcpssl protocol http
    #   with timeout 15 seconds
    #   then restart
    if 5 restarts within 5 cycles then timeout
    #depends on apache_bin
   group nobody
#
#
check process mysqld with pidfile /var/lib/mysql/vps.example.com.pid
#group database
start program = “/etc/init.d/mysql start”
stop program = “/etc/init.d/mysql stop”
if failed host 127.0.0.1 port 3306 then restart
if 5 restarts within 5 cycles then timeout
#
#
###############################################################################
## Includes
###############################################################################
##
## It is possible to include additional configuration parts from other files or
## directories.
#
#  include /etc/monit.d/*
#
#

# set daemon mode timeout to 1 minute
# set daemon 60
# Include all files from /etc/monit.d/
include /etc/monit.d/*

How It Works
Okay, the above code shows 2 blocks for Apache and one for mySQL. Too keep it simple, Monit looks for the adequate process ids for the Apache and mySQL services on your server every 2 minutes. If it does not find them, the service(s) are restarted.

Connecting To mySQL Using PDO

Although there are several methods you can use to connect to a mySQL database, the PDO(PHP Data Objects) method is a very good technique. For one, it is universal and can be used with Sqlite databases since it does not use any commands specific to mySQL. In addition to being universal, you can use PDO prepared statements to avoid the need to escape mySQL strings since bindParam method can do that for you.

Below is a simple example that shows how to connect to the database and make an insert statement. Other mySQL commands like Select, Update and Delete can be used by replacing the command that is shown below.

$user = '<username>';
$pass = "<add_password_here>";
$dbh = new PDO('mysql:host=localhost;dbname=username_database', $user, $pass);


$emailaddr = $_POST['email'];


$command = "INSERT INTO clients (id,email,date2) VALUES (NULL, :email, now())";
$command2 = $dbh->prepare($command);

//$command2->bindParam(':id', $myid);
$command2->bindParam(':email', $emailaddr);
//$command2->bindParam(':date2', $mydate);
$command2->execute();

//or

/*
$command2->execute(array(
    ':id'    => $myid,
    ':email' => $emailaddr,
    ':date2' => $mydate
));*/


Hosting a Website With Virtualbox

Virtualbox makes it easy to host a website on your virtual machine. This tutorial will discuss the basic setup. It assumes you have already installed the usual Linux, Apache, PHP and mySQL. If you need help with that, please check out the page here.

Hosting at home can be easily done if you set the DNS to point to your IP address assigned by your Internet Service Provider. 

After you have set the DNS, you need to run two wireless connections from your host pc. By doing this, your router will assign two local network IPs; one for each wireless connection. Note that you will want your host machine to use both wireless connections.

Now, you need to alter the settings with your Virtualbox guest machine so that it connects with one of the wireless adapters. In this case, you will use the Bridged Adapter. By default, the network adapter is set to ‘NAT’, which means it would use the same ip as your host pc. The setup is shown below.

 

After you have made the changes, you can boot your virtual machine. Meanwhile, you can allow port forwarding for port 80 on your router to be set to the IP address that is used by the virtual machine. You router will show its connections and you should easily find the ip for your wireless(or wired) connection. When you do find it, make sure to allow port 80 to be forwarded for that ip address.

After you have set the port forwarding, you should easily be able to access the website with http://<myipaddress>.com or http://example.com.

Using this method is an easy and quick method to host private web applications on your local virtual machine.


Mac Address and Linux Live

When you connect to the Internet with a Live CD or Live USB, your connection to your router will create its own network ip address and use the mac address based on the hardware that is used to make the wifi connection. For example, after booting Live Ubuntu, Live Kali, or another Live Linux distro, you will make an Internet connection. If you use a wifi dongle to make the Internet connection, your router will use that as the mac address for your machine. Meanwhile, if you used the built in wifi network adapter, the mac address would be something else.

To test this for yourself, you can connect a second wifi dongle and boot your Linux live distro. Then, connect to the internet with either of your network adapters. Now, open a browser and login to the router. You should be able to see the ip address and mac address for your pc. Now, disconnect from the network adapter and connect with the other one. Now, you will see a new ip address and mac address for this connection.


Virtual Machine With Its Own Network IP and Mac Address

Virtual machines have various means for which they can connect to the Internet. This lesson will discuss how Virtualbox can be used to connect to the router with its own IP address and mac address.

By default, a virtual machine connects to the Internet with NAT. This will allow you to connect through the same IP address as your host pc, although Virtualbox technically uses the Ethernet connection to make this happen. Essentially, if you browse the Internet and use your Virtual machine to do so, you will use the same IP address and mac address as the host machine.

But, what if I want to have my own network IP address and mac address for my Virtual machine? Well, if you want your Virtual Machine to act like a stand alone computer on the network you will need to alter two settings from the Network settings.

One setting is to change the setting ‘NAT’ to ‘Bridged Adapter’.

The second setting is a little more involved since it requires the usage of a second Wireless Internet card. You can pick up a wifi dongle for about $5-10 on Ebay(or ~$15 in a store). Once you have the dongle, you may have to install software and do a system reboot. Alternatively, it could be plug and play. Once your pc reads the new wireless device, you can connect to the Internet with either of the two wireless connections. 

So, if you want to connect your Virtual machine to the Internet with the wifi dongle, you select it. Now, when you run your Virtual machine, it will use the mac address of the wifi dongle.

You should note that when you look at your mac address with the ‘ifconfig’ command with your Virtual machine, it will be the one that is listed in the network. It will not be the same mac address as the wifi dongle. But, the router will use the mac address of the wifi dongle.


Secure PHP Website

Wow. The question is where to start and how to finish this instructive article. Okay, I will take a deep breath and make an attempt to cover many important concepts about PHP Security. Although there are many factors to consider, I always believe that reading about this subject from credible authors is a good place to start.

Books like ‘Essential PHP Security’ and ‘Pro PHP Security’ will give you some insight into security and they could even help more experienced programmers catch something they may have missed. Although the internet is a great place to solve a problem, reading is an excellent source to discover beneficial learning that you may not be looking for.

Although I will get around to making standard security methods for PHP scripts, the first two details I will cover are making a secure connection and making your server more secure. If you don’t protect your access to the server and you don’t make your server a safe place to operate, you could be in for problems.

PHP Security From Source To End

When you build a website, you more than likely use a PC and host the website on a remote server. This means the traffic route will go from your pc to your router. After that, your ISP routes the request to your web host. Your web host could have a hop or two as well. Whether you use FTP, SFTP, http or SSH, your data will travel over this Internet highway. 

Although this might not seem like securing PHP, the connection process is extremely important because your local network could be attacked and exposing passwords; which could inevitably give someone access to the server. Passwords on the network could be snatched with Wireshark or some other tool. Protocols like FTP and SSH will give yourself away. If you want to connect remotely, SSH, SSL and SFTP should be practiced for remote logins. In addition to that, Ethernet is more secure than Wireless. 

PHP and The Web Server

PHP is a package that is installed on Linux. By default, it is very insecure. If you rent a VPS or dedicated server, you will more than like need to make adjustments so that you have better security. On shared hosting, you will have a configuration that you cannot change, unless your ISP makes special rules for your own account.

Dangerous PHP Functions

PHP has quite an array of functions that can create havoc. Some of these functions allow for direct access to the server. This means, a skilled Linux admin could do anything from blast email spam to adding, editing or deleting any file on your server. In other words, the user could have full control of your machine.

So, if you have a poorly configured server, any client with access to an account like Cpanel or FTP could add PHP files that can run databases and modify files. From a security point of view, you do not want that, unless the server is your own and you have no intention of anybody else being able to access the file system.

So, how do you make things safer for all users? You can customize any account so that they can only use PHP functions that will not cause problems. Alternatively, you can create custom php.ini files and add them into the public_html folders.

With PHP Suhosin, you can make sure users cannot use a php.ini file in their public_html folder to override the one you want them to use. In addition to keeping a tight grip on the PHP functions, you can monitor the php.ini file for all users and other php files to see if any changes and undesirable files are showing up on the server.

 

If you not allow anyone access to the public_html folders, a custom php.ini files in the public_html folder will only make login sessions available within the same folder.

The code below shows some functions which can be quite dangerous. This lines of code can be used with the Linux command line to find some nasty functions. If you find some files on your system with these functions, you may want to look into why they are they there and consider getting rid of them asap.

root# grep -RPn “(passthru|shell_exec|system|phpinfo|base64_decode|chmod|mkdir|fopen|fclose|readfile|php_uname|eval|tcpflood|udpflood|edoced_46esab) *\(” /home/username/public_html

root# grep -RPn “(passthru|shell_exec|system|phpinfo|base64_decode|chmod|mkdir|fopen|fclose|readfile|php_uname|eval|tcpflood|udpflood|edoced_46esab)”  /home/username/public_html

root# grep -RPn “(passthru|shell_exec|system|base64_decode|chmod|mkdir|readfile|php_uname|eval|tcpflood|udpflood|edoced_46esab) *\(” /home/username/public_html


PHP File Handlers

 

When PHP runs on the server, it uses a filehandler like suPHP, CGI, and fastCGI. If you happen to use Web Host manager, you can see your list of PHP handlers at Service Configuration >Configure PHP and suEXEC >PHP 5 Handler. You have selections in the dropdown list. If you want one that is not there, you can install and enable it with easy Apache.

For most situations, suPHP and fcgi(fast CGI) are good options and arev very popular.

suPHP
For many web hosting environments, this is the default setting. It is a very good handler that does not consume excessive memory. However, it has 1 security drawback since it allows every account to make custom php.ini files. in other words, any domain name on your server can create this file and enable any php function they want. In most cases, you don’t want this to happen, unless nobody has access to all files on the server.

Luckily, you do have the option to edit the ‘/opt/suphp/etc/suphp.conf’ file on the server to make sure nobody can create and use custom php.ini files.


To disable the ability to create custom php.ini files, change the following lines of code in the suphp.conf file that are located directly below
‘[phprc_paths]’.

 ;application/x-httpd-php=/usr/local/lib/ ;application/x-httpd-php4=/usr/local/php4/lib/ ;application/x-httpd-php5=/usr/local/lib/  ##change to  application/x-httpd-php=/usr/local/lib/ application/x-httpd-php4=/usr/local/php4/lib/ application/x-httpd-php5=/usr/local/lib/  

Now, save the file and restart Apache. Now, you can test custom php.ini files and should see that they do not work. If you use Varnish, you need to restart that service too so that the cache does not pull a cached file.

FASTCGI

 
 

Fast CGI is a PHP handler that makes it easier to customize any account or domain since you can use the php.ini sections [PATH=] and [HOST=] within the default php.ini file. FastCGI can be added with Easy Apache using Web Host Manager, or via the Linux command line. To install and build with easy Apache, go to Web Host manager and Select Easyapache >Start based on profile >Next step >Next step >Exhaustive options list >Select Mod FastCGI >Save and Build.

To use these directives, you add the sections at the end of the files and make specific rules; like the example below.

 [PATH=/home/username/public_html] suhosin.executor.func.blacklist="eval,gzinflate,system,proc_open,popen,show_source,symlink,safe_mode,allow_url_fopen,base64_decode" #disable_functions="eval,gzinflate,system,proc_open,popen,show_source,symlink,safe_mode,allow_url_fopen,base64_decode"  

In addition to using FASTCGI, you can install the PHP security extention called suhosin. You can install via the command line with ‘yum install php-suhosin‘ or add it with Easy Apache in Web Host Manager.

With suhosin, you can add various other settings to your custom php.ini file. An example is shown above. As you can see, there is more than one method to blacklist various php functions. The user at /home/username/public_html with use these functions while other users would use other specified blacklisted php functions. This method gives complete control over each account. 

 
 

Suhosin allows many more customizable features than without. For example, if you use [HOST=] or [PATH=] sections you are limited to ‘PHP_INI_SYSTEM’. You can find a full list of directives at http://www.php.net/manual/en/ini.list.php.

As an alternative to the blacklist above, you could have whitelist functions using ‘suhosin.executor.func.whitelist’.

If you want to switch from FASTCGI to suPHP, you always disable and enable the FASTCGI module using the examples below.

 sudo a2enmod fastcgi sudo a2dismod fastcgi 


File Uploads

File uploading with PHP can be very useful, but, you want to make sure to only accept the proper mime type and file extension. Otherwise, it can be exploited and you could end up letting a malicious user upload nasty kiddie scripts to your website. Often, these uploaded PHP or Perl scripts use some of those functions that can do damage when they are allowed access in the wrong hands.

Unfortunately, there are many tutorials and even bestselling books with upload code that is very insecure. Although these scripts can help learn how things work, a stronger programmer could easily exploit this weakness. One possible ugly scenario could be a situation where a malicious user uploads a PHP file with a shell script that lists all your files and folders on your system. At this point, he could plant files for spamming, grabbing your database and downloading your files. When the user has your files….trouble.

If you ever have this happen to you, you want to back everything up, find and delete the nasty files. Often, the files show up at the same time since the user had a session where he was on some mission.

After you back up and delete the files, you want to change all passwords and keep tightening everything up. Make sure your system runs safely and prevent the attack from happening again. If you find files that have security issues, fix them.


Register Globals

The register_global directives should be off. If is off by default with PHP 5.3 and lower and it had been removed with PHP 5.4. Why is it so bad? It allows you to set variables in the url.

An example is shown below that creates two variables and two values. One variable is called $name and it has a value of ‘filename’ while the other one is called $owner and it has a value of ‘jack’. You could also make a variable equal to true with a url string like authorized=1.

example.com/upload.php?name=filename&owner=jack

Although using register_globals=on is bad practice, you could always make sure variables set in the url string are invalid; then reclare them and use stronger checking that makes sure these new variables are invalid.

The example below the checks for a variable’s existence. The insecure if statement just does something if the variable exists. Meanwhile, the other block removes any value given to the variable and make sure it comes from a post request. Now, the url string that set values would not have an impact in the script; even with global_variables = on since the variable values in the string would be removed and the $_GET string would not meet the posted criteria.

Insecure

if($name){
// do this
}

Securing with Unset() Function

unset $name;

if($_POST[‘name’]){
// do this
}

Securing With An Array

$name = array();
if($_POST[‘name’]){
$name[‘name’] = $_POST[‘name’];
}

Sanitize User Input

Although this line is used by every tutorial going, I will use it anyway…”Never trust user input’. When you program PHP, forms and user input will be something that you will probably work with on a regular basis. The absolute basics are to sanitize user input with htmlentities(htmlspecialchars) or mysql_real_escape_string.


To sanitize a string for XSS by adding html entities into the string,

$var_sanitized = htmlentities($_POST[‘variable’], ENT_QUOTES);

or

$var = $_POST[‘variable’]);
$sanitized_var = filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS);


To sanitize a string for mySQL and prevent SQL injection,

$password = mysql_real_escape_string($_POST[‘password’]);


Varnish Caching

Although Varnish is not typically included in your typical PHP security lecture, it really does wonders for session based PHP content. If Varnish is enabled on a website, the administrator logins will be useless because it will deliver the page from the cache and it will ignore any session. To use Varnish with sessions you need to unset variables and learn to edit the varnish configuration file. Since varnish does not cache files with SSL, you can have a secure login with SSL and a non-working login with non-https pages.


Don’t Show Directory Lists

There really is not much use in showing files within a directory. If you do not show the list of files, they cannot be downloaded and users cannot snoop around. A simple line in your htaccess file will prevent this from happening.

# Prevent Directory listings
Options -Indexes

Don’t Make Enemies

With so much social interaction going around, you would be surprised where hackers and crackers could be found. They could be someone you had offended at a web hosting company, competition, or a social media stage like LinkedIn and Twitter. Knowing they are out there can help in your eliminiating any potential hangups. But, if you offend a hacker, you could cause an action against your own network. It is best not to ruffle any feathers out there.


Passwords and Publc Computers

Although it is alarming and disturbing to know other people or coworkers will try to snoop your private passwords, you may want to make sure you never use them on a public or work computer. The computer could have software that records typed text. In addition to that, some browsers like Firefox store passwords in plain text. So, you might think that logging into your https site is secure, meanwhile, your manager may go look in your cookies and find you password. Then, it could be used on another computer or to check your other logins.

The moral of the story here is to never allow any user access to your passwords. If you have to use a public computer, never save the password for future logins.


Setting Maximum Emails per Hour With Web Host Manager

When it comes to email, spam and your clients, you may want to take control of their email limits for many reasons; much of which are very obvious. For example, you want to limit the emails that can be done with a mass emailing script from a client. If you do not control the limits, your ip and domains could find their way into blacklists. Then, you have to send nice emails telling the spam cop to remove your ip or domain name from the blacklist.

Setting the Limit For All Domains

If you have a VPS or dedicated server, you can do this with Web Host Manager. By default, Web Host Manager’s email limit is unlimited. 

To set the same email limits for all domains on the server,

1) Login to WHM
2) Goto Server Configuration >Tweak Settings >Mail >look for: Max hourly emails per domain > Set a number like 50-200.


Setting the Limit For Specific Domains

To set a limit for one domain particular domain on the server,

1) Login to the Linux shell as root
2) Open the file with the path /var/cpanel/users/username with your favorite editor.
ie) root# vi /var/cpanel/users/username
3) Change the max email per hour
ie) MAX_EMAIL_PER_HOUR=50

Protect Yourself From Image Hotlinking

In web development terms, hotlinking takes place when a remote server links to your images and uses them in their for their own purposes. Although it is a negative activity, the best way to deal with it is to not allow your content to be snatched. The easiest way to perform this task is to use Cpanel, Apache or .htaccess. The tutorial will describes these procedures with Cpanel and .htaccess.


Cpanel

With Cpanel, you can login and select ‘Hotlink Protection’. Once you read this page, you can add your domains, file extensions and enable this feature. When you enable this feature, your .htaccess has these new directives written it. Although this feature convenient, it can leave a lot of code within the htaccess file, especially if you have many addon domains within a Cpanel account.

 

Alter Settings

 


HTACCESS

Using your HTACCESS file is a very good method to fine disable hotlinking. Adding the snippet below into your .htaccess file will result in example.com and example.ca domains to have access to the image links. 

HTTP

RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.com$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.ca/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpeg|jpg|gif|bmp|png)$ – [F,NC]

HTTPS

The example below will disable hotlinking for http and https image links. The change from above is that it checks to see if the https variable is set. In the second set of conditions, the code allows only the https version of the website to pull images.

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_REFERER} !^(http)://example.ca/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^(http)://example.ca$      [NC]
RewriteCond %{HTTP_REFERER} !^(http)://www.example.ca/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^(http)://www.example.ca$      [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|jpeg|gif|png|bmp)$ – [F,NC]

RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_REFERER} !^https://example.ca/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^https://example.ca$      [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ – [F,NC]

When you add ‘RewriteCond’ and ‘RewriteRule’, they come in pairs with the conditions followed by the rules. You can have multiple sets of conditions and rules.


Checking and testing Hotlinking

You can test to see if your images can be hotlinked by going to the websites
http://altlab.com/hotlinkchecker.php or http://www.htaccesstools.com/test-hotlink-protection/

Its is important to make sure that no images are kept in the cache when you make a check.

Varnish users

If you use the Varnish cache, you will need to restart the service with the Linux command line or use the Varnish Admin to flush the Varnish cache, in addition to clearing the browser cache(if necessary). The Varnish admin command is shown below.

A simpler way to explain the details above is to make sure to flush every caching system. If you use only Varnish, flush it. If you use browser caching, flush it. 

root# varnishadm “ban req.http.host ~ example.com”


Extra HTACCESS Tips

Now that you have hotlinking working, you may want to make a few other minor adjustments to your image files and folders. One major detail you may want to add to make sure thaat nobody can see a list of files within a folder.

To deny users the ability to read a list of files within a directory you can add one of theb two code blocks shown below. Although both give the desired results for hiding images, the first option hides all files from being listed while the second block does not allow listing to take place.

Options +Indexes
IndexIgnore *
Options -Indexes

PHP Desktop Applications

Although PHP is primarily used for web development, it can be used to create regular desktop applications. Now that you know it is possible(and has been for quite some time), you may want to be informed about your possible options.

A few options you have are PhpDesktop, PHP-GTK, PHP Nightrain and Exeoutput. All of the previously mentioned options are free except for Exeoutput.

The remainder of this tutorial will cover the PhpDesktop and long time package PHP-GTK.


PHPDesktop

PHP is a very simple application that can be used to create a desktop application in minutes. After you download and unzip the zip file, you move the folder anywhere you want. Then, you click on the ‘exe’ file to run the application. The application itself is basically Chrome browser that can interpret typical PHP, SQL, html and css. Unlike a typical web application, it can run independently using an SQLite database file(which is included in the example).

All in all, it is essentially a web application that can run all by itself in its own folder. However, you could use a remote database if you desired. But, if you intend to have others download and use your custom desktop application you may want the portable Sqlite database since it is nice, convenient, movable file and it runs very fast.

PHPDesktop can be downloaded from Google at the url https://code.google.com/p/phpdesktop/

MYSQL vs Sqlite

Since using Sqlite is such a quality choice for your database, you will be able to use your mySQL skills and manipulate the database with a free tool like Sqlite Studio which be downloaded from their website or Sqliteman. This tool makes it very easy to run queries, create tables and alter databases to your liking.

Alternatively, you could use Linux and run the Sqlite console much like a mySQL console.


Using Sqlite with Linux Command Line

The example below explains how to access the sqlite> prompt. Its usage can be found at sites like http://www.tutorialspoint.com/sqlite/sqlite_commands.htm and http://www.sqlite.org/cli.html.

root# sqlite3 my_database.sqlite

Although using Sqlite is very similar to mySQL, you should know that many mySQL queries like ‘mysqli_query’ and ‘mysqli_fetch_assoc’ will not work with Sqlite. You will need to connect to the database of your php application using PDO(PHP Data Objects). The example below will show how to connect with PDO and output the rows from a table.

In addition to querying the database, you could face other slight differences with database usage. For example, with mySQL, you could have a field with the ‘int’ type that is autoincrement. With Sqlite, you would change that type to ‘INTEGER’ and make it a primary key.

Using PDO for database connections in your projects can make it easier to port a mysql application to a Sqlite application.

function PDO_Connect($mydb_file)
{
global $PDO;
$mydb_file;
$user=””;
$password = “”;
$PDO = new PDO($mydb_file, $user, $password);
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}

$db_file = “./sqlite-database.db”;
PDO_Connect(“sqlite:$db_file”);

$command = “SELECT DISTINCT id, url FROM urls WHERE enabled=’1′ “;
$sth = $PDO->prepare($command);
$sth->execute();
$result = $sth->fetchAll();

foreach($result as $key => $val) {
$urls[] = $val[‘url’];
}
}

The code below above uses the PDO_Connect() function to connect to the database. After that, the statement is prepared, executed and an array is returned with the name ‘$result’. Finally, each element of the array is parsed and another array of each values is added to the ‘$urls’ array.

Converting a mySQL Database to Sqlite Database

If you plan to create a Sqlite database from mySQL database, you can do it easily with the linux command line. An example is shown below for making the conversion. The script mysql2sqlite.sh can be downloaded here from Github.

root# apt-get install sqlite3

root# ./mysql2sqlite.sh -u username -pMyPassword database_from | sqlite3 database_to.sqlite


PHP-GTK

PHP-GTK has been around since its first release in 2001. Although the web site and code look a little dated, it still works. PHP-GTK can be downloaded from http://pigii.sourceforge.net/

PHP-GTK is very simple to use. You download the file and install it. Often, it install into your Program Files folder. Then, you can move the folder to any location you want; such as the C: folder since this is a very easy location to work with.

Once you have your working folder, you can make a ‘.cmd’ file within it. In the ‘.cmd’ file, you can add a line siimilar to the one shown below.

“%CD%\..\..\Desktop\PHP-GTK.201\php.exe”  “%CD%\demos\components\stock-browser2.php”

The line will run the php.exe file and will open the file located in the ‘demos\components’ folder. That is the basics to getting started and being able to use PHP-GTK. To build a nice, full blown application is another story.


PHPStorm With Git

Git is used for revision control. When you work on websites and web applications, you will often make various file edits. However, there can always come a time when you want to commit a file as a finished, or go back to a previous saved version. Git will help you maintain your file revisions.


Installing Git

1) Download Git for Windows from http://msysgit.github.io/

2) Run and Install. All default settings will work fine; like click next until it installs in program Files /GIT folder

 

 

Opening Git
 

To open Git,
1) Start >All Programs >Git >Git Bash
or
Start >All Programs >Git >GUI

Git Help

To get help with Git,
1) Open bash >git help git
You will see an opens browser and help.

Using Git With PHPStorm

To use GIT with PHPStorm,

1) Make sure you have the settings set up for using the git.exe file.

 

2) VSC >Import Into version Control >Create Git Repository >OK

 

A local repository should in same folder as the current opened project

Adding Files to repository

To add a file with Git,
1) Open the file >VCS >Git >Add

Files that are added with highlight green in your list of files on the left.

Altered files will be black. Files not in Git will be reddish.

 

To add a file after editing,
1) VCS >Git >Add

Notes:
Committed files become black.
Committed files that are changed again bcome blue.

Committing a File to the Git Repository

To commit a file after editing,
1) >VCS >Git >Commit File >Add a comment >Select Commit
Note:
Committed files become black.
Committed files that are changed again become blue.


To view file and git versions
,
1) VCS >Git >Fetch
2) VCS >Show Changes View >Right Click On file >Show Diff

You can also view the history of a file later on.

To view the history,

1) Right Click File >Git >Show History


Using Windows and Linux For Web Development

When you develop web applications, you can use a single operating system of choice. Normally, that involves one of the big 3; Windows, Mac, or Linux. However, you may find that using more than one at the same time can be more effective and easier for your workflow than a using a single option. You can run multiple operating systems by running virtual machines with a program like VM Ware or Virtualbox. Both VM Ware and Virtualbox have free versions.

This article will explain how you may want to use two operating systems at once in order to accommodate your custom needs. Essentially, the overall criteria for knowing if you should use one or more systems at the same time is to determine which system has the best software and applications to do your desired task.

For example, you may have purchased programs like Camstasia and want to run them natively on Windows. A true Linux faithful may explain that anything you can do on Windows can be done on Linux. That may be good enough for him, but, you may just want to keep going on with your habits and use a system that is already fine-tuned. Adding Wine or another Linux package may just seem like adding another layer of complexity for a seasoned Windows user.

Windows / Mac Usages

Here a few instances where you may find running Windows or a Mac to be beneficial.

1. My software I have used for years
This is very self-explanatory. You have bought some well tuned software like Photoshop, Camstasia or Pinnacle Studio, and you are very used to how it works. This means the familiarity from opening the program, opening files and saving files is not something you are willing to adjust.

2. Word Processing
Microsoft Word does everything you want. After years of usage, you are not that interested in starting over. The free Linux alternative LibreOffice is a worthy alternative, but, it may miss the odd white space or spelling mistake.

3. Email
Linux has excellent email clients like Thunderbird. However, like many Linux programs, the usage can vary from that of Windows. In this case, you may just want to use the formula that has been working all along.


Linux Usages

If you have Linux experience with distros like Ubuntu or Centos, you will have no problem finding your way around the operating system. But, if you are new, you may experience that it is a much different beast than Windows or Mac. Linux is largely a programmer’s operating system.

Permissions on files and starting some programs can involve time spent with the command line. In all honesty, if you are new or do not have a desire to be good at Linux you may find running a second operating system an uphill battle. However, if you just want to edit and run a Lamp server, it should be rather easy to accomplish.

Nevertheless, if you are dedicated to learning and running Linux, you have a lot of powerful knowledge that can be used to be more effcicient with dedicated or VPS hosting accounts, and for using Linux at home where you find its benefits are high. Spin-offs from using Linux for a hobbyist are that you can setup home servers with Raspberry Pis that can allow you to test and run web applications and run other Linux applications.

One such application is a live motion security cam that stream live video and save swf files after motion is detected. On top of that, Linux machines and Raspberry Pis can be used to automate your house; like turning lights on and off, creating a weather station and watering plants on a schedule; all of which can be monitored in an online environment. Linux usage can go on and on.

Anyways, here a few instances where you may find running Linux to be beneficial.

1. Local Lamp Server
From a web developer point of view, Linux could stand out if you want to install and run a Lamp server. Wamp is good, but Lamp is really kick-ass. Since you will likely use Lamp online, using it locally has many benefits. As a web developer, it is an automatic arena to test scripts offline, or, to run custom applications on a localhost. 

2. Using a Virtualbox For a Client
Virtualbox, by Oracle, allows you add Virtual Linux machines. Essentially, you can build an entire system that is specific to client. You can add an editor like PhpStorm, Netbeans, Gedit, and others.

Using Linux makes it easy to connect to foreign servers with the command line. Keeping a whole system to store files and run applications can make your workflow very efficient. It also makes backing up a very simple process since a Virtual Machine is essentially a large file.

Conclusion:

Under certain circumstances, using two systems can be very efficient. If you decide to avoid Linux, you may be able to make do. If you use many of its advantages like Lamp and home servers, you can get more done. Knowledge and practice of Linux is never a waste. As you learn more about it, you will be strengthening your web development and systems admin knowledge. As you can do more, more options and tasks are available to you. Being able to do more on the web is an advantage that Linux will deliver.

Finally, in addition to doing more, gaining a stronger knowledge of Linux can get you out of jams and keep your systems running smoothly. Therefore, when something does go wrong, you will have the basic troubleshooting skills to get things back to normal and find why things had gone wrong.


Raspberry Pi Motion Detecting and Live Web Cam

The Raspberry makes is a fantastic device that allows you to stream live video and record motion detection. As long you have a webcam that is compatible with the Raspberry Pi, you have the basic hardware to accomplish such a task.

In order to get started with live streaming and motion detection, you need to install the Linux package titled ‘motion’. Motion will handle the process of streaming and recording video. Normally, out of the box, it just works.

Installing Motion on Linux

 apt-get install motion 

Configuring Motion

After motion is installed, you will need to open a couple of files and make some simple edits. The two main files are /etc/motion/motion.conf and /etc/default/motion. Below are some code blocks that will need to be changed in order to broadcast streaming video or record motion detection.

motion.conf

 daemon on webcam_localhost off control_localhost off 


motion

This file, located in the /etc/default folder requires a single change.

 start_motion_daemon=yes 


Adjustments

After the initial options are set, you may want to customize your setup. Below, are a few examples of customization; like setting the framerate equal to that of the webcam.

//motion.conf
framerate 30  // default 1
quality 90 // default 70

Out of the box, it will record motion. But, it is sensitive to a single frame of motion. In some instances, flickering light could make it start recording a brief sequence. In order to combat this, you can increase the amount of frames that need to be contain motion.

 minimum_motion_frames 5 

Now that the cam actually runs and everything works, you can find the stored motion files in the directory defined by the target_dir option that is set in the motion.conf file. By default, the directory is tmp/motion.

Storing Motion Files On a USB Stick

If you run a Raspberry Pi on an SD card(in all likelihood), you may want to mount a usb stick on it so it records all motion to the usb stick. By doing this, you will cut down on writes to the sd card and keep files nice and organized.

To store images on a mounted USB stick,

1) get the USER ID

 id -u pi 

2) Add the user pi to fstab in order to mount for that user.

 /dev/sda1      /home/pi/mount/storage   vfat  uid=1000,noauto,user,exec   0 

3) Format a usb stick fat32

4) Mount it to a desired folder

5) Unmount it

6) Format it with mkfs.ext4. This format is critical to allow a user other than root to be able to have specified permissions with mounted media.

 mkfs.ext4 /dev/sda1 

7) Mount it again

8) Change folder permissions to 777

 chmod 777 /home/pi/myfolder 

9) Change owner to pi

 chown pi:pi /home/pi/myfolder 

When you can write to the mounted folders and they have the proper permissions, you can store the jpg images and swf files there.

Website Usage

Your Raspberry Pi will need a complete LAMP setup; or at least an installed web server like Apache. Once you have this, you can enable port forwarding in your router so your ip(or even a website) can be seen on the web via port 80. With port forwarding you can add other other forwarded ports to the router like 8080 and 8081, and port 22 for SSH, if desired.

By enabling an ssh port, you will be able to remote control all Linux boxes on your local network because once you can connect to one of them through the ssh port, you can easily connect to the others since they are all on the same local network.

Once you make the pages available to the outside world, you can create a web page that can be seen on the web with an src tag which embeds the streamed video. If you allow a local ip like 192.168.0.101 to be port forwarded with port 80, you make have a file like links to another inetrnal ip like 192.168.0.102.

All in all, you will use two Raspberry Pis on a local network that will be setup so that any other website can integrate the live streams into a webpage.

<img src=”http://local_ip_with_motion_service:8081/” width=”320″ height=”240″/>

Then, you can use any other online webpage and add an iframe to the website url hosted at home.

<iframe style=”width:343px; height:262px;” src=”http://isp_ipaddress/test.html”></iframe>


GOOD REFERENCE

http://linux.die.net/man/1/motion


PHP IDEs and PHP Editors

When you code PHP, you can use one or more editors. some are very simple, some are free and some cost money for a license. There are excellent options for every developer. Although deciding on an editor seems like a simple choice, it can easily become an ongoing pursuit to find the best editor for you that makes you comfortable and productive.

This article will contain some options and reasons why you may want to choose the best editor to suit your needs.

Beginner Tools

Simple Free Editors

Often, when a web developer learns to hand code PHP applications, an IDE can be a distraction since features like code completion and configuring your editor could be a distraction that gets in the way of understanding basic syntax, functions and loops. From experience, I found a simple quick loading editor like Notepad++ to be a very good tool to learn PHP / mySQL. Early on, I even moved from an IDE back to Notepad for a couple of years until I could easily hand code and copy and edit code rather easily. 

Notepad++ had good FTP and SFTP connectivity and made scripting a simple procedure. But, eventually I found it lacked important features like code completion and text formatting. At this point, I switched back to an IDE to become more productive and give the code a ‘good look’.  

Although Notepad++ is a good introductory tool, it is also a good tool for any developer to build small PHP scripts and edit other scripts since it so fast load. Also, it can be a secondary mini-script maker to work on a basic script while your IDE is open with a large project. 

More Advanced Tools

Free PHP IDEs

There are various free PHP IDEs. Two popular ones that come to mind are Netbeans and Eclipse. These tools will help you automatically complete code, format your work, and make finding your classes, functions, variables, etc an easy process. 

Commercial PHP IDEs

After experience with Netbeans and Eclipse, I was content and appreciative of such good free tools, but, there always seemed to be something minor that kept me looking at other options. I was a Netbeans user and liked the SFTP, projects, compatibility with Windows and Linux, code completion, highlighting, themes, custom rules and more. But, I did find it a bit slow, unappealing to look at and questionable about its formatting. 

During my times of questioning, I samples many trial versions of editors like PHPStorm, PHPEd, PHP Designer and PHPEdit. On the first go around, I thought Netbeans was a fantastic free option although I liked the others too.

After months of pondering a switch, I tried PHPStorm again. Immediately, I was drawn to the look and many of its similarities to Netbeans and the many numbers of other web developers and experts that recommend its usage. So, I opened up a page of code and reformatted it with PHPStorm. Immediately, I liked the new formatting which was always something I did not care for that much with Netbeans since the margins were not aligned like I wanted.

Although the default new colors of the editor may have had an influence, I still found this polished IDE was worth having. After all, as a full time PHP / mySQL programmer / web developer, spending $100 on the most important tool is less than a minor expense.

Since PHPStorm seemed like a good fit, I made a download from the server as a final check. Before that even completed, I pulled out my credit card on the first day of the free trial and bought it. Money well spent and it makes me want to code more.


Lamp vs Wamp

When you begin or work with server side scripting; like PHP(or Perl) and mySQL, you are often confronted with two server options; Lamp and Wamp. Lamp stands for Linux, Apache, mySQL and PHP(or Perl) and Wamp is the same except that the ‘W’ is for Windows. For many Windows users, Wamp is a simple and easy setup for which to practice PHP, mySQL and use phpMyAdmin.

In most situations, you will use lamp when you host a website on a live server. Therefore, using Lamp does have many benefits if you plan to host and administrate websites in a serious manner. For starters, you will be able to grow skills, understand how it works at it root level, and learn to master the command line. Without knowing how to use Linux and the command line, you could be in a tight spot if you plan or need to run a dedicated or VPS server.

Therefore, if you want to make overall headway and progress, you may want to use Wamp to become a proficient programmer and use Lamp to become a better programmer and system administrator. Once you gain a larger understanding of Wamp and setting up servers with Lamp, you may find Lamp is easier to configure on a custom level and you can do more with it.


Greedy and Non-Greedy Regular Expressions

Writing regular expressions allows you to make you custom matches the way you want. One particular meta character that can make pattern matching easier for large blocks of repetitive code is to add a ‘?’ after a greedy quantifier ‘*’. If you add a ‘?’ after a greedy quantifier, it will make the match as fewest times as possible. Oppositely, if you do not use a ‘?’ after a greedy quantifier it will try to make the match as many times as possible; thus you will end up with just one match since your expression will grab everything in between the first and last match.

The simplest way to show this is through the following coding samples.

The example below will match the first ‘<table>’ tag and everything in between until it finds the last ‘</table>’ tag in the document.

 $data = file_get_contents('http://localhost/ebay-pi.html'); $regular_expression = '/<table\s*listingId(.*)<\/table>/si';   //Make an array of all matches preg_match_all($regular_expression,$data,$posts, PREG_SET_ORDER); 

The example below will match every starting ‘<table>’ table tag to its matching ending ‘</table>’ tag. This method is often a choice for matching a pattern that occurs throughout a string(or file) and would be probably be desired for web scraping.  

 $data = file_get_contents('http://localhost/ebay-pi.html'); $regular_expression = '/<table\s*listingId(.*?)<\/table>/si';   //Make an array of all matches preg_match_all($regular_expression,$data,$posts, PREG_SET_ORDER); 

Linux Memory Usage Issues

With Linux, you must keep an eye on the system health to ensure that your hard drive space and memory do not get eaten up. If you exhaust your limit, you end up with issues like websites that cannot be viewed and the inability to login to GUIs like Web Host Manager and Cpanel.

When you do run out of memory and attempt to login to a control panel like Web Host Manager, you could see the an error message that is displayed below.

 Internal Server Error 500 No response from subprocess (whostmgr (cpanel)) with exit signal: 0 


Running Out of Memory

If you run out of memory, you need to login to your host with SSH and stop or kill some services; like mySQL. If you use a service like Web Host Manager and Cpanel, you may need to reboot the cpanel service to have access to your control panels.

To restart Cpanel,

 /etc/init.d/cpanel restart 

Once you have been able to login to Web Host Manager, you can do a graceful system reboot and hopefully your memory slide back into a usable level.

To see how much memory you have available, run the following command in the shell.

 free -m 

PHP Tutorial For Beginners

PHP is the most popular server side web programming in the world. Since it had been offered to the public back in 1995, its usage had grown tremendously. Meanwhile, its popularity continues to maintain a stronghold, regardless of the criticism from others who are always there to undermine it.

If you read enough blogs and books, you will find that its popularity emerged from PHP being easy to learn and its ability work well with html and Javascript coding. Regardless of why it became popular, you may want to ask yourself, “Why is PHP right for me?”.

The answer could easily go on indefinitely, but, a few solid reasons why PHP could be right for you are that it has a short learning curve, there is a lot of PHP tutorials, help, and support available online, most affordable web servers have it installed on their system, there is a large code base which makes it easy to find a program similar to one you want to use, and it is very easy to alter other PHP scripts when you have PHP coding skills.

So, now that you may be sold on learning PHP, the next part of this lesson will explain how to start coding with PHP. This basic PHP tutorial will cover basic syntax, printing text, variables and strings, arrays, loops and some insight regarding how to do more fancy stuff with PHP.

If you want to search our library with over hundreds of pages, you can find more PHP tutorials here.


Coding Syntax

When you use or write PHP scripts, the start of a coding can be <?php or <?. In most cases, the starting block uses the long tag <?php. The other method is called a short tag. Some servers will not allow the usage of short tags, but they all allow the usage of the ‘<?php’ tag. It is considered a good habit to code with the long tag so your script has a more ‘universal’ concept. PHP coding is done within files that have the ‘.php’ extension.

Although PHP files must have the “.php” extension, you can add HTML, Javascript, XML and CSS code blocks into your PHP. If you add HTML or other coding like Javascript outside of the PHP tags, The code will be interpreted. However, if you plan to use HTML or JavaScript within PHP tags you will need to create the code using the echo command. Normally, when you use the echo statement a string of text is inserted between single quotes or double quotes.


QUOTES

You use quotes when you want to print words, declare variables and strings. When you want to end the statement, you use a semi-colon. With PHP, you have the option to use single quotes or double quotes. In some instances they have similar behavior, but, not in others.

For example, if you use single quotes around variables, the variable will not be interpreted. But, if you use double quotes, it will. Since a variable could be something new for you, I will show a few examples using single and double quotes with variables and printing statements.

Single Quotes
Declaring a Variable

$variable1 = ‘Hi there’;
$variable2 = ‘John and Paul’;

Printing text
echo ‘Hi there’;

Printing Variables

echo ‘$variable1 $variable2’;

The result of the above statement is the same text that is shown between the single quotes, $variable1 and $variable2. Like I mentioned above, variables within single quotes do not get interpreted.

Double Quotes

Declaring a Variable
$variable1 = “Hi there”;
$variable2 = “John and Paul”;

Printing Text Within Double Quotes

echo “Hi there”;

Printing Variables

echo “$variable1 $variable2”;

As you can see, the output here is much different than the same statement that had used single quotes because it actually prints the data that the variables represent.
Here is one more example that is slightly more creative. It prints variables and text using variables that are outside of quotes and strings of text that exist between quotes.

 echo $variable1.” “.$variable2.” are great guys”;

As you can see, when you echo a variable outside of the quotes, it is interpreted. If they strings of text do not contain variables, they will both output the same results.
Also, this example shown above introduces concatenation. Concatenation uses the period character ‘.’.

When you place the dot in a statement, it can be followed by another variable or a set of quotes. After a set of quotes, you can add another dot and add another variable or set of quotes. If the syntax is not proper, you will see an error when you try to view the page in a browser.

At this point, you should be able to write simple on-liners with PHP and see the output as you expect.
Here are a few more coding examples which could help you understand more about basic PHP syntax.  All the syntax will look different in all of these samples even though they all display the same results.

Sample #1

echo ‘<ul><li>Item1</li><li>Item 2</li></ul>’;
<ul>
echo “<li>Item1</li><li>Item 2</li></ul>”;


Sample #2

<?php
echo ‘<ul>’;
?>
echo ‘<li>Item1</li><li>Item 2</li></ul>’;


Sample #3

<?php
echo ‘<ul>’;
echo “<li>Item1</li>”;
echo ‘<li>Item 2</li>’;
?>
</ul>


PHP Arrays

You won’t get far with PHP without strong knowledge about PHP arrays. An array is a group of options. For example, an array of cars is Ford, Chevrolet, Toyota, Honda, Volkswagen, BMW and Mercedes. An array can written using array(). It contains a list of items separated by commas with values stored in quotes (with the exception of numbers). If an array value contains a number, no quotes are needed.

A tip to understanding arrays is that each item will always have a key and a value. Let’s move on and look over a few arrays to help you know more about them.

An example array of cars is shown below.

$cars = array(“Ford”, “Chevrolet”, “Toyota”, “Honda”, “Volkswagen”, “BMW”, “Mercedes”) ;

Let’s go through the top line of code. The array is called $cars. The car Ford has a key ‘0’ while the car Mercedes has a key of ‘6’. All cars in between have the ordered keys from 2-5. In case you are wondering, numerical keys always start from ‘0’, not ‘1’ like you may expect.  The values are the names of the cars; such as Ford.

Now, here is another example that is equal to the example above, except that we wrote the keys and the values.

$cars = array(0 =>“Ford”, 1 =>“Chevrolet”, 2 =>“Toyota”, 3 => “Honda”, 4 => “Volkswagen”, 5 => “BMW”, 6 => “Mercedes”) ;

The two car samples are identical. Here is how you access a value in the array.

echo $cars[‘0’];

The output from the code about is ‘Ford’

Here is another example using the array shown above. It includes a review of some basic syntax we had covered earlier.

echo “My car is a “.$cars[‘0’].”.”;

The output from the code about is ‘My car is a Ford’.

More detailed examples and a crash course for PHP arrays can be found at http://fullstackwebstudio.com/locations/coding-blog/PHP-Array-Primer.html.


PHP Loops Tutorial

Loops are another major component of PHP programming that a PHP programmer should learn well. Loops are repeated procedures that you run for a specified number of repetitions. The most common loops you will use with PHP are the for, foreach and while loops.


Simple For Loop

The for loop starts with the word ‘for’. After that, a pair of brackets () holds the conditions and sets a variable. There are 3 main parts within the brackets; the value of a variable(in our case $i). After the variable is set a semi-colon is added. The next criteria(on the other side of the semi-colon) with a condition that says the variable $i is less than 5. It too is separated by a semi-colon. The final criteria is the $i++; this time without a semi-colon. The $i++ is just there to allow for iteration to take place.

In a nutshell, the first value of $i is printed followed by a repeated loop until $i is no longer less than 5.

As soon as $i is not less than 5, there is no more repeated loops.

After the code is added into the round brackets, you add a set of curly brackets for which you can add any desired code.  The example below should make everything clear.

for($i=1; $i < 5; $i++) {
echo $i.”<br/>”;
}

The output of the above code is the printing of numbers 1-4 on separate lines.


Simple Foreach Loop

The foreach loop is often used to output values from arrays. To make this work, you use the foreach statement and throw an array into it. After you add the array name, you can add another name that your want to use for each element in the array.

Essentially, the foreach statement goes like this …. Foreach my entire array as single value in the array, do this. In the example coming up, you can see an array called $items and it will loop through all values like one, two, three and four.

$items = array(‘one’, ‘two’, ‘three’, ‘four’);
foreach ($items as $item) {
echo $key.” “.$item.”<br/>”;
}

Now that you have the hang of the foreach loop, you may want to try another foreach loop where a key is introduced. Earlier, in the section about arrays, you learned that each item in array has a key and a value.

The main difference with the next loop is that is contains the name of the key(which happens to be $key in this case) and a ‘=>’ which associates an array key to an array value. So, the code below will run a loop for each key and value pair; such as the key ‘First’ and its matching value of ‘one’.

$items = array(‘First’ => ‘one’, ‘Second’ =>’two’, ‘Third’ =>’three’, ‘Fourth’ =>’four’);
foreach ($items as $key =>  $item) {
echo $item.”<br/>”;
}

Simple While Loop

While loops do repeated loops as long a s a specific condition is set. Using while loops is very popular with database programming using a database like mySQL.
The code block below will repeat as long as the value of $i is less than 5.

$i = 1;
while($i < 5) {
echo $i.”<br/>”;
$i++;
}

Here is a glimpse into the future regarding using a while loop with data returned from a MySQL database query. Here is what is going on in the next example. A query is made to select the id, firstname and age from a database table called table_sort. The mysqli_query() function runs the query. Now, the while loops runs for all rows of data within the table. The code within the while loop will run for each row of data that was fetched.

$command= ‘SELECT id, firstname, age FROM table_sort’;
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];
$user_age = $row[‘age’];
$user_firstname= $row[‘firstname’];
echo “<h2>Hi id #”.$id.”</h2>”;
echo “Firstname: “.$user_firstname.” | Age: “.$user_age.”<br/>”;
}


PHP OOP Tutorial Basics

OOP(Object Oriented programming) is more complicated than basic PHP programming that had been discussed in this post. OOP allows you to create objects that use classes, methods and properties. An object is like bundling up a class and being able to use its properties and methods based on accessibility. Methods in OOP are written similarly to regular PHP functions while properties are similar to variables. OOP really allows programmers to keep a tight set of rules within each class. This makes reusing classes very easy.

PHP has gone through various versions; such as PHP3, PHP4 and PHP5. Since PHP4, Object Oriented Programming (OOP) had been available so that programmers could have more coding options. With PHP OOP, programmers can create classes, methods, constructors and more.

Although OOP can seem a little complicated to learn and hand code, you may find that persistence will make this easier. Knowing OOP is valuable since many PHP scripts contain some or the majority of its code with OOP and you will not be guessing about the coding. It also makes it easier to modify an OOP script to suit your needs.
Basic OOP samples can be found here.


MYSQL Database

MYSQL is that most popular database engine that is used with PHP. Under normal working conditions, a PHP programmer will work with MySQL databases on a regular bases. All major PHP scripts like WordPress, Joomla, Magento and thousands more use PHP and MySQL. Information regarding MYSQL can be found here.

Your Bright Future

With years of practice, skill accumulation, and dedication your PHP skills can help open lots of doors. You can seek a regular 9-5 job, freelance, freelance / work fulltime and code as a hobby. Since you have so many options, you can make a switch at any time. For example, some people go the full time route in order to receive steady pay and job security, build a solid resume and build skills which will act as a stepping stone since everyday your skillet grows, so does your worth.

Since a web developer has so many options for self-employment, subcontracting and regular 9-5 work, you don’t have to stay stuck in a job that raises you pennies on the dollar when your skillset and productivity grows 100-500%. As an alternative to a 9-5 setup, your company may allow you to obtain a contract with them and you can work from home. Since your job is really a connection to a web server and done on a pc, you are not confined to a position where your physical being makes any difefernce.

In this era, employers may hire Junior PHP programmers with little experience thinking they are more likely to stay at one job. But, if you develop good PHP code, you are likely smart enough to know your worth in the marketplace.

Everything in life runs its course and always look out for yourself because your needs and interests are unique. Lucky for you, web developers can take their career anywhere since a good laptop is essentially an office.

Regardless of your working needs and desires, there is the right option for you.


Crash Course PHP HERE Documents EOF

Using PHP HERE documents allows you to print or create custom, readable strings within EOF tags.

$var1 = “Hello”;
$var2 = “World”;
echo <<<EOF

Echoing heredoc. My variables and text output just fine. Variable 1 is $var1 and Variable 2 is $var2.

EOF;

$make_eof_variable = <<<EOF

Hey Variable 1 called $var1! I can add the variables within the EOF tags then output the variable anywhere on the page!

EOF;

echo $make_eof_variable;


Crash Course For PHP Arrays

These various examples should shed some light about PHP arrays. The examples show simple arrays, indexed arrays and multidimensional arrays. 

Simple Array 

This simple arrays contains
2 items. Each item has a key and a value. The first element in the array has the key ‘first’ and a value ‘myfirst’ while the second item has a key ‘second’ and value ‘mysecond’. All keys in an array have a name or a numerical value. In this example, the key is a name.

When you want to output an item in an array, you simply use the array name followed by the key that is enclosed in brackets.

$mypages = array(
'first' => 'myfirst',
'second' => 'mysecond'
);
echo $mypages['first'];

Multi Dimensional Array 

Although the the example below looks more confusing than the example above, the two are very similar. The main difference is that some of the items in the array called ‘myarray’ are arrays. Essentially, you have an array with some single items while the ‘multi’ item also contains an array and one of its items contains an array.

To get your desired output, you simply start with the main array and work down the ladder with the various nested keys. For example, the coding $myarray[“multi”][“dimensional”][“array”] contains the multi, dimensional and array keys which represent the value called ‘foo’.

$myarray = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($myarray["foo"]);
echo "
"; var_dump($myarray[42]); echo "
"; var_dump($myarray["multi"]["dimensional"]["array"]); echo $myarray["multi"]["dimensional"]["array"];

Another Multidimensional Array 

This example is like the example above, except the ‘dimensional’ key contains an array with only names. The values for the array mice, cat and dog are represented with the numerical keys 0,1,2. This is the reason why printing $myarray3[“multi”][“dimensional”][1] outputs cat.

$myarray3 = array(
       "multi" => array(
         "dimensional" => array("mice","cat","dog")
         )
    );

echo "Array 3: ". $myarray3["multi"]["dimensional"][1]; // cat;

Multidimensional Array With Indexed Entries 

This example is like the example above, except there are numerical keys written for the dimensional array. The values for the array mice, cat and dog are also represented with the numerical keys 0,1,2. This is the reason why printing $myarray3[“multi”][“dimensional”][1] outputs cat.

$myarray4 = array(
       "multi" => array(
         "dimensional" => array(0 => "a", 1 => "b", 2 => "c", "myword" => "test")
         )
    );

echo "Array 4: ". $myarray4["multi"]["dimensional"][1]; // cat
echo "
"; echo "Array 4b: ". $myarray4["multi"]["dimensional"]["myword"]; // cat

Accessing Elements In an Array With Numerical Keys or Named Keys 

This example is like the example above, except that the numerical indexes are gone. Without a key defined with ‘=>’, any item takes on a numerical key.

$myarray5 = array(
       "multi" => array(
         "dimensional" => array("a", "b", "c", "myword" => "test2")
         )
    );

echo "Array 5: ". $myarray5["multi"]["dimensional"][1]; // cat
echo "
"; echo "Array 5b: ". $myarray5["multi"]["dimensional"]["myword"]; // cat

At this point, you should have some idea about arrays in regards to keys, values and usage.


Moving WordPress to a Subdomain

When you move a WordPress site to a subdomain, there are a few steps that can follow to ensure that the new subdomain will look and operate and you want. The steps are outlines below. 

1. Setup a new subdomain with cpanel or add an A record for the main domain.
2. Download the original database
3. Extract the database with a zip tool like Winrar, if necessary.
4. Open the database file in a text editor like Notepad++ or Gedit.
5. Do a search and replace for the old url and replace it with the new one. For example, search for http://example.com, http://www.example.com and replace this with your subdomain like newsubdomain.example.com
6. Do a search and replace for absolute paths like /home/username/public_html/example.com and change to the new path like  /home/username/public_html/newsubdomain.
7. You can look for hard coding in files too. Your editor can do a find / replace for all files or you can use the Linux command line. The command ‘grep -H -r “www.example.com”  /home/username/public_html/newsubdomain’ will serach the new subdomain for www.example.com.
8. Create a new database and dump (import) the updated ‘.sql’ file.
9. Change the database settings in wp-config.php.

At this point, you can open the new subdomain and see the website. It may or may not look exactly as you expect. One issue could be that the header is missing files. This can be fixed. Open the original domain and find the header image name with ‘View Source’.  Do a find and replace in the database using phpmyadmin (or command line). The url for a subdomain will change in size. Believe it or not, the size is important.

If the url grew by 13 characters (example.com became newsubdomain@example.com), you can change numbers like ‘s:55’ to new amount of characters. For example, in wp_options you may have an option_name like theme_mods_templatename where ‘s:55’ needs to be changed to to new amount of characters for the long absolute url lengths. Essentially, all instances of ‘s:55’ will now become ‘s:68’.

Now, the website should display properly.  


Using Yslow To Increase Web Page Speed

Yslow is an addon you can add to a browser like Firefox or Chrome so that you can analyze web pages. With the analysis, you can determine some areas that require upgrading.

When Firebug and Yslow addons are installed in Firefox, you simply open Firebug and select the Yslow Tab.

To run a Yslow check,

1) Open the desired web page.
2) Select ‘Run test’

 

After a test is completed, you can see your score and a list of grades. 

 

Upgrade Web Page(s)

To upgrade your web pages and get higher grades, you can select any link from the list shown above. Generally, there are a few quick fixes that can give instant results. The major changes are to add expires headers into your .htaccess file, enable compression (Cpanel can do this), minify css and javascript files, and set Etag in .htaccess file.

Sample Additions to .htaccess

FileETag none

ExpiresActive On
<IfModule mod_expires.c>   
    ExpiresDefault “access plus 6 month”
    ExpiresByType image/x-icon “access plus 6 month”
    ExpiresByType image/jpeg “access plus 6 month”
    ExpiresByType image/png “access plus 6 month”
    ExpiresByType image/gif “access plus 6 month”
</IfModule>


Caching With mod_expires and mod_headers

Allowing visitors to cache images and files in their browser can make your website significantly faster to navigate. This post will explain how to use mod_expires and mod_headers to allow visitors to cache files in their browser. With browser caching, you can set the time for which files can be cached. The caching duration has pros and cons. For example, if you are blogging and you update content, but rarely change images, caching for long time periods can significantly decrease the load from your server and make the user’s experience much better. Alternatively, if you have a small website and make changes daily, caching for the long term can be detrimental if you want your visitors to always see the latest content.

For a larger game plan, you can use Varnish and mod_expires to keep your website running quickly.

Show Modules with Debian / Centos

Debian / Ubuntu
root# apache2ctl -M
root# apachectl -t -D DUMP_MODULES

Alternatively, a tool like Web Host Manager with Centos can show which Apache modules are installed and enabled. You can see that with Easy Apache.

Enable mod_expires (Debian / Ubuntu)

root# a2enmod 
root# /etc/init.d/apache2 restart

Now I can cache all the images on my site by adding this to .htaccess in my root directory.

1) Add code to .htaccess.

#mod_expires
ExpiresActive On
<IfModule mod_expires.c>    
    ExpiresDefault “access plus 1 month”
    ExpiresByType image/x-icon “access plus 1 month”
    ExpiresByType image/jpeg “access plus 1 month”
    ExpiresByType image/png “access plus 1 month”
    ExpiresByType image/gif “access plus 1 month”
    ExpiresByType application/x-shockwave-flash “access plus 1 month”
    ExpiresByType text/css “access plus 1 month”
    ExpiresByType text/javascript “access plus 1 month”
    ExpiresByType application/x-javascript “access plus 1 month”
    ExpiresByType text/html “access plus 600 seconds”
    ExpiresByType application/xhtml+xml “access plus 600 seconds”
</IfModule>


Using mod_headers

1) Enable mod_headers

root# a2enmod headers


To use mod_headers,
1) Add code to .htaccess file

<FilesMatch “\.(php)$”>
Header set Expires “Sat, 15 Dec 2015 20:00:00 GMT”
#Header set Cache-Control “public, max-age=3600, must-revalidate”
</FilesMatch>

#mod_headers
<FilesMatch “\.(ico)$”>
Header set Expires “Sat, 15 Dec 2015 20:00:00 GMT”
#Header set Cache-Control “public, max-age=3600, must-revalidate”
</FilesMatch>

<FilesMatch “\.(ico|pdf|flv|jpe?g|png)$”>
#Header set Cache-Control “public, max-age=3600, must-revalidate”
</FilesMatch>

Simple Check to See If caching Is Working

If you have Firebug and Yslow addons installed in your browser, you can fine tune your Expires Headers. All you must do is a run a Yslow test and check the Expires Headers. It will give you a grade and tell you what has ‘No Future’ expiry date. With a little tuning, you can fix the expires headers. You may need to add expires for specific file types like ‘.ico’. Or, you may need to remove links to non-existent images (or add 1 pixel transparent images to a folder). As you tune expires Headers your Yslow grade will climb instantly. 


Installing Varnish On Raspberry Pi

Varnish is an http accelerator (reverse proxy) that can be used to store copies of web pages that will be used to serve the web surfer instead of copying the page from the server. Essentially, websites that are delivered from the cache will display much faster than those that are not. Although Varnish can accelerate the page delivery, the ISP (Internet Service Provider) upload speed, page content, and browser caching will have very high impacts on the page load speed too.

Since Varnish can store the pages in memory, a small website that is optimized for performance can be quite efffective; especially if its size is well under the cache size that you set.

Although Varnish and a Raspberry Pi can be used to host a website under aquequate conditions, it can also be an excellent starting point to experiment with Varnish and its features before making major changes to a live server with many Virtualhosts and addon domains.

Here are the steps to setting up Varnish on the Raspberry Pi.

To install Varnish on the Raspberry Pi,

1) Become a sudoer to execute root commands.

 pi@raspberrypi:# sudo -s 

2) Open the /var/tmp folder

 root@raspberrypi:# cd /var/tmp 

3) View the files in the repository at http://repo.varnish-cache.org/source/.

4) Download a file like varnish-3.0.5.tar.gz.

5) Open the /var/tmp folder

 root@raspberrypi:# wget http://repo.varnish-cache.org/source/varnish-3.0.5.tar.gz 

6) Extract the file and change directory. When you compile and install from source you work from within the top folder. In this case, the folder is varnish-3.0.5.

 root@raspberrypi:# tar xzf varnish-3.0.5.tar.gz root@raspberrypi:# cd varnish-3.0.5 

7) Install dependencies

 root@raspberrypi:# apt-get install autotools-dev autoconf libpcre3-dev libedit-dev automake libtool groff-base python-docutils pkg-config 

8) Run autogen file and continue compiling and installing from source.

 root@raspberrypi:# sh autogen.sh 

9) Configure

 root@raspberrypi:# sh configure --enable-diagnostics --enable-debugging-symbols 

10) Make

 root@raspberrypi:# make 

11) Make install

 root@raspberrypi:# make install 

Note: If anything went wrong and you are doing a second attempt, run make uninstall and make clean. Make uninstall will remove the previously installed package.

12) Setup the necessary links

 root@raspberrypi:# ldconfig -n /usr/local/lib/ 

13) Edit the configuration file default.vcl.

 root@raspberrypi:#  vi /usr/local/etc/varnish/default.vcl 

or

 root@raspberrypi:#  nano /usr/local/etc/varnish/default.vcl 

Note: You will need to uncomment some lines such as;

  backend default {      .host = "127.0.0.1";      .port = "8080";  } 

Note: The port 8080 will be used by the web server.

14) Change the port from the web server. Normally, Apache or Lighttpd will use port 80. Change this to something else like port 8080.

 root@raspberrypi:# vi /etc/lighttpd/lighttpd.conf 

15) You can make a file to start the service or you can type or copy and paste the following command to start the Varnish service.

 root@raspberrypi:# /usr/local/sbin/varnishd -f /usr/local/etc/varnish/default.vcl -a :80 -P /var/run/varnish.pid -s malloc,35m 

Note:
The -f option tells Varnish where the configuration file is located. In the case, the file is located at /usr/local/etc/varnish/default.vcl
The -a option is the port that Vanish will use. In this case, Vanish will use port 80. Your router will allow port forwarding on the port.
The -P option is the PID file location which records the process id for Varnish. When you know the process id, it makes it easier to kill the service, etc.
The -s option tells where the cache is located and the size of the cache. In this case, the cache is 35m.
Find more about options at https://www.varnish-cache.org/trac/wiki/Performance.

Check if Varnish is Running

 root@raspberrypi:# /usr/bin/pgrep -lf varnish 
 

Check if Varnish is Working Properly

PHP Users can make a file called view_headers.php and use the get_headers() function to output the headers which hopefully includes some information about Varnish. The samples below show how to get headers from a URL.

 print_r(get_headers("http://localhost", 1)); print_r(get_headers("https://example.org", 1)); print_r(get_headers("myIPaddress", 1)); 

You can run the file in a browser or via the command line. Running the PHP file at the command line is shown below.

 root@raspberrypi:# php ./view_headers.php 

If all goes well, the array will contain the line below. [Via] => 1.1 varnish PERL users can install the libwww-perl package to view headers.

 root@raspberrypi:# apt-get install libwww-perl root@raspberrypi:# GET -Used http://localhost:80/ 

If all is working fine, you should something similar to the output below.

GET http://localhost:80/
User-Agent: lwp-request/6.03 libwww-perl/6.04

200 OK
Connection: close
Date: Sat, 11 Jan 2014 18:23:19 GMT
Via: 1.1 varnish
Age: 0
ETag: “3260290251”
Server: lighttpd/1.4.31
Vary: Accept-Encoding
Content-Type: text/html
Last-Modified: Sat, 14 Sep 2013 23:19:36 GMT
Client-Date: Sat, 11 Jan 2014 18:23:19 GMT
Client-Peer: 127.0.0.1:80
Client-Response-Num: 1
Client-Transfer-Encoding: chunked
Title: Welcome page
X-Varnish: 361868210

This little excerpt explains my experience with Magento 1.8 Community Edition. Although everything seems easy in theory; download, unzip the file, create a database and install the software, I had found it a bit a of a journey and experienced a lot of trouble shooting to get Magento to work as I had intended. 

The initial install went smoothly. But, as soon as I had got into the theming with the template the client had wanted, everything changed.

Backtracking, after you install Magento, you keep a key for safe keeping. The key sample is shown below.

Before you continue to your store, please make a note of your encryption key (Magento uses it to encrypt passwords, credit cards and more).

5e20757rrbcfe79fad6487cc0b0839a9

(Make sure you keep it in a safe place.)

Now that Magento seemed like a smooth, running machine, I installed the template as this tutorial explains.

After I had done that, I had various different password and admin issues for which I had to quickly solve my creating new users and updating passwords.

UPDATE admin_user SET password=CONCAT(MD5(‘zcmypassword’), ‘:zc’) WHERE username=’admin’

Installing with SSL seemed problematic, so, I decided to do it without and use a redirect later with .htaccess. At this point, I had done many installations.

After the template was setup, I inserted the ‘sql’ file into the database. The data needed a severe fixup. For one, the ‘core_config_data’ table needed proper named urls.
 
Also, the file ‘/home/username/public_html/app/code/core/Mage/XmlConnect/sql/xmlconnect_setup/upgrade-1.6.0.0-1.6.0.0.1.php’ needed to be renamed to ‘/home/username/public_html/app/code/core/Mage/XmlConnect/sql/xmlconnect_setup/upgrade-1.6.0.0-1.6.0.0.1.php_ renamed’. This file was really problematic and caused frontend and backend errors. But, after this renaming after the template installation I was at least able to see the frontend looking proper. Unfortunately, I had backend ‘logging in’ issues. To fix those issues, I altered the ‘app/code/core/Mage/Core/Model/Session/Abstract/Varien.php’ file like shown below.

 // session cookie params
        $cookieParams = array(
            ‘lifetime’ => $cookie->getLifetime(),
            ‘path’     => $cookie->getPath(),
            //’domain’   => $cookie->getConfigDomain(),
            //’secure’   => $cookie->isSecure(),
            //’httponly’ => $cookie->getHttponly()
        );

At this point, I was able to login to the backend end and thought I was home free. Well, all worked well until I tried to set up the Payment methods. When I tried to alter the payment methods, I was deficient in memory. Therefore, I had to login to the server and change the PHP memory to 64M in the file php.ini. Then, I was able to make these changes. I can only imagine many users on shared hosting that run into a wall here. I assume you could alter the database tables to work around changing these settings in the backend, if you really had to.

For testing and setting prices, you can set up sandbox mode. Now, you can add categories, products, etc and test the checkout.

Rarely, does a template display the modular blocks as you want. In this case, I disabled ‘Popular Tags’ and other unwanted default blocks from appearing in the sidebar.
The sequence to disable the ‘Popular Tags’:
System > configuration > advanced > disable Mage_Tag

Although I had thought I had the currency setup, I went to the sequence below to set Canadian dollars.
General > Currency setup > Set your currency

Below, is another example of removing unwanted sidebar blocks.
System >Advanced >Remove ‘Compare Products’

By default ‘Out of stock’ .. Needed to be changed I this or it won’t show up. Alternatively, you can set the managing stock option to ‘No’.

At this point, I was happy and thought I was in the clear… until the cart would not update properly or remove items in the cart.  I read through various forum posts and tried clearing the cache and clearing cache index data. But, this failed. I also tried the sequence below.
System >Cache Management >Select All >Enable > Submit
I also flushed the Magento cache. Still no luck.

With a little quick luck and research, I was directed to fix the template file shown below.
Go to app/design/frontend/default/my_template/template/checkout/cart.phtml

Change:
 <form action=”<?php echo $this->getUrl(‘checkout/cart/updatePost’) ?>” method=”post”>
        <fieldset>
Change to:
 <form action=”<?php echo $this->getUrl(‘checkout/cart/updatePost’) ?>” method=”post”>
    <?php echo $this->getBlockHtml(‘formkey’); ?>
        <fieldset>

After this change above, the checkout worked.

Now, I was a little concerned about the importance of the earlier login issue.
Therefore, I uncommented the varien.php file and checked if logging in to the backend worked, and it did.

File:
app/code/core/Mage/Core/Model/Session/Abstract/Varien.php

comment out
 // session cookie params
        $cookieParams = array(
            ‘lifetime’ => $cookie->getLifetime(),
            ‘path’     => $cookie->getPath(),
            ‘domain’   => $cookie->getConfigDomain(),
            ‘secure’   => $cookie->isSecure(),
            ‘httponly’ => $cookie->getHttponly()
        );

Styling

At this point, it seemed like most of the storm was over and I could get down to some basic styling; such as removing unwanted blocks.

The CMS tab allowed some quick, simple, styling options. For example, I quickly changed the footer with the click and command sequence:
CMS > Static Blocks >Footer Static >Customize or (display:none)

The system tab was also useful. The sequence I used is show below.
System >configuration >General >Design tab >Add keywords, change template links, etc

To change the home page title,
CMS > Select ‘Home page’ >Change ‘Page Title’ >Save

Taxes and Shipping

Finally, I was able to start playing with the taxes and shipping settings.

Make a tax rule like for a country, state or province.
Here is where you need to set the Customer Tax Class, Product Tax Class, Tax Rate

Make a tax class for each area.

Manage Tax Zones and Rates

Conclusion:
After going through the events described above, I was able to run the shop effectively. Setting up and editing products, prices and taxes worked as expected.


Cron Jobs With Ubuntu

With Ubuntu, you have a couple ways to setup cron jobs. You can run the ‘crontab -e’ from the command line or, you can edit the /etc/crontab file. The /etc/crontab file will run no matter which user is logged into the system. If you are a single user, keeping everything in this file is a valid option.

Making Cron Job

 root# cd /etc root# vi crontab or  username# crontab -e  

Sample Cron Job That Runs Every 5 Minutes

 */5 * * * *   username    /usr/bin/php -f /var/www/myhtml/filename.php 

Change All Permissions on File and Folders

Eventually, you may install a script that has a directory with multiple folders and files. Unfortunately, the files and folders had been installed with inadequate permissions. For example, you may want to set the permissions for all folders to 755 and the permissions for all files to 644. The code code below will demonstrate two simple Linux command line statements that can do this.

 root# find /home/user/public_html/mycrm/cache -type d | xargs chmod -v 755 root# find /home/user/public_html/mycrmr/cache -type f | xargs chmod -v 644 

Create MYSQL Trigger

MYSQL Triggers can be created in order to make an update on a database table only when a specific condition is met. With the code the code below, there are two columns in one table that can be cloned. For example, columnb can be a cloned copy of columna only when the date in the date column is in the future. Therefore, if the date is in the future for a specific entry and columna is updated; then columnb will be updated too. But, columnb will not update if the date column is in the past. 

DELIMITER //
 CREATE TRIGGER updatemytable BEFORE UPDATE ON tablename
     FOR EACH ROW
     BEGIN
     IF NEW.columna <> OLD.columnb AND OLD.date >= now() THEN
     SET NEW.columnb = NEW.columna;     
     END IF;
     END
     //    
mysql> DELIMITER;

Five Reasons To Use Virtual Machines Using Virtualbox or VMware

Virtual machines are operating systems that run through software which enables this to take place. For example, Virtualbox or VMware allows you to run other operating systems within its program while you are running your host operating system. The reasons why you would want to use Virtual machines can be long and exhaustive. But, this section will focus on five strong points for using virtual machines. Five reasons why you may want to run virtual machines are to try new operating systems, run old operating systems where your software is compatible or you have familiarity, easily backup and move custom setups to other machines and to run Linux and Windows (or mac and other OS) at once and testing software.

Try New Operating Systems
Within minutes, you can setup a new virtual machine and test out various operating systems. For Linux users, there are so many varied distros that you may want to have many virtual machines since they all have their strengths and weaknesses.

Run Old Operating Systems
You could need to setup an older operating system to run software which could have compatibility issues with your current software. Now, you have the option to take advantage of old and new software. Also, you may be lost with your new operating system. Therefore, running both can help you to be more efficient with your tasks.

Easily Backup and Move Custom Setups to Other Machines
So, you like to create custom setups and want them usable on other pcs. Backing up and cloning virtual machines is very quick and easy to do. In fact, you can backup 30GB virtual machines in a few minutes while saving them to an external disk for safekeeping can be done very quickly too.

Run Linux and Windows (or Mac and other OS) At Once
For many specialists like web developers, running Linux and Windows allows you to use both operating systems at once which is very convenient. You can easily flip back and forth between Linux and Windows. Personally, I like to run Windows software in Windows while using Linux virtual machines to build scripts which use both shell and php / mySQL programming.

Testing Software

For obvious reasons, using a virtual machine is a safer method to test software that is downloaded from the Internet.


Resizing and Increasing Ubuntu Disk Space With Virtualbox

So, you have spent hours and hours working with your Ubuntu Virtual machine to set it up just right. Meanwhile, your files and folders have grown to the point where you are running low on disk space. This should not have been a complete surprise since it probably has been a trend since you bought your first pc. Anyways, this post will help solve those issues and allow you to increase your disk space so you can move forward.

1) Make a clone.

2) Make sure you are not actively using the newly cloned virtual machine.

3) Increase disk space with the command prompt. This example uses Windows 7.

 a) Open the folder with the Change Directory (cd) command. View images below, if necessary. cd C:\Program Files\Oracle\VirtualBox  b) Run the VBoxManage file to resize the disk VBoxManage modifyhd "C:\users\ted\VirtualBox VMs\Ubuntu Resize Dec1\Ubuntu Resize Dec1.vdi" --resize 40000

 
 

4) Download the Gparted ‘Live’ iso. The file is about 165 MB. It can be downloaded here.

5) Add the Gparted ‘Live’ iso to the Controller: IDE list.

To add Gparted Live,
a) Select the clone > Settings > Storage > Under Controller IDE select ‘Add CD/DVD Device’ > Choose Disk >Select the Gparted live iso > OK.
Note: the disk size needs to be larger than the iso file. This example uses ~ 413 MB. See images below.

 

 
 

6) Start the virtual machine
Note: Gparted Live will boot
a) Select you language and all that jazz, Enlish may be somthing like 02 and your ‘GUI’ view may be something like ‘0’. Just hit ‘Enter’ on the keyboard after selecting your options.


Using Gparted

When Gparted opens, you will see the new unallocated space. In this case, 7.64 GB.

Now, here is where things get interesting because you want to increase the sda1 partition.

7) Increase the sda1 partition.

To increase the sda1 partition,

a) Delete the Logical partition (swap) > Select Apply. Make sure to run the operation.
b) Delete dev/sda2 extended partition from dev/sda > Select Apply. Make sure to run the operation.
c) Select partition /dev/sda1 >Resize / Move >
Note: Make sure to use all of the space. make sure to run the operation.


Altering the Virtual Machine Settings

8) Now, go back to your list of Virtaulbox machines and select your Virtual machine. In this example, the machine is called Ubuntu resize Dec1. Select ‘Settings’ >Storage and change Gparted from ‘Primary Master’ to something else. Change ‘VBoxGuestAdditions.iso’ to your ‘Primary Master’. The ‘Primary Master’ will be the iso which boots when you start a Virtual Machine. You want to start Ubuntu this time, not Gparted. Alternatively, you can remove gparted if you want.

9) See the new changes in disk space. When you boot into Ubuntu and open the terminal, type df -h and you should see the newly added hard drive space.

 

Using Rsync With Linux

Rsync is a very good package which allows use Linux users to synchronize files and folders on the same, or different machines. The concept behind Rsync is that is only updates files that have changed in date and file size. So, from a backup point of view, it can keep an accurate live backup when you run the command to synchronize the files.

Using Rsync On Same Computer

pi@raspberrypi$ rsync -avz /home/pi/test1/ /home/pi/test2/

Using Rsync On Different Computers

1) Generate SSH keys on the computer with the host(master) files
pi@raspberrypi$ ssh-keygen
Note: Do not set passwords for auto connections, but, you can if you want to be prompted for password
2) Move the id_rsa.pub file to the guest(slave) machine where you want the backups (ie. machine on local network). 
There are many ways to perform this task. The whole idea is that the id_rsa.pub file will end up as the authorized_keys files in the .ssh folder of the other machine.
Method A:
pi@raspberrypi$ ssh-copy-id -i ~/.ssh/id_rsa.pub pi@192.168.0.115:~/.ssh
Method B:
pi@raspberrypi$ scp ~/.ssh/id_rsa.pub pi@192.168.0.115:~/.ssh/authorized_keys
3) Login to the slave machine and change file permissions.
pi@raspberrypi$ chmod 600 authorized_keys
4) Use Rsync to create backups
pi@raspberrypi$ rsync -avz /home/pi/test1/ pi@192.168.0.115:/home/pi/test2/
Note: Rsync can be run manually or with a cron job that runs at your desired schedule.

Potential Problems:

Permissions. When you sync the files to the slave machine the folder should have adequate permissions. For example, if you login as pi@192.168.0.115 the files will transfer into the desired folder if the files or group is owned by pi. If you login as pi and attempt to move files into a folder owned by root, the sync will not happen.


Adding Aliases Into .bashrc

When you boot into your Linux OS, the .bashrc file, an others will load variables and aliases which can be used within the command line. There are many reasons why users will want to add variables and aliases. One of the main reasons why users want to take advantage of these aliases and variables is to cut down on typing. If you are a web developer, you may find you will have files nested inside many folders, since the default file directory is /var/www. If you like to create may projects, the directories can find a way to grow and grow.

To make an alias,

 user# alias mymaindir="cd /var/www/scrapers/website/" 

To make the alias usable without rebooting,

 user# source ~/.bashrc 

To navigate to your chosen directory,

 user# mymaindir 

Cost of a Raspberry Pi

Although Raspberry Pis might seem cheap to buy, the costs can add up by the time you add on various accessories. At the very least, you need a power supply, an SD card (hard drive) and an hdm1 cable. This brings the tally up to $70 or so; depending where you buy the supplies. After you have these basic supplies, you can can turn on your tv, start your pi and install an operating system on your SD Card. If you are lucky, you have a mouse and keyboard that is compatible with the Raspberry Pi. Otherwise, you will need a compatible keyboard and mouse which can run $20 and up. At least now, you are up and running anywhere from $70-$100.


No Internet?

The Raspberry Pi comes without Internet, so add on another $5-30 for an Ethernet cable. A cheap dollar store model is usually sufficient. A wireless usb dongle is another $15.

Conclusion:

By the time your Raspberry Pi is up and running, you can expect to pay somewhere around $100. As an owner of 3 Raspberry Pis, I still find them very useful for my intended purposes. They use very little power, take up very little space, make excellent storage devices and can run local php / mySQL scripts.

Would I buy 3 again? Yes.


Cloning Virtualbox Machine

Although Virtualbox allows you to build up your Linux distro, it offers so many more features.One of its great features is that is allows you to create clones. Essentially, cloning can be used as a backup mechanism for which to store copies of virtual machines. Therefore, you can easily save a machine that is detailed to your personal specifications, then, create a clone and experiment.

The image sequence below shows how to clone a virtual machine with Virtrualbox.

1) Select the machine you want to clone >Select ‘Snapshots’ >Click the sheep.

 

2) Name the backup.

 

3) Make a full clone.

 

4) Let it clone.

 

5) The new clone had been added and you can start it.

 

Migrating Website To New Domain Name

After days, months or years, you have finally come to the conclusion that you want to migrate your website to a new domain name. There are many reasons why you may want to do this such re-branding, recycling content, you need a name that reflects how the website has grown or you want to use a ‘new domain name’ that is easier to remember. Now that you have the plan, you must execute it. The move is rather quite simple and this procedure will work for any small or large php / mySQL website whether it was made with WordPress, Joomla, or a custom php / mySQL script. The process consists of five simple steps. The steps are to change the old domain name to the new one in all files, make the same name changes in the database, alter your database connection settings (if necessary), add a 301 redirect and resubmit new sitemaps.

1. File Name Changes

The first step is to do a ‘Find’ and ‘Replace’ for all occurrences of your old domain name in your files and replace it with the new domain name.

Method A
One way to do this is to ftp the files to your pc and use an editor that can search all files and folders for a specific string and replace it with the new one. For example, you search for example.com and replace it with example.net. In many cases, you can change everything at once. But, if you have large error_log files or lots of cache files it could take a while. You could remove all error_log files and cache files to save time, if necessary.

 
 


Method B

If you have Linux shell access, you can do a quick find and replace with the Linux command line. The example below will find and replace a string for all files within the directory. The example below will search for example.net and replace it with example.com. Be careful! If you screw up, you screw each occurrence up and need to fix it. However, this example shows hows effective command-lining can be. 

root# grep -rl ‘example\.net’ /home/username | xargs sed -i ‘s/example\.net/example\.com/g’


2. Database Name Changes

Changing the occurrence of your old domain to the new one is simple. You download an uncompressed sql file and load it in an editor. Then, you do a simple find for the old domain name and replace it with the new one. After that, you can import that database into a new or existing database.

3. Alter Database Connection

If you setup up a new database on a new account or a new host, you will have a different. You must change the old username and password with the new one. If you try to view web pages with invalid credentials, your browser will show you connection errors.

4. Add a 301 in your .htaccess File

The one line below can be added to your .htaccess file so that all old urls will point to the new ones. In other words, example.net will redirect to example.com and pages like example.net/wordpress_post will redirect to example.com/wordpress_post.

Redirect 301 / http://example.com/

5. Resubmit a New Sitemap to Google Webmaster Tools

Finally, login to your Google Webmaster Tools account and submit new sitemaps for the new domain.

Conclusion:

Out with the old, in with the new. All of your web pages that are indexed with Google (or any other search engine) will redirect to your new website. In time, your new content and old pages on the new website will be indexed. All in all, everything will go smoothly as though the move did not take place.

MYSQL Events

A mySQL event is the mySQL version of a Linux cron job. An event can be used to run a mysql query at a specified interval.The code below shows how to create an event called ‘update_log’ that will insert a row into the log table every 2 minutes.

mysql> CREATE EVENT update_log
-> ON SCHEDULE EVERY 2 MINUTE
-> DO INSERT INTO log VALUES(NULL, now());
mysql> CREATE EVENT update_log
-> ON SCHEDULE EVERY 2 MINUTE
-> DO INSERT INTO log (id, time) VALUES(NULL, now());

Creating MYSQL Stored Procedures With The Command Line

Stored procedures require a different set of methods from typical mysql queries, but, there are only a few which need to be implemented. For example, you need to create a procedure with ‘CREATE PROCEDURE’, you use ‘BEGIN’ and ‘END’ around the declared variables and mysql query and you declare and set variables. Finally, you use a delimiter so that mysql will run all of the code; rather than an execute when it sees a semi-colon(;). The examples below show how to make simple stored procedures.

Why use stored procedures?

Using stored procedures allows a programmer to create custom mysql queries that can be used throughout variious scripts without having to hard code each and every time time. Essentially, using stored procedures can reduce redundancy.

Example #1

DELIMITER //
CREATE PROCEDURE new_procedure()
BEGIN
DECLARE my_variable INT DEFAULT 0;
SET my_variable = 10;
select my_variable;
END //
mysql> DELIMITER ;

Example #2

DELIMITER //
CREATE PROCEDURE second_procedure()
BEGIN
DECLARE my_variable INT DEFAULT 0;
SET my_variable = (SELECT COUNT(*) AS cnt FROM at_admins)
select my_variable;
END //
mysql> DELIMITER ;

Example #3

DELIMITER //
CREATE PROCEDURE third_procedure()
BEGIN
DECLARE my_variable varchar(255) DEFAULT 0;
SET my_variable = (SELECT login FROM at_admins WHERE login=’admin’);
select my_variable;
END //
mysql> DELIMITER ;

The simple code below shows how you can call a stored procedure from a php script.

$command = “CALL new_procedure()”;
$result = mysqli_query($db, $command);

MYSQL Stored Procedures With phpMyAdmin

Creating stored procedures in mysql can be done with phpMyAdmin or the mysql console. Obviously, this particular example will be show how to make a stored procedure with phpMyAdmin.

The code below will create a new stored procedure called new_procedure. The ‘CREATE PROCEDURE’ statement will be on the first line. The second line contains the ‘BEGIN’. Then, a variable is declared using the ‘DECLARE’ statement. The declare statement includes the datatype and size, and a default value. In this case, we declare an integer with a default value of 0. The ‘SET’ statement gives the newly declared variable a value of 10. the ‘select my_variable’ is a typical mysql query.Finally, ‘END’ is used to complete the task. It is very important that the delimiter is blank before selecting ‘Go’. After everything looks good, select ‘Go’.

 
Here are 3 example sets of code for stored procedures.

CREATE PROCEDURE new_procedure()
BEGIN
DECLARE my_variable INT DEFAULT 0;
SET my_variable = 10;
select my_variable;
END;

CREATE PROCEDURE second_procedure()
BEGIN
DECLARE my_variable INT DEFAULT 0;
SET my_variable = (SELECT COUNT(*) AS cnt FROM calendar)
select my_variable;
END;

CREATE PROCEDURE third_procedure()
BEGIN
DECLARE my_variable varchar(255) DEFAULT 0;
SET my_variable = (SELECT title FROM calendar WHERE id=’3′);
select my_variable;
END;

To call a stored procedure, the statement call new_procedure() is implemented.

 
 

To view the stored procedure,

SHOW CREATE PROCEDURE new_procedure;  Note: You may want to select 'Print view' to see the details.


Virtualbox Linux File Backups

Using Virtualbox is a fantastic tool for which to write custom php / mySQL scripts, while making it easy to flip back and forth between some heavy duty Windows software like Pinnacle Studio, Camstasia, Adobe Captivate and Photoshop. However, you may want to backup some files on an external usb stick, hard drive or Raspberry Pi. Personally, I like a quick and easy backup device like a Raspberry Pi that is connected to the local network so I never have to plug any thing in. But, I also like my “Sacred Files” backed up outside of the home in case of fire and theft. Starting any long-winded project over is something you never want to do.

Moving on, here is a quick method for which you can store backups from your Virtual Machine. The sequence involves using a $35 Raspberry Pi which is connected to the router with an Ethernet cable. However, it would also work fine with a wireless connection.

To transfer the file(s) to a usb stick,

1) Move the file to another Linux operating system since it will have a different local area network address. The scp command is used below.
root# scp myfile.zip pi@192.168.0.130:/home/pi/my_backups

2) Open an ftp client in your Windows operating system.

3) Connect to the address of your Raspberry Pi. In this case, the address is 192.168.0.130. The default user for a Raspberry Pi is ‘pi’ and the default password is ‘raspberry’. Security minded people probably change the default password within minutes after an installation.
4) Use sftp or ftp and transfer the file to your usb drive.

You could make a zip or tar ball of a folder, scp the file to your Raspberry Pi and transfer them to your usb stick in less than a minute.

Alternatively, you could create a Samba server on a Raspberry Pi for which you can transfer files to and from the Samba server.
 


Virtualbox Screen

Virtualbox works very good if you add one or more virtual machines like Ubuntu, Centos, Mint, Puppy, Kali and Windows. Normally, a new virtual machine can connect to the Internet and be run in its own world. However, the time could come when you want to go back and for between you pc and the virtual machine, and, this includes copying and pasting files from one operating system to the other. Well, here is where ‘Guest Additions’ comes into play. ‘Guest Additions’ is included with Virtual box. Alternatively, you can download and install it with the Linux command line.Once you have ‘Guest Additions’ working, you can change the appearance of the screen and copy and paste text from your pc to the virtual machine. The ‘host’ key on your computer is the [right ctrl] key.

The commands below show how to change the appearance of your Virtualbox. Host F and Host L give nice, large screens. The default screen may be host C which may not be that desirable.

Host F Full Screen
Host L Seamless
Host C Scale Mode // default
Host G Auto Resize Guest Display
Host A Adjust Window Size

To copy and paste from pc to virtual machine,

1) Select Devices >Drag and Drop >Host To Guest
2) Select Devices >Shared Clipboard >Host To Guest


PHP Hand Coding Vs Coping and Pasting

If you are trying to learn a programming language and are wondering how about going about this ….. please read on. When you first try to learn a programming language, the syntax, built-in functions and loops can seem overwhelming. You may even ask yourself, “Am I supposed to know and remember all of this stuff?

The answer is yes and no. You should be able to do many tasks from memory; like querying a database, sorting loops and using functions. The more you practice, the more automatic this will become. If you try to copy and paste your way through programming, you could end up with a slower learning curve and a weaker knowledge base. If you have time and the opportunity to hand code at work or at leisure, take advantage of it.

With days, weeks and years of practice, the day will come when you can type out a relational mysql query using high performance joins with 4 database tables while a copy and paste programmer may be stuck writng good code because the coding process is not automatic. One of the keys to programming is to reduce or eliminate redundancy. Therefore, typing and enforcing propper coding practices on a ‘hand-coding’ level will leave you with very powerful skills that will make doing your tasks and custom applications a simple process.  


Using SSH Between Raspberry Pis

As your local network grows with the addition of new Raspberry Pis, you may want to keep your workload minimized by using SSH between Raspberry Pis. If you use SSH to connect from Pi to Pi, you can easily move files and program any Pi quickly and efficiently.

To connect to other Raspberry Pis with SSH, you will need to have SSH enabled. The simplest way to to enable SSH is to run the command ‘raspi-config’ from the command line. Then, simply select SSH and make sure it is enabled.

Once SSH is enabled, you can easily SSH into another Raspberry Pi on your local network. An example connection is shown below.


SSH Connection To Raspberry Pi

You have the Raspberry Pi with an installed operating system and it is connected to the Internet. In this case, it does not have a monitor you will use because you simply want to access and program it from the command line. Well, once you open Putty, you can connect and use the command line in less than a minute. The following steps will demonstrate this connection.

To connect to the Raspberry Pi,

1) Open Putty (putty.exe).
2) Add the local ip address assigned by your router.

 

3) Login as ‘pi’. This is the default use with the Raspian operating system.

 

4) Type your password and hit ‘Enter’ on your keyboard. By default, the password is ‘raspberry’. You may want to change it to something stronger than that.

 

5) Congratulations. You are logged in and can use the command line.

 

Create a USB Copy of Your Raspberry Pi SD Card Hard Drive

I will keep this blunt. This tutorial explains how to make a usable copy of the existing Raspian installation on your SD card. There are several reasons why you may want to do this operation such as; you want exact copies of your Raspian installation to use on other raspberry Pis, you want changeable installations on various usb drives and you want a backup in case your SD card malfunctions or becomes corrupted.

Once you have built a custom Linux installation, you can copy it to a USB drive and use it on your Raspberry Pi. To get started, all you need is a formatted fat32 USB stick.

To format the USB stick in Windows,

1) Insert the usb stick into a usb port.
2) Select Start >Computer.
3) Right click the usb stick
4) Select format >fat32
5) Safely remove formatted usb stick.

To format the USB stick in Linux,

1) Insert the usb stick into a usb port. If you use Raspberry Pi (Raspian), Ubuntu or another OS it should mount right away. Check to see where it is mounted.

 root@raspberrypi:/home/pi# df -h 

2) Unmount the usb stick. In this case, it is mounted on /dev/sda1

 root@raspberrypi:/home/pi# umount /dev/sda1 

3) Format it with fdisk command unless you formatted it in Windows. If you formatted it with Windows, skip this step.

 root@raspberrypi:/home/pi# fdisk /dev/sda1 

4) Format it for Ext4.

 root@raspberrypi:/home/pi# mkfs.ext4 /dev/sda1 

5) Mount the usb drive.

 root@raspberrypi:/home/pi# mount /dev/sda1 /media/usbdrive 

6) Use the ‘dd’ command to move the data to the usb drive.

Clone Raspberry Pi SD Card To USB
 

7) Resize the drive.These examples are show for the root user. To enable the root user on your Raspberry Pi or Linux, simply type ‘sudo -s’. Otherwise, you can always use the default user ‘pi@raspberrypi ~ $’ with sudo in front of the command.

 root@raspberrypi:/home/pi# resize2fs /dev/sda1 

On top of that, you may want to note that you can always open up the Linux package Gparted and show the usb device. Then, you can unmount it and resize the unallocated space to the desired partition.

8) Change this line to boot the usb next time the Pi restarts.

 root@raspberrypi:/home/pi# vi /boot/cmdline.txt 

or

 root@raspberrypi:/home/pi# nano /boot/cmdline.txt 

9) Change ‘root=/dev/root’ to ‘root=/dev/sda1’

10) You may want to make changes to the /etc/fstab file too. The code below will show to mount it upon boot.

 proc            /proc           proc    defaults          0       0 /dev/mmcblk0p8  /boot           vfat    defaults          0       2 /dev/mmcblk0p9 /                ext4    defaults,noatime  0       1 /dev/sda1      /media/usbdrive  ext4  uid=1000,noauto,user,exec   0       0 

Making a Static IP With Raspberry Pi

This tutorial explains how to create a static ip address for your Raspberry Pi.

The file for which you will edit is called ‘interfaces’ It is located within the /etc/network folder.

Why do I want to do this? There are many reasons why you may want to create a static ip address for a Raspberry Pi. Some of the reasons could be that you want to run a web site on a Raspberry Pi or run a cluster of Raspberry Pis. If you attempt to so this with dhcp, dynamic changing ips will make port forwarding and other setups a hassle that will need ongoing changes. Also, if you have several customized Raspberry Pis, you may like to ssh into any one of them with known ips in order to be efficient.

To access the interfaces file,

1) Open the file.

 root# cd /etc/network root# vi interfaces 
2) Alter the code to resemble the code displayed below. The top block of code shows a static ip connection while the second block shows code for a wireless connection and Ethernet connection using DHCP. By default, the second block of code is installed with a Raspian distro.  
 auto eth0 iface eth0 inet static address 192.168.0.118 netmask 255.255.255.0 gateway 192.168.0.1 

Creating Persistence On a Live Kali Linux Distribution

When you download and write a Live Kali linux distro to a usb stick, any changes you make will not be there the next time you boot the usb stick. However, you can add persistence to the installation if you want to build on to the installation, add and edit files and add databases. The following instructions and images will guide your through the steps that are required to create the Live usb distro with persistence.

To enable persistence for a live USB installation,

1) Download Kali Linux iso.

2) Download, install and open Win32 Disk Imager

3) Write the image to the usb stick.

4) Boot the live usb stick.

5) Open the terminal.

6) Run the command gparted

7) Create a new partition. In this example, a 16 gb usb is used. As you can see below, the installation used 2.35 gb and 12gb is unallocated. The primary partition that is used is sdc. The sdc partition is the usb stick. Sda and sdb partitions are on the physical hard drive. It is critical not to select the wrong disk or you could do serious hard drive damage.

As you can see, gparted shows sdc1 uses 2.35 GB. This ia a logical partition. The unallocated space will become the sdc2 partition. Partitioning always works in a numberical sequence.

 
2) Create the new partition.

 

3) Select the Ext4 File System and add persistence to the Label field. Make sure unallocated is selected.

 

4) Select ‘Add’.
5) You now see the new partition on the list.

 

6) Run the operation.

 

7) Select ‘Close’. Now, you see the new sdc2 partition added to the list and no pending operation.

 

Now, you need to open a terminal and add the following commands.

mkdir /mnt/usb
mount /dev/sdc2 /mnt/usb
echo “/ union” >> /mnt/usb/persistence.conf
umount /mnt/usb

What did those commands do? Firstly, you created a new directory that will be used to mount the sdc2 partition. Then, the sdc2 partition is mounted at the location /mnt/usb. The ‘echo’ command appends a new line of text to the persistence.conf file. Finally, the partition is unmounted using the ‘umount’ command.

Using A Live Persistent Kali Installation

Now, you can reboot your computer with your usb plugged. As you should know, the boot order should have usb preceding the hard drive. When Kali boots up, you can select from a list of option. But, you select the ‘Tab’ key on your computer, then the space bar, and finally type ‘persistence’.

 

Wireless Raspberry Pi

Your Raspberry Pi should easily connect to the Ethernet easily after you have Raspian or another distro setup on your SD card. However, using wireless could be simple, or it could take a little workover. This tutorial will show how to get that wireless internet working with a plug and play wireless adapter like ‘Ourlink’.

To enable wireless connection,

1) Open network-interfaces file

 
2) Navigate to the wpa_supplicant folder

 
3) Add your wireless network settings and save the file. Hopefully, one of the two codeblocks is sufficient for your connection to succeed.

 
Now, you can open your GUI, be connected to the Internet and surf websites.

Moving Files Within Your Local Area Network With Linux With SCP

You may have multiple computers being used at home or work and you want to easily move files between them. You could have laptops, desktops, Raspberry Pis or any combination of the three. The simple solution is to use the command ‘SCP’. The commands are shown below.

 

The image below is unnecessary. But, it shows what happens when you try to use the cp command between two different computers on the same network. CP is used to copy files with a single computer.


Testing Linux Distributions with Virtualbox

Virtualbox is free software from Oracle which can be downloaded and installed on Windows that can be used to run other operating systems.

1) Open Virtualbox.

 
2) Select ‘New’ >Give a descriptive name.

 
3) Set the memory limit.

 
4) Create a virtual hard drive.

 
5) Select a hard drive file type.

 
6) Choose a storage option.

 
7) Input the virtual hard drive space.

 
Running the Virtual Machine

1) Select the option you want to use >Click Start

 
2) Select an iso

 
3) Select ‘Start’

 

Operating System Specifics

At this point, you can install the operating system just as you would on a regular hard drive. If all goes well, you should be able to boot into your operating system of choice and run it. The Internet should work too. However, you may find that some operating systems, like Centos will need to make a small adjust in order for the Internet to work. For example, when you use Centos you may have to select ‘auto Eth0’ for the network connection.

Linux Live Distro

If you plan to use a ‘Live’ version of Linux, you can select the operating system (ie. Centos) >Settings >Storage >Select the ‘iso’ file >Select ‘Live CD/DVD’

 


Multiple Terminals With Ubuntu and Other Linux Distros With Terminator

Opening a terminal with Linux allows you to command to your heart’s content. But, you may find the day has come when using one terminal at a time is just not enough. There could be many reasons for this possibility such as; you are running an application like Gedit or Caffeine that is using a process for which you do not want to quit, you want to connect to other multiple Raspberry Pis(or pcs) on your network at the same time and run separate commands on each one, and the list goes on.

Well, look no further because Terminator can allow you to open as many terminals as you want.

Installing Terminator on Ubuntu / Debian Distros

 root# apt-get install terminator 

Installing Terminator on Centos

 root# yum install terminator 

Terminator Usage

After Terminator is installed, you can open it at the command line with the ‘terminator’ command, or search for the application with a gui and open it.

To create multiple terminals,
1) Right click on the terminal
2) Select ‘Split Horizontally’
Note: The new shell will be used with the same user. Therefore, if you initially split the screen under a username like ‘mike’, the new terminal will maintain that user. But, if you switch to root, the new terminals will be used with root.


How To Use and Setup Netbeans For PHP Programmers

Netbeans, is a free, PHP IDE editor which can be used to build simple and large php applications in Windows and Linux. The dual operating system is a real plus for those who go back and forth between Windows and Linux partitions on a regular basis. It can be downloaded from Netbeans.

Getting Started

After downloading and installing Netbeans, you can open it up and be up and running in no time at all. You can open and edit downloaded files on your pc and send them back with an FTP program like Filezilla or WS_FTP Pro., or use FTP (SFTP) with Netbeans. If you use SFTP (FTP) with Netbeans, you can synchronize files so that any changes you make on your local pc will be changed on the web server too.

 

 

Synchronizing Files

To synchronize files,
1) Select ‘Source Files’ > Synchronize

 

SFTP (FTP)

To setup FTP,
1) Select ‘Source Files’ > Properties >Run Configuration
2) Fill in the details (shown below)

 

SFTP (FTP) Connection Setup and Test Connection

To setup SFTP or FTP Connection,
1) Select ‘Source Files’ > Properties >Run Configuration >Manage
2) Create a new FTP or SFTP connection and add the details(shown below) >OK


SSH To Linux PC or Raspberry Pi From Ubuntu or Linux Distribution

Ubuntu, or another Linux distro makes it very easy to connect to another Linux box or Raspberry Pi from your pc, a Raspberry Pi, or a Linux live usb using ssh. If you have the adequate ssh client installed, and know the passwords, you can make connect to the other machine and take over with shell commands.

Install SSH Client On Ubuntu or Linux Distro

 root# sudo apt-get install openssh-client openssh-server 

Connect To Remote Linux Machine With SSH

This example demonstrates how quick and easy it is to connect to a Raspberry Pi using SSH. The computer doing the connecting is Ubuntu.

 root# ssh pi@192.168.0.102 pi@192.168.0.102's password:  Linux raspberrypi 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l 

Using Caffeine With Ubuntu or Other Linux Distribution

Caffeine is an application that can be used to ensure that your monitor stays active. Although you can disable the screen saver and sleep functionality, caffeine is still another option which you can use at your leisure. This way, you can open and use caffeine only when you want to make sure the monitor will not sleep and stays active. One instance you may want this to occur is for watching movies.

Install Caffeine

 sudo add-apt-repository ppa:caffeine-developers/ppa sudo apt-get update sudo apt-get install caffeine 

Activating Caffeine

 caffeine -p & 

Getting Started With Raspberry Pi Projects

The Raspberry Pi can be used to build many projects. This tutorial will show you how to get started with your Raspberry Pi so that you can begin to explore and create many projects of your own.

To get started with the raspberry Pi,
1) Format your SD card.
 

2) Download Noobs or a raw image from Raspberry Pi website. This example shows the setup with ‘Noobs’. 3) Extract the file and copy the contents on the SD card.

3) Connect your Raspberry Pi to a usb keyboard, a usb mouse and a tv with a HDMI connection.
4) Plug in your Raspberry Pi and install Raspbian. You can enable features like boot directly to desktop, enable ssh and more.
5) Connect an Ethernet cable to the Raspberry Pi if you want to connect to the Internet.


Using Vi / Vim With raspberry Pi

If you have used Ubuntu or Centos, you may find that the when you use ‘vi’, everything works as you expect right out of the box. However, this may not be the case with a Raspberry Pi. The good news, is that you can install vim and get to the zone for which you are seeking. Another option, is to use the Nano editor for which many online tutorials are based on. For others, Nano may not be preference for any one who prefers vi.

To install vim,

 root# apt-get install vim 

Now, you can use some favorite commands like :q, :q!, :wq and :w


Use Desktop or Laptop to Run Raspberry Pi

This simple tutorial will explain how to use your laptop or desktop computer as the monitor for your Raspberry Pi. In this example, it is assumed that you have a monitor connected to your Raspberry Pi. If you want to connect to a Raspberry Pi that is headless (no monitor attached), you can see go to this page.

Step #1 Install XRDP on the Raspberry Pi

 root# sudo apt-get install xrdp 

Step #2 Open Remote Connection
Option a) (Windows) Open Windows Remote desktop access Raspberry Pi

Option b) Use SSH(Putty) and install Xming in Windows. Then, connect to the internal ip, select x11 forwarding in Putty


Remote Desktop With Raspberry Pi Without Monitor Connected

Install tightvnc server on any Linux or Raspberry Pi and use VNC Viewer from personal computer. If you want to use a ‘headless’ Raspberry Pi, read on. If you follow the following instructions, you can connect to your Raspberry Pi and use your monitor will deliver the Raspberry Pi desktop, even though it has no monitor connected. At this point, you can surf the Internet with Midori, use Sketch, or open a terminal to run shell commands. If you have the Raspberry Pi connected to a monitor with HDMI cable, you can go to this page for other methods for which to connect remotely.

 root# sudo apt-get install tightvncserver 

Select ‘Y’ when necessary and be sure to remember your password, if necessary.

To run the VN/C server,

 root# vncserver :1 

On a separate Linux Desktop or Windows pc, download VNC Viewer at http://www.realvnc.com/

To use VNC Viewer,

1) Open VNC viewer
2) Insert network IP address and password and connect.

Lighttpd Server Setup On Raspberry Pi

You may want to install a Lighttpd server on a Raspberry Pi for many reasons. Some of the possible reasons are that you want to run a website from your home, you want to try out the Lighttpd Server, or, you want to test php scripts on your localhost.

Open your shell terminal and run the following commands to install the Lighttpd server with the ability to use php / mySQL.

Install Lighttpd
root# apt-get install lighttpd

Install PHP and MYSQL
root# apt-get install php5-common php5-cgi php5
root# apt-get install mysql-server mysql-client
Note: Hit enter on the keyboard when necessary

Enable Fast CGI Module
root# lighty-enable-mod fastcgi-php

Reload Lighttpd
root# /etc/init.d/lighttpd force-reload

Test server and php file
root# cd /var
root# mkdir www
root# chmod 755 www
root# cd /var/www
root# vi test.php 
Write a php echo statement save the file.


Test Server and File
Open http://192.168.0.109/test.php
Open in browser http://192.168.0.109


What is the Raspberry Pi

When you pass through a magazine store or browse the web, you may have come across the words ‘Raspberry Pi’. It is getting lots of attention. Being the owner of three Raspberry Pis, I will try to explain what it is. The Raspberry Pi is a microcomputer. This microcomputer is designed to use an SD card as its hard drive which runs a Linux distribution. If you browse enough websites and forums, you will see how popular ‘Raspbian’ is for the operating system of choice. This microcomputer comes with two usb ports, 1 ethernet connection, 1 HDMI connection (for tv or monitor) and a power connection (like a cell phone power connection).

This microcomputer can be used to browse the Internet and run shell command just like a computer that runs Linux, such as a desktop computer or laptop. However, the performance will not make you throw away your laptop and the Pi will not be a great option for everyday computer use. If the Pi is not a great computer and a usb stick allows me to test and run Linux on my computers, then, why on earth would I want a Raspberry Pi? Well, the Raspberry Pi can be used as a tool to test and work with home web servers or connect to hardware to output results. Here is where its strengths lie. They are excellent devices to test Linux software and applications; such as heartbeat and clusters and take up no space at all. As far as a web server goes, it can help someone make the transition from shared hosting to Linux Administration. If you can manage a server at home and use shell commands, you would be better off than just diving in to a VPS or dedicated server without any knowledge at all.

External Hardware

Many hobbyists use the Pi to connect hardware and sensors and sensors to pins which can be used to gather data with Linux programs. Then, another language like Perl, Python, or PHP / mySQL can be used to output that data.


Download a Single File From Web Server To Linux PC

The scp command in Linux is a fine way to download a file from a Linux Web Server. You can download a file if you know where it resides and you know the password for which to login. All you need to do is to login to the shell terminal with your pc. This example shows how it can be done with an Ubuntu PC.

The code below shows how you can download a tar file from the root directory on a Linux server to the desktop on a home PC running Ubuntu.

 root# scp username@example.com:/myfile.tar /home/username/Desktop 

Linux For PHP Programmers

If you plan to take your PHP / mySQL programming seriously, you will more than likely end up using the LAMP stack. LAMP stands for (Linux, Apache, PHP and MYSQL). Initially, you will need to use php and mySQL to make a database driven website. However, you should be very aware that these technologies are installed on Linux. If you use shared hosting, you will not have shell access and be able to alter and navigate the Linux file system. But, as your website(s) grow, you will eventually need a VPS or dedicated server. With a VPS or dedicated server comes responsibility. Here is where the more Linux you know, the better off you are. With knowing some Linux through practice, studying or certification, you will have much more control to knowing what is happening. In addition, Linux has various other programming languages for which you can write scripts to monitor your file system, or, add into your php scripts. Essentially, you can use shell commands, sed and awk in your php (if you really want to).

Linux Home Server

Asides from using a data center to host your websites, your Linux knowledge can extend into home usage. Linux variants like Ubuntu and Centos make great operating systems at home. In fact, you may find yourself spending more time on Ubuntu than Windows 7. Why? Linux can run much faster, boot much faster and you can create a home server to test files and even host a simple, lower traffic website. If you are familiar with Wamp (Windows, Apache, mySQL, and PHP) you may want to explore LAMP at home. Personally, I have found Lamp to be a much better experience to use than Wamp; especially using curl, pear extensions and adding custom extensions and software. Also, using Lamp at home will accelerate your knowledge for the Lamp you use with a VPS or dedicated server.

Ubuntu and Linux Tar Backups

As you may spend hours and hours configuring and setting your current installation, it is a good idea to make sure that you do not lose all that hard work and customization that enables you to use your Linux variant as you wish. There are many methods for which to backup your existing installation such as, making iso files, cloning the installation with Clonezilla and good old tar files.

The examples below show how to create backups of the entire file system or parts of the file system. If you are hoping to move a server to a new machine, you could clone the entire disk and make an iso file, or you could make a fresh installation and extract the tar ball and overwrite the files. Making tar backups is much faster and easier than making an iso, especially with a larger file system.

Tar Backups

Tar backups can be used to backup the entire file system “/” or various parts of the file system.

Backup the entire file system but do not include the tar backup file
root# tar cjvf ubuntu_backup.tar.bz2 --exclude=/ubuntu_backup.tar.bz2 .

Backup the file system but do not include some folders (Method A)
root# cd /
root# tar cjvf ubuntu_backup.tar.bz2 --exclude=/ubuntu_backup.tar.bz2 --exclude=/home/username/tunes --exclude=/media --exclude=/boot --exclude=/sys --exclude=/proc --exclude=/mnt /


Backup the file system but do not include some folders (Method B)
root# cd /
root# tar cjvf ubuntu_backup.tar.bz2 --exclude=ubuntu_backup.tar.bz2 --exclude=home/username/tunes --exclude=media --exclude=boot --exclude=sys --exclude=proc --exclude=mnt .

Checking Tar Backups

root# tar tjvf ubuntu_backup.tar.bz2 |less 
or
root# tar tjvf ubuntu_backup.tar.bz2 | grep etc |less 

To move the tar file, 
1) Copy and paste to usb .. or use ssh and scp the file to another machine.

Install PHPmyAdmin On Ubuntu

Install phpmyadmin

1) sudo apt-get install phpmyadmin
Select Y when necessary
Select Apache >Enter
Configure database for phpmyadmin with dbconfig-common? 
> Select Yes >Enter
Add passwords, or leave empty and click Enter
2) Open file /etc/apache2/apache2.conf
At the bottom add the line:
Include /etc/phpmyadmin/apache.conf
3) Navigate to /etc/phpmyadmin
change this line 
$cfg['Servers'][$i]['host'] = $dbserver;
to:
 :$cfg['Servers'][$i]['host'] = 'localhost';
to
Change
  $cfg['Servers'][$i]['controluser'] = $dbuser;
    $cfg['Servers'][$i]['controlpass'] = $dbpass;

to
  $cfg['Servers'][$i]['controluser'] = 'root';
    $cfg['Servers'][$i]['controlpass'] = '';

uncomment the line
//      $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
to
     $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Restart apache and open your page in a browser to a url like:
example.com/phpmyadmin

You should be able to login with root and no password. If you login and see the databases, that is a good start. But, the security needs fixing right away.

Comment the AllowNoPassword line.
//      $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Update your mysql root password
mysqladmin -u root password your-new-password
sudo /etc/init.d/mysql restart

Update a mysql user password:
SET PASSWORD FOR root@'localhost' = PASSWORD('password');

The mysql password is the one for which you will login to phpmyadmin. 

Disable root logins
$cfg['Servers'][$i]['AllowRoot'] = FALSE;


Create a new user in mysql
mysql> CREATE USER 'test'@'localhost' IDENTIFIED BY 'mypassword';
mysql> GRANT ALL PRIVILEGES ON * . * TO 'test'@'localhost';

To remove a user

mysql> DROP user 'test'@'localhost'

Using Squirrelmail With Ubuntu

Your home pc or home server running Ubuntu can easily be used to send email and run many web server applications such as phpMyAdmin and Squirrelmail. This tutorial will explain how to install and use Squirrelmail with Ubuntu.

1) root# apt-get install squirrelmail squirrelmail-locales
Type 'Y'
2) root# squirrelmail-configure
^C
3) root# ln -s /etc/squirrelmail/apache.conf /etc/apache2/conf.d/squirrelmail.conf

Restart apache 
root# /etc/init.d/apache2 restart

4) Check browser to see if login shows up:
http://localhost/squirrelmail/src/login.php
5) Open browser and run configtest to troubleshoot. Often, some things need to be changed.
http://localhost/squirrelmail/src/configtest.php

You may see errors and warnings such as;
'ERROR: Error connecting to IMAP server "localhost:143".Server error: (111) Connection refused'


root# apt-get install nmap
root# nmap localhost

root# sudo iptables -A INPUT -p tcp --dport (143) -j ACCEPT
root# iptables-save

root# sudo apt-get install dovecot-postfix

Run this again:
http://localhost/squirrelmail/src/configtest.php

You should see:
Congratulations, your SquirrelMail setup looks fine to me!


Try logging in:
If unsuccessful, you will need to change owners and permissions

root# chown daemon:daemon data
root:/var/lib/squirrelmail# chmod -R 777 data


root:/var/lib/squirrelmail# mkdir attachments
root:/var/lib/squirrelmail# chmod -R 777 attachments
root:/var/lib/squirrelmail# chown daemon:daemon attachments

Now, you need to have a non-root user that can login.

root# useradd myusername
root# passwd add_password_here

At this point, you can attempt a login. If anything fails, you can find the errors in the /var/log/mail.log file. One possible error could be that the user does not have the mail directory setup in the proper location. What the error below is attempts to explain is that it cannot create mail directory. The reason for that is because the there is no /home/myusername. Under some Linux conditions and distros, the folder is created automatically. In this case, it was not. 

Jul 23 11:09:59 NAME-VirtualBox dovecot: imap-login: Login: user=<myusername>, method=PLAIN, rip=127.0.0.1, lip=127.0.0.1, mpid=8117, secured
Jul 23 11:09:59 NAME-VirtualBox dovecot: imap(myusername): Error: user myusername: Initialization failed: Initializing mail storage from mail_location setting failed: mkdir(/home/myusername/Maildir) failed: Permission denied (euid=1001(myusername) egid=1001(myusername) missing +w perm: /home, dir owned by 0:0 mode=0755)
Jul 23 11:09:59 NAME-VirtualBox dovecot: imap(myusername): Error: Invalid user settings. Refer to server log for more information.

The code below shows how to setup the mail directory for a new user.The first step is to create the folder for the user and the second step is to create the folder for the email directory. After that, the permissions are set for that user.

root@NAME-VirtualBox:/home# mkdir myusername
root@NAME-VirtualBox:/home# cd myusername
root@NAME-VirtualBox:/home/myusername# mkdir Maildir
root@NAME-VirtualBox:/home# chown -R myusername:myusername myusername

At this point, you will like want to send email that is authenticated. In order to do this, you need to have the DNS for your domain name point to the IP at home. To make sure email is sent through a valid email address, add this line to the bottom of main.cf file.

smtp_generic_maps = hash:/etc/postfix/generic


After that, open and create the file /etc/postfix generic and add this line.

myusername@NAME-VirtualBox myusername@example.com

Now, you just need to reload the postfix service and you can send email. To receive email, you need to enable port forwarding on the router so that the local network ip of your machine or Virtual machine is forwarded through port 25.


Install Adobe Reader In Ubuntu

If you plan to use Ubuntu for many desktop and server applications, you will probably find the need to install Adobe Reader at some point in time. This simple installation can be done with the terminal in just a few seconds.

Installing Adobe Reader in Ubuntu From Command Line

 root# wget http://ardownload.adobe.com/pub/adobe/reader/unix/9.x/9.5.1/enu/AdbeRdr9.5.1-1_i386linux_enu.deb root# sudo dpkg -i name_of_package (ie. AdbeRdr9.5.1-1_i386linux_enu.deb) 

Using Squirrelmail With Ubuntu

Your home pc or home server running Ubuntu can easily be used to send email and run many web server applications such as phpMyAdmin and Squirrelmail. This tutorial will explain how to install and use Squirrelmail with Ubuntu.

1) root# apt-get install squirrelmail squirrelmail-locales
Type 'Y'
2) root# squirrelmail-configure
^C
3) root# ln -s /etc/squirrelmail/apache.conf /etc/apache2/conf.d/squirrelmail.conf

Restart apache 
root# /etc/init.d/apache2 restart

4) Check browser to see if login shows up:
http://localhost/squirrelmail/src/login.php
5) Open browser and run configtest to troubleshoot. Often, some things need to be changed.
http://localhost/squirrelmail/src/configtest.php

You may see errors and warnings such as;
'ERROR: Error connecting to IMAP server "localhost:143".Server error: (111) Connection refused'


root# apt-get install nmap
root# nmap localhost

root# sudo iptables -A INPUT -p tcp --dport (143) -j ACCEPT
root# iptables-save

root# sudo apt-get install dovecot-postfix

Run this again:
http://localhost/squirrelmail/src/configtest.php

You should see:
Congratulations, your SquirrelMail setup looks fine to me!


Try logging in:
If unsuccessful, you will need to change owners and permissions

root# chown daemon:daemon data
root:/var/lib/squirrelmail# chmod -R 777 data


root:/var/lib/squirrelmail# mkdir attachments
root:/var/lib/squirrelmail# chmod -R 777 attachments
root:/var/lib/squirrelmail# chown daemon:daemon attachments

Now, you need to have a non-root user that can login.

root# useradd myusername
root# passwd add_password_here

At this point, you can attempt a login. If anything fails, you can find the errors in the /var/log/mail.log file. One possible error could be that the user does not have the mail directory setup in the proper location. What the error below is attempts to explain is that it cannot create mail directory. The reason for that is because the there is no /home/myusername. Under some Linux conditions and distros, the folder is created automatically. In this case, it was not.

Jul 23 11:09:59 NAME-VirtualBox dovecot: imap-login: Login: user=<myusername>, method=PLAIN, rip=127.0.0.1, lip=127.0.0.1, mpid=8117, secured
Jul 23 11:09:59 NAME-VirtualBox dovecot: imap(myusername): Error: user myusername: Initialization failed: Initializing mail storage from mail_location setting failed: mkdir(/home/myusername/Maildir) failed: Permission denied (euid=1001(myusername) egid=1001(myusername) missing +w perm: /home, dir owned by 0:0 mode=0755)
Jul 23 11:09:59 NAME-VirtualBox dovecot: imap(myusername): Error: Invalid user settings. Refer to server log for more information.

The code below shows how to setup the mail directory for a new user.The first step is to create the folder for the user and the second step is to create the folder for the email directory. After that, the permissions are set for that user.

root@NAME-VirtualBox:/home# mkdir myusername
root@NAME-VirtualBox:/home# cd myusername
root@NAME-VirtualBox:/home/myusername# mkdir Maildir
root@NAME-VirtualBox:/home# chown -R myusername:myusername myusername

At this point, you will like want to send email that is authenticated. In order to do this, you need to have the DNS for your domain name point to the IP at home. To make sure email is sent through a valid email address, add this line to the bottom of main.cf file.

smtp_generic_maps = hash:/etc/postfix/generic

After that, open and create the file /etc/postfix generic and add this line.

myusername@NAME-VirtualBox myusername@example.com

Now, you just need to reload the postfix service and you can send email. To receive email, you need to enable port forwarding on the router so that the local network ip of your machine or Virtual machine is forwarded through port 25.


Cloning With Clonezilla

Clonezilla is free software that can be used to make a cloned image (iso file) of your pc. After you make the clone, it can be used to replicate other installations on other pc and be used as a backup.

Clonezilla can be downloaded from clonezilla.org. Then, you can make a live cd or usb for which you run at boot time when you want to make your clone.

Key Points To Remember

1. When you make a a clone with Clonezilla, the first disk options you select will be the destination disk where you want to save the clone. The second option will be to select the source disk you want cloned . making a mistake here can destroy your data.

2. When you restore a clone with Clonezilla, your first selection will be to select the disk which holds the iso image. Your second option will be to select the disk where you want to add the cloned image.

Cloning USB Hard Drives With Clonezilla

After you boot from CD or usb with Clonezilla, you can insert two usb drives into other usb ports. One usb will be the iso file and one will be formatted and blank. Then, you just go along with Clonezilla instructions and clone one usb drive to another usb stick. This method can be used to clone persistent Linux installations from usb to usb. In fact, you can set up a server, a website and an email server on a usb stick. This is no way to host a website, but, it is a simple and cheap method to experiment with Linux installations on disk.


Linux Home Server

Setting up a ‘Linux Home Server’ requires using a Linux installation of choice. You can use a distribution like Ubuntu, Centos, Mint, Fedora, Debian, Puppy, etc. Regardless of which distribution you decide to use, you will need Apache, mySQL and PHP installed on the system. Then, you can alter and a few files within your installation. Finally, you need to configure your router and set up a dns zone which will point to your IP address. Then, when someone looks up example.com, they will find your website. A Linux home server may not be the best solution to host multiple websites, but, it can be a great testing ground or remote streaming video source.

Ubuntu Home Server Setup

Centos Home Server Setup

Centos Home Server Setup

A Centos Linux Home Server can easily be built after installation. Using Centos as a Linux Home Server is an excellent option because it is free and it is commonly used for web hosting. Based on Red Hat, Centos is the Linux variant which can run Cpanel at hosting data-centers. Therefore, using it will help you be familiar with its file system. Since Linux file systems vary from variant to variant, using Centos at home can make using command lines and running a VPS or dedicated server much easier. This tutorial will explain how to turn the newly installed Centos Installation into a home server which can host a website like example.com.

Install Apache, mySQL and PHP

4) Install mySQL.
a) $ yum install mysql-server mysql php-mysql  
b) Select Yes(y) when necessary.

b) /etc/init.d/mysqld start

5) Login to mySQL to check it out
a) # mysql > Enter
Now, you have access to the mySQL console and can create and edit any database.
b) To leave mySQL type:
mysql>exit

6) Install php
a) #yum install php
a) Select Yes(y) when necessary

7) Restart the Apache service.
a) # service httpd start 



[root@livedvd local]# cd /etc/httpd/conf/httpd.conf
Open the file in text editor and scroll to the bottom
Add: Include conf/conf/*.conf

[root@livedvd conf]# mkdir conf
[root@livedvd conf]# ls
conf  httpd.conf  magic

open conf/example.com.conf

<VirtualHost *:80>
        ServerName www.example.com
        ServerAlias example.com *.example.com
        DocumentRoot /var/www/example.com

        <Directory “/var/www/example.com”>
                Order allow,deny
                Allow from all
        </Directory>
</VirtualHost>

Set the dns to point to your ip. You can do this with an online hosting account or free service like free dns. 

[root@livedvd www]# cd /var/www
[root@livedvd www]# mkdir example.com
[root@livedvd www]# ls

Just add an index.html or index.php file to the folder and open the website in the browser. You should see your website hosted from home.

Ubuntu Home Server

An Ubuntu Linux Home Server can be built with the server or home edition. Using Ubuntu for a Linux Home Server is an excellent option because it is free, the support and documentation is very good and updated and in general, it performs well. Furthermore, Ubuntu is such a good desktop operating system that using it as a server at the same time can offer the best of both worlds.

Install php and mysql

user# sudo -s

For all installations, type 'Y' when necessary
root# apt-get install mysql-server mysql-client
root# apt-get install apache2

root# apt-get install php5 libapache2-mod-php5
root# /etc/init.d/apache2 restart

Restart server and set the config to restart automatically (often, this is already the default setting). 

Router Port Forwarding for your IP
Test your ip in browser.

Create a DNS zone for which the website points to your ip. Set the dns to point to your ip. You can do this with an online hosting account or free service like free dns.
 

 
root# /etc/apache2/apache2.conf
Open the file in text editor and scroll to the bottom
Add: Include conf.d/sites/*.conf

Make a new folder called sites
Now, open the directory /etc/apache2/conf.d and make a file for your website. For example, for the website example.com I will call the file example.com.conf. It is a good idea to give the file the same name as the top level domain since it is unique and you will be well organized.

root# vi example.com.conf

Add a virtual host entry to the file:

<VirtualHost *:80>
        ServerName www.example.com
        ServerAlias example.com *.example.com
        DocumentRoot /var/www/example.com

        <Directory “/var/www/example.com”>
                Order allow,deny
                Allow from all
        </Directory>
</VirtualHost>

Now set up the folder for the site example.com
open /var/www/
root# cd /var/www
root:/var/www# mkdir example.com
Copy the original index.html file from www/index.html to www/example.com/index.html
root# cp index.html example.com/index.html
Edit the example.com/index.html so that you know it comes from this directory. Just add a simple line like "This is from example.com"


Access your firewall in browser (ie 192.168.0.1)
Select advanced > allow port 80 with tcp

Install Clamav (Clam Antivirus) On Ubuntu

This short, simple tutorial will explain how to install and use Clamav with Ubuntu.

To install Clamav,

Install Clam AV
root# sudo apt-get install clamav
Install Clam AV Automated Package
root:# sudo apt-get install clamav-daemon


Clam AV Usage


To use Clamav, 

1) Open the terminal
2) Run a scan
Scan the home directory and recursive files and folders.
root# clamscan -r /home
Scan everything
root# clamscan -r /

Output Sample:

----------- SCAN SUMMARY -----------
Known viruses: 2304039
Engine version: 0.97.8
Scanned directories: 29545
Scanned files: 111854
Infected files: 0
Total errors: 18080
Data scanned: 3206.81 MB
Data read: 6249.99 MB (ratio 0.51:1)
Time: 307.823 sec (5 m 7 s)
root# 

Clam GUI

If you want a gui for Clam you can download it from sourceforge. The current download url is http://sourceforge.net/projects/clamtk/files/ClamTk/4.44/clamtk_4.44-1_all.deb/download.

To install the gui tool,

1) Download the file and save it.
2) Open the terminal.
3) Go to the download folder.# cd /home/user/Downloads
4) Run the command for the specific version:
root# sudo dpkg -i clamtk_4.44-1_all.deb

Install Universal Firewall GUI For Ubuntu

With Ubuntu, the Universal Firewall(ufw) is install by default. You can run the command sudo ufw status to check it out. It is most like disabled.

If you want a simple gui for basic firewall rules, you can install the gui version ufgw. However, you need to have the the Universe repository enabled in order to install ufgw, which could be enabled by default. To install ufgw,

1) Open the terminal: 
2) Run the command: sudo apt-get install gufw 
3) When necessary, select 'Y' to complete the installation.

To use the Firewall and make rules,

1) Open System Settings >Firewall Configuation  or  Dash Home >Look for gufw >Select Firewall Configuration 
2) Make rules. The image below shows a simple rule to allow incoming traffic to receive http requests from port 80; the web server.

Centos Install PHPMYADMIN

1) Download from phpmyadmin website
2) Extract the file from the directory (such as /tmp directory) 
tar xvjf file.bz2
3) Rename the phpmyadmin folder after it is extracted
root# mv phpMyAdmin-4.0.0-all-languages.tar.bz2 phpmyadmin
4) Move the phpadmin folder to the /var/www/html folder, or, your virtual host folder such as a website called example.com. If you have a single website it will be in the html folder.
5) Open the phpmyadmin folder 
cd phpmyadmin
6) cp config.sample.inc.php config.inc.php

If mysql has no root password, you can 
change
$cfg['Servers'][$i]['AllowNoPassword'] = false;

to
$cfg['Servers'][$i]['AllowNoPassword'] = true;
But, that is a security risk.

You can alter the root password by logging into mysql and changing it.

 

[root@livedvd phpmyadmin]# mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.1.69 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> update mysql.user set password=PASSWORD('newpassword') WHERE user='root';

# service mysqld restart


Login to phpmyadmin
Look for errors and fix 
ie)
The mbstring PHP extension was not found and you seem to be using a multibyte charset. Without the mbstring extension phpMyAdmin is unable to split strings correctly and it may result in unexpected results.
The mcrypt extension is missing. Please check your PHP configuration.

How To Install Linux On Partitioned Hard Drive

A Linux distribution can be installed directly onto a hard drive or it can be installed on a partition on the hard drive. When you partition a hard drive, you can have have the option to run either operating system when you boot the computer. The software EASEUS can be used to partition a hard drive with Windows for which the new partition can be used to install Linux. The key to partitioning a hard drive with EaseUS is to make the Linux partitions with the type ‘Ext 3’.

When you create the partition, the new Linux partition must have a status as ‘active’ and the type is ‘primary’. After you have created the partition you reboot the computer. The bios boot order should start with your installation media; such as cd or usb. Upon reboot, you will follow the simple Linux installation instructions. The only part that may need some tweaking is making sure the root ‘/’, boot and swap partitions are properly created and named.

Partitioning Tips For Linux
When you partition a hard drive to install Linux, you will need to make 3 ‘Ext’ partitions. The partitions can be made with EaseUS or they can be created when you install the iso image on the computer. One will be the large ‘root’ partition which will have the mount point ‘/’. Another partition will be the ‘boot’ partition’ that will have the mount point ‘boot’ and it will be about 200 mb in size. The final partition will be the type ‘swap’, and it should be twice the size of your computer’s memory. For example, a computer with 4gb of memory will have 8-9 GB of swap. If ou do not have the three partitions created, you will be prompted during installation that you must have them. Therefore, if this is the case, you simply create them.

Post Installation
After Linux is successfully installed, you reboot your computer (without the media installation disk or usb stick). You will be able to select your operating system of choice.


Linux Find Files Based On Size

This example will demonstrate how to find files that are larger than a specified size. The example below will find files in the home directory which are larger than 20mb.

 root# find /home -size +20480k -print 

Find Files On Linux System Within A Timeframe

This tutorial will list files on your Linux system within a specific date range.

List Files Within 1 Day

 root# find . -type f -mtime -1 
 root# find /myfolder -type f -mtime -1 

List Files More Than 1 Day Old

 root# find . -type f -mtime +1 
 root# find . -type f -mtime +1 
 root# find /home/user/public_html/example.com/myfolder -type f -mtime +1 

Find Data Within Files In Linux and Centos

This tutorial explains how to find list all files and directories on a Linux system that have a string of text within the name. The example below is looking for files or folders with database_connect in the name.

Find Text Within The Files and Folders

 root# find /pathtofiles -name "database_connect*" 
 root# find /directory | grep "database_connect" 
 root# find . | grep "database_connect" 
 find /home/username | grep connect 

Find Data Within Files In Linux and Centos

This tutorial explains how to find data within files on a Linux system.

Find Text Within

 root# find /pathtofiles | xargs grep "username" 

How To Remove An Ip Address With A Linux Device Like eth0 or eth1

This basic set of instructions can be used to remove an ip address of a device on your Linux system.

Show IP addresses.

 root_user# ip addr show eth0   

Remove the undesired ip.

 root_user# ip addr del 192.168.0.1/21 dev eth0 

Find Word Count of Linux Files

Using SSH, you can find the word count of one or more files.

Word Count of A Particular File

 # find . -name 'edit.php' | xargs wc -w   99 ./mobilesite/forms/system/scaffolding/views/edit.php  383 ./blogger/edit.php  164 ./edit.php  646 total 

Word Count of All PHP Files

 # find . -name '*.php' | xargs wc -w  or # find . '*.php' | xargs wc -w 

Total Word Count of All Files

 find . -type f -print0 | xargs -0 cat | wc -w 

CentOS Linux Live DVD with Server Running Apache, PHP and mySQL

When you use a Linux Live DVD like CentOS 6.3, you can easily setup and modify the Linux installation to suit your needs. However, the Live DVD or Live CD will not save any changes that are made because Live CDs or DVDs run on a virtual disk drive in memory. The benefit of using a Live installation is security against malware and its portability.

Nevertheless, you can easily take a Linux Live DVD like Centos and setup php / mySQL in minutes. Then, you restart httpd and you have a functioning localhost to test php / mySQL scripts. This tutorial expklains how to use a Live DVD to create and test php / mySQL scripts.

To install and use php / mySQL with Centos Live DVD,

1) Open the console (Applications>System Tools>Konsole)

2) Change user to root
    Type:
a) $ sudo passwd root
b) Add password and verify
c) $ su – root
d) Give Password > Click Enter

4) Install mySQL.
a) $ yum install mysql-server mysql php-mysql  
b) Select Yes(y) when necessary.

b) /etc/init.d/mysqld start

5) Login to mySQL to check it out
a) # mysql > Enter
Now, you have access to the mySQL console and can create and edit any database.
b) To leave mySQL type:
mysql>exit

6) Install php
a) #yum install php
a) Select Yes(y) when necessary

7) Restart the Apache service.
a) # service httpd start

8) Type: localhost in a browser to see a test page.

9) Use Vi or Nano to create files and store them in the www folder. For example, the file test.php in the ww folder can be viewed in Firefox with http://localhost/test.php
To create a php page,
a) # cd /var/www/html
b) nano test.php

Linux How To Install Sudo

Sudo ‘Super User’ can be installed with Yum. The process to install sudo is shown below.

 root# yum install sudo 

You will be prompted to install. Select y and click ‘Enter’ on your keyboard.

 root# sudo whoami root 

From Centos Gnome To Console

 Ctrl + Alt + f2

From Centos Console To Knome

 Ctrl + Alt + f7 

Move Files With Linux mv command

Unlike the cp command, the mv command moves a file and the original file gets removed.

Moving a File
The command below will move the file from the current working directory into the username folder which is located within the home directory. 

 root@vps [/]# mv newtest.txt /home/username/ 

Copy Files With Linux

The ‘cp’ command can be used to copy files from one location to another. After a file is copied, there is the original file and the copied file.

Copying a File
The code below will copy the index.php file from the user directory into the current working directory which is user2

 root@vps [/home/user2]# cp /home/user/index.php ./  

Copying a File To a New Name
The code below will copy the oldfile file to a file named newfile

 root@vps [/home/user2]# cp -r oldfile newfile  root@vps [/]# cp -r newtest.txt newtest2.txt root@vps [/]# ls   

Both files newtest.txt and newtest2.txt now exist.

Linux Vi Editor Basics

Using the Vi Editor that comes with various Linux distributions is one of your options to create, edit and save files. Two other popular editors are Nano and Pico. Nano and Pico usage are almost identical, while Vi usage is different. This tutorial and listings of commands is for the Vi editor. Opening Vi Editor and Insert Mode

 root@vps [~]# vi newfile Here is my new text ~ ~ ~ -- INSERT --

Exit Insert Mode and Enter Command Mode

1) Press 'Enter' and go to a new line 
2) Press 'Esc' on the keyboard

Exit Command mode and go to Insert Mode

 1) Press 'Insert' on the keyboard

Navigating the Vi Editor

 1) Use the arrow keys.

Saving Files and Quitting the Editor In Command Mode

To save a file and quit in command mode, 
1) Type: :wq  

To save a file to another name, 
1) Type: :w newfilename  

To quit the vi editor, 
1) Go to command mode. 
2) Type:  :q or :q!

For more commands and usage, a Vi cheatsheet can be found here.


Terminate a Linux Command

Sometimes, during testing or typos, Linux will hang up and it will seem as though you are stuck. At this point, you probable just want to return to the prompt.

The ^C command allows you to stop the command and return to the prompt. However, if you are using an editor like Nano or Pico, you will need to exit the editor with the appropriate commands like ^X.


Linux Job Control

The jobs command can be applied to see which jobs are executing in the Linux shell.

 root@vps [~]# jobs [1]+  Stopped                 cat 

Linux Piping Output With Grep

Using the pipe operator ‘|’, you can send data from program to another. This example will show how to search for all files with ‘test’ in the name. It returns the names latest, test2.txt and test3.txt.

Search the current directory for files with the string ‘test’

root@vps [~]# ls | grep test
latest
test2.txt
test3.txt
root@vps [~]#


Searching A Single File for a String

root@vps [~]# grep "kent" newfile.txt
My name is kent.
root@vps [~]#


Searching All Files for Strings

root@vps [~]# grep -r "kent" .
./.bash_history:ls | grep kent
./.bash_history:grep kent newfile.txt
./.bash_history:grep kent ls
./.bash_history:grep -r kent
./.bash_history:grep -r "kent"
./newfile.txt:My name is kent.
root@vps [~]#

Standard Output With Linux

Linux uses three standard program communication streams; STDIN, STDOUT and STDERR. The three streams represent standard input, standard output and standard error. The tutorial will detail standard output.  

With Linux, you can create a new file with an editor, or, you can redirect output into a file.

 Nano Sample

1) Create the file with nano
root@vps [~]# nano myfile.txt
2) Write text
3) Save file
^O
4) Exit nano
^X

 Standard Output Method To Create a File

1) Use > to redirect output to a file called myfile.txt
root@vps [~]# echo "New text goes here" > myfile.txt

Furthermore, with output streams, you can run a Linux command and output the results into a file

Sample #1
1) 
root@vps [~]# echo $PATH > test2.txt
root@vps [~]# cat test2.txt
/usr/local/jdk/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/root/bin

Sample #2
root@vps [~]# ls -lt > test3.txt
root@vps [~]# cat test3.txt
total 4576
drwxr-x--- 15 root root    4096 Dec 25 08:25 ./
-rw-r--r--  1 root root       0 Dec 25 08:25 test3.txt
-rw-r--r--  1 root root     157 Dec 25 08:23 test2.txt
  Adding Standard Output to a File
To add a new lines to a file,
1) Type the following commands.
root@vps [~]# echo "New line" >> test2.txt
root@vps [~]# cat test2.txt
/usr/local/jdk/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/root/bin
New line
root@vps [~]#

Linux which rm

The command below uses which rm to find the location of the nano editor.

 root@vps [~]# which rm nano /usr/bin/nano root@vps [~]# 

Note:
The editor is located in the bin folder.


Aliases With Linux

Linux allows you to create aliases for commands. In this example, we will make an alias called md which can be used to run the mkdir command. If you run the command below, you will set an alias, create a new directory and see that the new directory was actually created.

 alias root# md="mkdir" md test_directory ls -l 

Linux Environment Variables

Linux has many environment variables. A few worth remembering are pwd, path, PS1, USER and VISUAL. These environment variables can be used during each session. Alternatively, you can create environment variables which will last for your SSH session.

Using Environment Variables

root@vps [~]# echo $PATH 
/usr/local/jdl/bin:/usr/kberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/X11R7/bin:/root/bin 

root@vps [~]# echo $USER 
root 
root@vps [~]# echo $VISUAL 
pico

Creating Environment Variables

root@vps [~]# VAR="Hello" 
root@vps [~]# export VAR 
root@vps [~]# bash 
root@vps [~]# echo $VAR 
Hello

ls Linux Command

The ‘ls’ command is one which gets used quite frequently. The ‘ls’ command is used to display files. There are many ways for which you can display files; such as ls, ls -l , ls -a, ls a* and ls -lt.

ls (lists one file for each row)

root# ls 
file1 .file2

ls -l (lists a long output with file permissions, date and file size)

root# ls -l -rw-r--r--  1 root root   38473 Feb 22  2012 memcached-2.0.0b2.tgz -rw-r--r--  1 root root   38473 Feb 22  2012 memcached-2.0.0b2.tgz.1

ls -a (lists all files including hidden files)

root# ls -a 
file1 .file2

ls -a (lists all files beginning with a)

root# ls a* 
afile .afile

ls -lt (lists all files with long output ordered by date desc)

 root# ls -lt drwxr-x--- 15 root root    4096 Dec 24 22:28 ./ -rw-------  1 root root   17386 Dec 24 09:14 .bash_history

Shell Variables and Linux

With the shell you can define your variables. When you define the variable, it is convention to use capital letters. When you want to use the variables, you add a ‘$’ in front of the variable name. You can use variables within double quotes, but, not within single quotes. In addition, you some characters cannot be used within double quotes since they take on a different meaning. Fore example, ‘!’ cannot be used within double quotes.

Declaring the Variable

 root# VAR="Hello World"

Printing the Variable

root# echo $VAR Hello World 
root# echo "$VAR" Hello World

Changing the Linux Root Password

Changing the Linux root password can be done with a GUI like Web Host Manager, or, it can be done with SSH. The code below shows the simple procedure to change the password with the shell.

root# passwd
Changing Password for user root.
New UNIX Password: Add_PASSWORD_HERE (Click Enter)
Retype new UNIX password: RETYPE_PASSWORD_HERE (Click Enter)
passwd: all authentication tokens updated successfully.

Using Linux With SSH

When you have root access to your Linux hosting account, you have so many extra features that are not available with shared hosting. One of the major features is SSH access with a tool like Putty. With SSH acccess you can literally connect fromm any computer on the Internet and do whatever you want to your website. You can create, edit and delete files, reboot the server, have acomplete access to all mysql databases, and much much more.

Knowing how to navigate at the Linux root can allow you to work on a website with no extra tools. Unlike a typical pc where you need FTP software and an editor, using SSH can be your final safety net if you need to use that. Imagine going on vacation in Cancun and you lose your laptop, or it fails. If you can access your Linux server wuth SSH, you can be back to work at the nearest Internet connection.

Logging In With SSH

Putty is a simple tool which can be used to connect to the server with SSH. The tool is free to download.

To login with SSH,
1) Open Putty

To view files in the folder

To view files within a folder,
1) Use the ls command.

Current Directory

To view the current directory
,
1) Use the pwd command.

Changing Directories

To change directories
,
1) Use the cd command.

Editing and Creating Files

To view a file(but not edit),

root@vpscat [/home/user]# cat filename.txt

To view and edit a file,
1) Open nano or pico editor
2) root@vpscat [/home/user]# nano filename.txt
3) Use arrow keys to navigate.
Note: If you already have a file with Nano it opens up the file. Otherwise, the command nano filename.txt will open a blank screen and you can make the new file called filename.txt.

To save a file edited or created with Nano or Pico,
1) Click Ctrl + O on the keyboard
2) Click ‘Enter’ on keyboard

To exit Nano or Pico,

1) Click Ctrl + X on the keyboard

Removing Files

To remove files,

1) Use the rm command.
root@vpscat [/home/user]# rm filename.txt
2) You will be prompted ‘rm: remove regular file ‘filename.txt’ ?
3) Answer ‘yes’ or ‘no’
3) Hit Enter on the keyboard.


Exit SSH

To exit SSH,
1) Type: Exit
2) Hit ‘Enter’ on your keyboard.


Making SSL Certificates With Cpanel and Web Host Manager(WHM)

When you want to add a SSL certificate to your website using Cpanel or web Host Manager(WHM), there are a few key points to remember. The two main points are the key and the actual SSL certificate. The two go hand in hand because the key on the web hosting account is used to create a matching SSL certificate. Then, the certifcate from the SSL company is added to your hosting account to finalize the match on the server.

In the end, the company where you buy the SSL certificate will ask for a key that was generated from your Cpanel or WHM. Then, they give you a certificate which can be used to update your key on yopour server. Now, both your SSL provider and your server have details for the key and SSL certificate. That is the main details which will deploy a usable SSL certificate.

With Web Host Manager or Cpanel, you can create SSL certificates.  

Cpanel

To add an SSL certifcate to Cpanel,
1) Make sure the Cpanel account has its own dedicated ip address.
2) Select SSL TLS Manager
3) Select ‘Generate, view, or delete SSL certificate signing requests’. You will add your domain name and some other required fields like city, state and country.
4) At the bottom look for Generate.
5) Select Generate.

 
At this point, you will have a RSA PRIVATE KEY and a CERTIFICATE SIGNING REQUEST(CSR). The company where you buy your certificate will ask for one of the two code blocks. For example, a company like Namecheap may want the CSR while Godaddy could request the PRIVATE KEY.

The CERTIFICATE SIGNING REQUEST(CSR) will have a block of code that the resembles the block of code shown belown.

Certificate Signing Request

 -----BEGIN CERTIFICATE REQUEST----- MIICrDCCAZQCAQAwZzEhMB8GA1UECgwYQm9oZW1pYSBXZWJzaXRlIHNlcnZpY2Vz MQ8wDQYDVQQHDAZTYXZvbmExCzAJBgNVBAgMAkJDMQswCQYDVQQGEwJDQTEXMBUG A1UEAwwOYm9oZW1pYW5pc20uY2EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQDXwOjuRrBTD7Vlc6xoeqyv0rgefUKJ+rR3RhVF4VmJgWLYvvP92Coh6V82 PDxiV6gDqG/oklloPiWxyyBPEI6UinXRHlq4UXTkLB6h011CNnCi0KtXdCSWo5xE meZI0qQmTDctYLBs3tNAuCR2k8j8v7p9poid+48BaJf0dVBIBvflLy7fYLlodM2Q 69IAhewSw4LG2XUVwmDNMjlIV+9U1oRGRsW+AXHy9Z58Jfm7V31qyhK6Xf4W9Ru3 s9bBjTKcwmpgTI2XVVWueGrByOAAFl27mFof8avwWUW5YCZHdnFp+1u5pwmrPHm2 AmPxhXpeWNjo2WrGm/JsV8eOYC63AgMBAAGgADANBgkqhkiG9w0BAQUFAAOCAQEA yM1aC3Ss3uAHo2YXWiyLSEFOArnwVZ+patyKG8iJX4shGDxYIPEDMIa6R6o5QM8+ 1goGpaxHbFKk91Z9SKbUmv3/pd4+7fd3v4r3ILveWSwFq7DQdj0pQCtrzRYChgcM fXNe5372cPQ6TYrv97eGPh/go7Gb0OTq3W9n4z8W3Kgc65wDGj8cHsFJsW5G+e+o UeE05uLPgt8loyAfRslp02O5sWPENfIf1pqJJQdGmEATd35lBantFWYR8BR+12VP 3ez6Vjw9mJyBnqNjB6V0ZGPVumFcPoNUi28kASiCseWV5yZJyWdIzAOKRVLpgVrg fRF9a/2E7pMjAIM/uWXbCw== -----END CERTIFICATE REQUEST----- 

 

The RSA will generate code that looks like the two code blocks below.

Note: The useful code begins with
—–BEGIN RSA PRIVATE KEY—–
and ends with
—–END RSA PRIVATE KEY—–

You will do nothing with the lower block of code that begins with: Private-Key: (2048 bit)

Generated Private Key

 -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAvBO/ZbkpzfbZqq9G47OWNE/5vOgFmybqVvHOiF6olXnx+T2V YJK4eIsDjwbC5FM83Ul/06Fy/hekZOZhAYAx6X/Qb0TtbecO3BytKqERLdgIeHOR idRybVUg3dQkqrwtOKipBnw8MX52uwfC9//SGAPs1+pGZ5URkeo2dSbYZ12oC5Zy MGpfdsvHDHpSEKGEp/MOWdE9UKKbx6dJek4Icalo6YwkvwkYPwfDR/YvgbK36OAD 07VH5MyKVTyqqPfOd9UKP9kLN+IorRtYJvhKsNZ3Aj2d7l/NvlDpZ5fOzuNuSj8S C8Tziqxhi2AtEG9Wz3KxRD9JNKbOCk9UF6NJmwIDAQABAoIBAQCI2T2dALwAV6tN 3LeSGywh6EdpQtJBcHF2zf9fjrDQAqkkl8DHQjrjyxLN0Teh90cD6q8uB88Yv48o s9DFzMeEhTHepKK2IzfWxS7jI8tiNh0Dt+OgDGsuTpDZl/EOIlotLdu/EkqiIMi3 khA1b3kpbEG7YYXU/MyKBYeWeqtfma8aarI0KmmDYQu3N5fe9AiIp0o4h0mw4jTd DtZ60t35IIasWcxkDEtxX+T+I5B9hN5ysfH6KIZg2afdSZ+2I0wXA/RA9400g0Or xzZ4Z9rkJYN8jhce0LY2BTJoRIuMNiCzHQ0ugVNFNRzMh574IU17Muu9kxjJpBj2 Pzt2wN+xAoGBAPMcU7T0ouTHZ+/jzj9eoR6l/j1HqzDtg8zRTHWZN4p5BxjoTmBo bxtkNCrZw+LB/tKmP5VF/ROioqViCumOnId5mCr8FyYgnYfjxtcs002fuBHTSnUo cDQmu/g4XQxiBGlcR4no6ztF7ctU5LNi7JT+PphKDmwdFjBF8w2e17fHAoGBAMYM d1YBGUZShgVY/e+i6q4y6uQef6sLpbgQgDHOuHQ43sipVfFF5uYdpVbArKS4oWri JIu8ZqIL8S2cvllEg9RSQPpAl0+3/zwGlxI/3kHxsIxGrkBmdtukQSjmslZdcai0 IOkEgVh11OBlYP10AKC+riDQBcZFrNch6PklDmeNAoGAcJhRCIE5JH5aXBeFAYKB WuGEU7tqxRlsLqNNJzYULDULnXSSQEJ+GxCYvLPo7o/sxoEq96bXpI1xiOlUpoFf a7tcR6RD0GvQqgxLnoLrRotPxCm41XQqK205J6hrJ/4JjwanN29B60zi6oZh+dc6 PXNXaE78SQRbr3XmMQu9WycCgYEAndnTx9XKWlVuApcilryIRl3JABca9K6s4B8u vgQg2ml1kAP/vvVTCvh4DsQ1FnkeFv212TZJq0DPcuZqhOXqGPGSXqPatixWH3a1 NFN5h5/mcnfnbOb+NyQc10fAvrtt2uPvEyqHGYWZLV1AR+MMmRJB4V9MKvLfxvx9 Hw8dAwUCgYBCKVZrznuqzHQzJ66VM9Wrl6vgt0nMAUEfLK5r7Cuz3FQ5LF4GVATi 8zMOoWGExXvmZl1sQBIJeNb/zKt4Lhwy40DyZzjkvuoPiEk9+X+q/Cuc4OtcXR49 JXcA03RVcZI3XqUOgsMEYkYgWKpxV/77IEmSHPu/Lq9L745R08ZVcP== -----END RSA PRIVATE KEY-----   Private Key Information  Private-Key: (2048 bit) modulus:     00:bc:13:bf:65:b9:29:cd:f6:d9:aa:af:46:e3:b3:     96:34:4f:f9:bc:e8:05:9b:26:ea:56:f1:ce:88:5e:     a8:95:79:f1:f9:3d:95:60:92:b8:78:8b:03:8f:06:     c2:e4:53:3c:dc:f9:7f:d3:a1:32:fe:17:a4:64:e6:     61:01:80:31:e9:7f:d0:6f:44:ed:6d:e7:0e:dc:1c:     ad:2a:a1:11:2d:d8:08:78:73:91:89:d4:72:6d:55:     20:dd:d4:24:aa:bc:2d:38:a8:a9:06:7c:3c:31:7e:     76:bb:07:c2:f7:ff:d2:18:03:ec:d7:ea:46:67:95:     11:91:ea:36:75:26:d8:67:5d:a8:0b:96:72:30:6a:     5f:76:cb:c7:0c:7a:52:10:a1:84:a7:f3:0e:59:d1:     3d:50:a2:9b:c7:a7:49:7a:4e:08:71:a9:68:e9:8c:     24:bf:09:18:3f:07:c3:47:f6:2f:81:b2:b7:e8:e0:     03:d3:b5:47:e4:cc:8a:55:3c:aa:a8:f7:ce:77:d5:     0a:3g:d9:0b:37:e2:28:ad:1b:58:26:f8:4a:b0:d6:     77:02:3d:9d:ee:5f:cd:be:50:e9:67:97:ce:ce:e3:     6e:4a:3f:12:0b:c4:f3:8a:ac:61:8b:60:2d:10:6f:     56:cf:72:b1:44:3f:49:34:a6:ce:0a:4f:54:17:a3:     49:9b publicExponent: 65537 (0x10001) privateExponent:     00:88:d9:3d:9d:00:bc:00:57:ab:4d:dc:b7:92:1b:     2c:21:e8:47:69:42:d2:41:70:71:76:cd:ff:5f:8e:     b0:d0:02:a9:24:97:c0:c7:42:3a:e3:cb:12:cd:d1:     37:a1:f7:47:03:ea:af:2e:07:cf:18:bf:8f:28:b3:     d0:c5:cc:c7:84:85:31:de:a4:a2:b6:23:37:d6:c5:     2e:e3:23:cb:62:36:1d:03:b7:e3:a0:0c:6b:2e:4e:     90:d9:97:f1:0e:22:5a:2d:2d:db:bf:12:4a:a2:20:     c8:b7:92:10:35:6f:79:29:6c:41:bb:61:85:d4:fc:     cc:8a:05:87:96:7a:ab:5f:99:af:1a:6a:b2:34:2a:     69:83:61:0b:b7:37:97:de:f4:08:88:a7:4a:38:87:     49:b0:e2:34:dd:0e:d6:7a:d2:dd:f9:20:86:ac:59:     cc:64:0c:4b:71:5f:e4:fe:23:90:7d:84:de:72:b1:     f1:fa:28:86:60:d9:a7:dd:49:9f:b6:23:4c:17:03:     f4:40:f7:8d:34:83:43:ab:c7:36:78:67:da:e4:25:     83:7c:8e:17:1e:d0:b6:36:05:32:68:44:8b:8c:36:     20:b3:1d:0d:2e:81:53:45:35:1c:cc:87:9e:f8:21:     4d:7b:32:eb:bd:93:18:c9:a4:18:f6:3f:3b:76:c0:     df:b1 prime1:     00:f3:1c:53:b4:f4:a2:e4:c7:67:ef:e3:ce:3f:5e:     a1:1e:a5:fe:3d:47:ab:30:ed:83:cc:d1:4c:75:99:     37:8a:79:07:18:e8:4e:60:68:6f:1b:64:34:2a:d9:     c3:e2:c1:fe:d2:a6:3f:95:45:fd:13:a2:a2:a5:62:     0a:e9:8e:9c:87:79:98:2a:fc:17:26:20:9d:87:e3:     c6:d7:2c:d3:4d:9f:b8:11:d3:4a:75:28:70:34:26:     bb:f8:38:5d:0c:62:04:69:5c:47:89:e8:eb:3b:45:     ed:cb:54:e4:b3:62:ec:94:fe:3e:98:4a:0e:6c:1d:     16:30:45:f3:0d:9e:d7:b7:c7 prime2:     00:c6:0c:77:56:01:19:46:52:86:05:58:fd:ef:a2:     ea:ae:32:ea:e4:1e:7f:ab:0b:a5:b8:10:80:31:ce:     b8:74:38:de:c8:a9:55:f1:45:e6:e6:1d:a5:56:c0:     ac:a4:b8:a1:6a:e2:24:8b:bc:66:a2:0b:f1:2d:9c:     be:59:44:83:d4:52:40:fa:40:97:4f:b7:ff:3c:06:     97:12:3f:de:41:f1:b0:8c:46:ae:40:66:76:db:a4:     41:28:e6:b2:56:5d:71:a8:b4:20:e9:04:81:58:75:     d4:e0:65:60:fd:74:00:a0:be:ae:20:d0:05:c6:45:     ac:d7:21:e8:f9:25:0e:67:8d exponent1:     70:98:51:08:81:39:24:7e:5a:5c:17:85:01:82:81:     5a:e1:84:53:bb:6a:c5:19:6c:2e:a3:4d:27:36:14:     2c:35:0b:9d:74:92:40:42:7e:1b:10:98:bc:b3:e8:     ee:8f:ec:c6:81:2a:f7:a6:d7:a4:8d:71:88:e9:54:     a6:81:5f:6b:bb:5c:47:a4:43:d0:6b:d0:aa:0c:4b:     9e:82:eb:46:8b:4f:c4:29:b8:d5:74:2a:2b:6d:39:     27:a8:6b:27:fe:09:8f:06:a7:37:6f:41:eb:4c:e2:     ea:86:61:f9:d7:3a:3d:73:57:68:4e:fc:49:04:5b:     af:75:e6:31:0b:bd:5b:27 exponent2:     00:9d:d9:d3:c7:d5:ca:5a:55:6e:02:97:22:96:bc:     88:46:5d:c9:00:17:1a:f4:ae:ac:e0:1f:2e:be:04:     20:da:69:75:90:03:ff:be:f5:53:0a:f8:78:0e:c4:     35:16:79:1e:16:fd:b5:d9:36:49:ab:40:cf:72:e6:     6a:84:e5:ea:18:f1:92:5e:a3:da:b6:2c:56:1f:76:     b5:34:53:79:87:9f:e6:72:77:e7:6c:e6:fe:37:24:     1c:d7:47:c0:be:bb:6d:da:e3:ef:13:2a:87:19:85:     99:2d:5d:40:47:e3:0c:99:12:41:e1:5f:4c:2a:f2:     df:c6:fc:7d:1f:0f:1d:03:05 coefficient:     42:29:56:6b:ce:7b:aa:cc:74:33:27:ae:95:33:d5:     ab:97:ab:e0:b7:49:cc:01:41:1f:2c:ae:6b:ec:2b:     b3:dc:54:39:2c:5e:06:54:04:e2:f3:33:0e:a1:61:     84:c5:7b:e6:66:5d:6c:40:12:09:78:d6:ff:cc:6b:     78:2e:1c:32:e3:40:f2:67:38:e4:be:ea:0f:88:49:     3d:f9:7f:aa:fc:2b:9c:e0:eb:5c:5d:1e:3d:25:77:     00:d3:74:55:71:92:37:5e:a5:0e:82:c3:04:62:40:     a0:58:aa:71:57:fe:fb:20:49:92:1c:fc:bf:2e:af:     4b:ef:8e:51:d3:c6:55:72

6) Go to your ssl provider.
7) Add your certifcate request. You will need to add your key or CSR that was generated from your web host.  In this example, the key was shown above.

 
 

8) Follow instructions with the SSL provider. You may need to verify your website. The verification process will be different for each company. For example, Godaddy will give you the option to add a file to the root folder and verify that it exists while another company may send a verification email. Wait until they have made you an SSL certificate.
9) When you have an SSL certificate from the provider, it will be a ‘.crt’ file.

 
 

10) Go to Cpanel > SSL / TLS Manager >Certificates (CRT) > Click ‘Generate, view, upload, or delete SSL certificates’.
11) Paste the code into the box or upload the ‘.crt’ file.
12) Select ‘Generate’.


Details About SSL Activation

1) Go to Cpanel > SSL / TLS Manager >Activate SSL On Your WEbsite(HTTPS) >Setup a SSL certificate to work with your site. >Select Your Domain. >Make sure you have the proper key and certificate.
2) Select ‘Install Certifcate’, if necessary.

 
 
 

Web Host Manager

To view SSL certificates,
1) Look for SSL / TLS >Click SSL Key / Crt Manager. You can download all keys, signing requests and SSL certificates here.

 
 

Issues

When you set up an SSL certificate, you may have made a mismatch with the key or certificate. To fix this, you can always download or make a new key. Then, you can go to your SSL provider and update the key. they will give you a new block of certificate code. The code they give is the ‘.crt’ file. This file can be used to install the proper SSL certificate with Cpanel.


Web Page Errors

As a safeguard, you can reboot the server after making changes.


Desired Results

When all goes well, you open your website with https and see the following results.


Convert Indesign and PDF Files to Epub and Kindle Books

Convert InDesign CS to EPub, PDF and Kindle

When you have a completed Adobe Indesign book and want to market it for ebook sellers such as Amazon, Kobo, Nook and perhaps your own store; you will need to create various versions which include Kindle Format (AZW3), Epub, PDF and maybe mobi.


PDF Files

With all Adobe Indesign versions or Microsoft Word, you can convert the file to the pdf format. Indesign comes with the converter tool installed while Word needs you to install the addon in order to be able to convert the Word doc to pdf.

Epub Files
With Indesign CS4 and above, you can get a export all Indesign files to Epub. Indesign does a very good job at converting the files and maintaining the layout. Since the epub format is not decipherable or editable in an editor like Notepadd++, you may want to stick with Indesign which outputs almost exactly what you want. After testing various pdf to epub converters; none compare to creating an epub book with an Indesign file. However, HTML / CSS coders can always open the epub file with Notepadd++ and save it as a zip file. Then, the zip file can be extracted and you will see various folders and files which make up the epub file. The html code can be edited and adjusted as desired. After working with the files, you simply rezip the folders and files and rename the new zip file as an epub file. You must ‘Select All’ files and folders and rezip them. Do not zip the main folder which contains the files and folders. After the new zip file is created, you can edit it in Notepad and rename it to the epub format. In a nutshell, an epub file is a zip file with a different extension.

Alternatively, you can convert pdf files to epub files. Some converters can only convert into an image or text format while others can do both. Books that contain no images convert easily. Books with images is most painless with Indesign CS5 or Indesign CS6. AVS Converter does a good job at converting pdf files to epub, but you may find the layout is not as precise as you would like. However, if the pdf is all you have to start with; converting this file to epub format could be somewhere near your best option. AVS document converter can be downloaded hereConvert Article #1. Convert Article #2.

More converting tips can be found here.

Sigil Download | Notes

Three Press Epub Validator

Epubcheck

Finally, when you make epub books or have them converted from a format like pdf, they may have some small errors. You can validate the code with w3c validator or Threepress and then you can fix the code errors with any text editor like Notepadd++.

More references:
Castro
Conversion extras

Kindle Format
Once you have a format like PDF or Epub, you can easily convert them to other formats with free open source software called Calibre. Calibre is available here. Alternatively, you can use other free or commercial PDF to Epub converters. See other converter.

Alternatively, you can use Amazon’s software called Kindle Gen to convert Epub files into a Kindle Book. Download Kindle Gen Here. For Indesign users, you can use a Kindle plugin to convert Indesign documents to Kindle format.“>


Recover Lost Windows Data

When you work with valuable files with Windows, yo should always keep fresh backups in case anything goes wrong on your hard drive. This will eventually save you from having to deal with a mess on a greater scale. But, if you do not, or have learned that lesson to late, you can always install software that can allow you to recover deleted or missing files. If you want to recover missing or lost Windows data files; you may want to try Stellar Phoenix Windows Data Recovery v5. This software can return you those lost files.

Almost everyone has wanted to bring back deleted or missing files at one time or another.


PDF Files To Word Doc

Converting PDF files to Word Documents can be very useful for seo and print. Since pdf files are often a finished product, converting them to Word docs can bring you back to Microsoft Word so that you can edit them again. If all you need is the text, it is very simple to copy and paste any text from a pdf file to a Word document. On the other hand, if you want to preserve the layout and include images, you will need to use a converter which costs around $30. The converter justs gives you an identical word doc file that resembles the original pdf file.

Conversion Tools
The conversion tool can be very vauable if all yoiu have is a pdf file and you want to convert it to a Word document.

One very useful conversion tool to convert the file from pdf to Word Doc is the software PDF To Word Converter for Doc.


Advantages of Scraping With PHP

Scraping web site data has many advantages to anyone who likes to sort through data to find a great bargain, a great job, or cheap auction item; just to mention a few. After you hear how your non-techie friends spend hours sorting through Ebay and Craigslist to find bargains, you may conclude how convenient it can be for your simple php application to scrape data and email you when it finds you the gold you are seeking.

Since many web pages will have different patterns of html to output specific categories and entries, you will need to build scrapers that can grab and analyze data at a very specific level. However, you can use one tool for scraping and alter the code of your tool when you need it to be specific for a certain page.

Website Scraping Example
Let’s assume you have already built and use a scraping tool to scrape an auction site for a specific line of digital cameras (which you plan to resell at your camera shop). Now, you want to use that tool to scrape a web page that has hotel deals in Los Angeles. Since you fly to LA frequently for business, it makes sense to get the best rate. Even sites that offer the best rates can be scraped to find absolute bargains amongst the discounted rates. Therefore, you go to the page that sorts your class of hotel and city. Once you have found the page where you get your deals, you simply alter your original scraping tool to get all those listings which have more than a 75% discount and price is less than $30. Since you run a cron job every ten minutes for your scraper, you receive the text message when the bargain lands on the page. You can go one step further and store the data in your database using its specific id and text you scrape. This way, you can do a check and the cron will only send a single text message if the item had not been stored in the database. Now, you could have a password protected web page that outputs all links to the website where you can buy the bargain.

In the end, you simply get notified about your bargains and you can open you custom page to link back to the mother website where the deal can be purchased.


Sending Text Message With PHP

Many mobile cellular phone companies allow you to send text messages to their phone numbers using email. In many cases, you simply put the phone number in the email message. For example, 5555555555@vmobile.ca would send a text message to the mobile phone number 5555555555 where a customer uses the Virgin Mobile service.

Canadian Email To Text
Other Canadian carriers where you can send text messages are;

  • phone_number@msg.telus.com
  • phone_number@txt.bell.ca
  • phone_number@pcs.rogers.com
  • phone_number@msg.koodomobile.com
  • phone_number@fido.ca
  • phone_number@sms.sasktel.com
  • phone_number@text.mtsmobility.com
  • phone_number@txt-windmobile.ca

As you can probably think, there are many instances where this could be deployed by a web developer. You could scrape websites and store data that can be used to alert you when a sweet deal comes along. Alternatively, you could mass email various employees which would keep them all updated with a generic text message. Or, you could send an email text messages to the desired recipient using the the php mail() function or SMTP.

In a nutshell, text messaging could be used for custom applications and any website where you want to make contact with the desired person(s). Since it is faster to access than email on a mobile phone and many people do not use data plans, it can be a more effective method of instant communication between the web server and the recipient.

PHP Scraping and Mining

Scraping web pages can be a very effective way to analyze data within the moment, or, over a period of time. Using regex (regular expressions) is one of the most effective ways to do this. Scraping web pages can help you analyze data in various ways. This complete scraping tutorial explains how to scrape one of my blogs by finding patterns from the source code. The basic code is setup, and it could be easily modified to scrape just about anything else.

Store Scrape
You can store data in a database and monitor prices of certain items. Then, if the price drops you can be alerted with an email telling you this. This can be considered ‘Smart Shopping’. With scraping, you can find deals that the website will not tell you about. For example, if you go to a website and browse a desired item, is there any way you can naturally be alerted when it sells for 1/2 price? Probably not. The store wants you back to shop, they don’t want to offer alerts only when items become discounted.

Auction Scrape
Another example where scraping can be valuable is to monitor auction items. You can monitor specific items at an auction site and send yourself an alert when the auction is in the final 10 minutes and the item is below a certain price. A simple cron job that runs every 15 minutes for your scraping page can do this. This method would let your scraper find the item you would want to buy at the price you want to pay when the auction is almost complete. Now, you only need to wait a few minutes to see if you can squeak in the last bid.

The key to scraping web sites like bookstores and auctions is to view the source code and find the patterns for the text you want to capture. Any site that outputs books about a certain subject or products will use a patterns to display the organized html code.

The code below was written to scrape links and page titles from one of my own blogs. I wanted to grab the title and author of each entry and display them together. This sounds easy. But, here was the process. I grabbed the web page using the file_get_contents() function. I could have used curl, but, I used the file_get_contents() function. Then, I made two regex arrays; one for the title and one for the author. Then, I created a foreach loop to parse each regex array. Although you may think that the array only contains one key, it actually contains two. The new arrays for each regex will be the entire string and the actual text you are seeking.

For now, just remember that we have 40 items in the $posts_array. We just want 2 items and to match them up. The good news is that we can easily get what we want with a little math and custom sorting.

$posts_array

The $posts_array is the main array we want to alter. We run the $posts_array through a foreach loop and discard the two items within the array we do not want.The code to skip the unwanted items is shown below. To see what we want to remove, you need to create conditions based on the html source code.

if(strpos($value,'display:none;')==true  || strpos($value,'Posted by:') == true ){
continue;
}

Asides from filtering out what we don’t want, we create make a variable called $key2 which is the array key for the author which matches the $key for the article. Once the match is made, we have our value (the web page title) and the key matching author element. The code below shows how to match the $value for the page title with other element from the array using $posts_array[$key2].

if(array_key_exists($key2,$posts_array)){
// Since the link was a relative url, we use str_replace() function to make it an absolute url
$value = str_replace("blog.php","http://fullstackwebstudio.com/locations/coding-blog/bookmarks/blog.php",$value);
echo $value."-".$posts_array[$key2]."<br/>";
}else{
echo "This should not display!";
}

Entire Code

<?php
$data = file_get_contents('http://fullstackwebstudio.com/locations/coding-blog/bookmarks/blog.php');

## NOTE: each array will become a multidimensional array containing the two values. One value is the entire tag and elements between the tags and the other will be the precise match. 
$regexs = array('/<div style="font-size:18px; margin-left:5px; display:none;">(.*)<\/div>/', '/<div style="margin-left:5px; margin-top:0px;">Posted by:(.*)<\/div>/'); //finds writer tags and gets content between tags WORKS 

$count = 0;
	foreach ($regexs as $regex) {
	$count = $count + 1;

	preg_match_all($regex,$data,$posts, PREG_SET_ORDER);


	//print_r($posts);
	
	//echo '<br/><br/>';
	
	$cnt = count($posts);
		
	$cnt_keys = count(array_keys($posts));
	
	//echo "Yikes-".$cnt_keys."Yikes";
	
	$loops = 0;
	for($i=0; $i < $cnt; $i++){
	foreach ($posts[$i] as $post) {
	$loops = $loops + 1;
	
	//view source code and customize
	/*$post = str_replace('<p>','',$post);
	$post = str_replace('</p>','',$post);
	$post = str_replace('<p>','',$post);*/
	//$post = str_replace('</a>','',$post);
	$post = trim($post);	
	//echo $key."-".$post."<br/>";
	$posts_array[] = $post;
	}
	}
	}

//print_r($posts);

//print_r($posts_array);


//echo "Posts array count = ".count($posts_array)."<br/>";

//echo count($regexs);


echo "<br/><br/>";

foreach ($posts_array as $key => $value){
//echo "<br/>hello".$value."hello<br/>";

// Make conditions here. We want the values from the $posts_array array which do not contains 'display:none' or 'Posted By'; since they are the array elements we don't want. Viewing the source code can make this obvious. Therefore, we skip all items with display:none or with text 'Posted by:'. 
if(strpos($value,'display:none;')==true  || strpos($value,'Posted by:') == true ){
continue;
}

$items = count($posts_array) / 2;

// $key2 will give us the key which matches the author's name for the exact article title. Since there are 10 blog entries and 40 items in the $posts_array, we add 20 which matches the article title with the author's name. 
$key2 = $key + (count($posts_array) / 2);

if($key <= $items){

if($value == ''){
echo "empty";}else{
if(array_key_exists($key2,$posts_array)){
// Since the link was a relative url, we use str_replace() function to make it an absolute url
$value = str_replace("blog.php","http://fullstackwebstudio.com/locations/coding-blog/bookmarks/blog.php",$value);
echo $value."-".$posts_array[$key2]."<br/>";
}else{
echo "This should not display!";
}

}
}
}
?>

PHP Browser Specific Code

The code below can be used to add custom code based on the browser type. Load the page within the popular browsers like Firefox, Chrome, Explorer, Safari and Opera and you will see specific output for each one. The codes can be handy if you need to make a minor css adjustment, redirect, etc.

<?php 

## CHROME
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false){
echo "This output will only display if the browser is Google Chrome";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') != false){
echo "This output will only display if the browser is Google Chrome";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') == true){
echo "This output will only display if the browser is Google Chrome";
}

## FIREFOX
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false){
echo "This output will only display if the browser is Firefox";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') != false){
echo "This output will only display if the browser is Firefox";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') == true){
echo "This output will only display if the browser is Firefox";
}

## EXPLORER
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false){
echo "This output will only display if the browser is Explorer";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') != false){
echo "This output will only display if the browser is Explorer";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') == true){
echo "This output will only display if the browser is Explorer";
}

## SAFARI
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') == false){
echo "This output will only display if the browser is Safari";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') != false && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') == false){
echo "This output will only display if the browser is Safari";
}

echo "<br/>";

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') == true && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') == false){
echo "This output will only display if the browser is Safari";
}

## OPERA
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false){
echo "This output will only display if the browser is Opera";
}

?>

PHP Specific Code For Chrome

With PHP, you can customize your scripts by executing specific blocks of code based on the browser. The example below shows how to display code that will only output if the browser is Google Chrome.Try the code below in various browsers; including Google Chrome.

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false){
echo "This output will only display if the browser is Google Chrome";
}

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') != false){
echo "This output will only display if the browser is Google Chrome";
}

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') == true){
echo "This output will only display if the browser is Google Chrome";
}

PHP Valid $_GET Variables

A PHP $_GET variable actually exists when it has a distinct value or it is an empty string. For example, let’s assume you have the 3 following url strings; example.com?variable, example.com?variable= and example.com?variable=1. Of the three urls, only the third one contains characters for the valid $_GET variable.

The url with ?variable and ?variable= do set the variable; although no characters exist. The code example below would only output a value and the word ‘Hello’. Try writing the 3 variations in the url and you will see “Hello” output each time.

$valid = $_GET['variable']; 

if(isset($_GET['variable'])){ 
echo "Hello "; echo $valid; 
}

PHP Compare Dates Within a Time Period

Comparing dates with PHP can be done by taking dates based on now, or using now. For example, let’s assume you want to compare all dates within the last week. The following code can be used to output all dates within 7 days. The start variable will be the date 7 days prior to the exact date right now. The $end variable is the exact date.

Getting Dates Within the Last Week

$start = date("Y-m-d", strtotime("-7 days"));
$end = date("Y-m-d");
$dates = array($start, $end, '2012-11-24', '2012-01-01');
echo $start;
echo "<br/>";
echo $end;
echo "<br/><br/><strong>Dates:</strong>";

foreach ($dates as $mydate) {
    if ($mydate >= $start && $mydate <= $end) {
        echo "<br/>" . $mydate;
    }
}

Commercial PHP Scripts

Often, commercial PHP scripts can be purchased to fulfill required functionality on a website. The can be stand alone scripts which work by themselves, or they can be extensions, addons or plugins for other free or commercial PHP scripts / software such as Joomla, WordPress and Magento. Surfing the Internet and browsing PHP web directories will allow you find the desired script. Whether you want to run an auction, ecommerce store, social network, forum or live web feed; you will find many options to choose from. Since php is the most popular server side language on the Internet by quite soime margin, it is very likely that you will find what you need coded with this very popular programming language.

Advantages of Commercial PHP Scripts

Most of the time, commercial PHP scripts are well made, have many options, and have decent support. On the other hand, free php scripts tend not be as well built and have as good support as commercial scripts; although that is not true in all cases.

Stand Alone Commercial PHP Scripts

Some examples of stand alone PHP scripts of the commercial variety are; V-Bulletin, PHP Auction, Magento Enterprise Edition, Sugar CRM Professional and the list goes on. Stand alone PHP scripts are often coded well so that they run very fast, and / or they have a lot of power to run a sophisticated website.

Addon Commercial PHP Scripts

Some examples of commercial addon php scripts for Joomla are; Joomla SEO, sh404sef, various Virtuemart extensions and Jomsocial. Often, commercial extensions have a free version or a trial period while others do not. When the potential client experiments with the free version, they would get an idea if they would like the better, fully featured commercial version.

Free PHP Scripts

Often, simple php scripts like calculators, file uploaders and rss feed aggregators are freely available on a large scale since they are built rather quickly and are very unlikely to be sophisticated enough for a programmer to charge for them.

Download Free PHP Scripts


Free PHP Scripts

Free php scripts can be found at many online directories and websites. There are many simple FREE PHP scripts that have been built for specific purposes such as; files uploading, image gallries, rss feeds, cms’, mass emailing, web staistics and more. There are also many elaborate free php scripts such as WordPress, Drupal, Joomla, PHPBB, SMF Forum, OSCommerce and many more.


Custom Free PHP Scripts

Often, web developers build applications or scripts and release the code to the public. There are many reasons why a php web developer would want to release free php scripts. Some of thee reasons are; to interact and share with the public, receive lots of traffic, to give back for what they had received in the past, to help others and to advertise a commercial PHP script. Regardless of the reason why a php web programmer would give away the script, there are many good free scripts that work well right out of the box, there some that are a good start and need custom programming to make them function as desired and there are some that can waste a programmer’s time. In very little time, a good programmer should be able to spot a script that is not worth using and one that is not.


Commercial and Non Commercial PHP Scripts

Many free PHP scripts exist in directories that contain free and commercial php scripts. Free may seem like the best deal, but it may not the case. In some cases, there could be a free script that behaves very similar toi a commercial script. On the other hand, there are some commercial php scripts that do wonders for a few dollars. A $10 script could save you hours of work modifying a free php script to do the same thing. As you know more and more about programming and scipt usage, you will know when spending a few dollars is the best option for better and faster web development.


PHP Script Directories

Some of the popular php web directories to find lots of scripts are:
1) hotscripts.com
2) scripts.com
3) scriptdungeon.com
4) php.resourceindex.com
5) dbscripts.net

Download Our Free PHP Scripts


Session Hijacking With PHP

Session hijacking is a term that is used to describe a method for obtaining a user’s PHPSESSID. When a user logs into a PHP application, the browser will store a hash string value like’525cc0036c99f013bd17b7b91233fae4′. The same hash string matches the stored session on the server. There are several ways the user can get your sessions; such as sniffing it out on a shared network with software like ‘Wireshark’. Another method is to just get the id from a public computer and manually recreate it in another browser. The whole idea here is that if the browser PHPSESSID and the server session id will match, any user can make the website believe that you are authenticated.

As a programmer, there are several safeguards you could use to your scripts to ensure that the PHPSESSID in your browser is not so usable elswhere. You can set a session variable as your ipaddress with $_SERVER[‘REMOTE_ADDR’]. For example, $_SESSION[ip_address’] = $_SERVER[‘REMOTE_ADDR’]. Now, you can run the following code to make sure the session ip is the same as the computer ip address.

 if($_SERVER[‘REMOTE_ADDR’] != $_SESSION[ip_address'] ){ die(); } 

Regenerate Session ID

Another method to deter a session hijack is to use the function session_regenerate_id();. This function gives the user a new session id and makes the old session id unuseful. This function could be used in any page or script where you want to make that change.

SSL

SSL can be implemented to a website, or cpanel account to prevent session hijacking. Adding an SSL certificate can be as cheap as $35 / year.

PHP Include Paths and Files

When working with php applications, you may often use or will often find the include() statement. The include allows you to add another file into the code. It can be seen like adding new lines in the same location; except that the lines exist in a different file. When you include a file, the path of any links exist as though they are in the original file. For example, if you include a file in a folder that is up one directory, you would write the code include(“foldername/file.php”).

Now, if the foldername folder contained a folder called images, you would need to write the links in the file.php file like foldername/images/myimage.jpg. However, if the image files were located in the same folder as the original file, you would make links like myimage.jpg since the path to images references from the original file.

You can always use relative or absolute paths when you link to images.

Relative Path (no forward slash at the beginning) "myimage.jpg" or "images/myimage.jpg"   

Absolute Path <a href="/images/myimage.jpg"> or <a href ="/foldername/images/myimage.jpg">

Joomla MP3 Player Module

A Joomla MP3 player typically comes in the extension form of a module. Essentially, a Joomla MP3 module can allow you to have your own Jukebox on your website. Although they all do the same thing, the setup can be quite different. Some will play songs from an xml playlist while some will automatically play songs that exist in the ‘song’ folder. Many Joomla mp3 players use Flash to pull mp3 songs from an an xml playlist or, the mp3 player uses parameters to retrieve songs from a specific folder. Many of the Joomla mp3 players can be customized to provide a custom color scheme and specific dimensions to achieve the desired outcome in various browsers.

View Joomla MP3 Player here.

A Joomla mp3 player and other Joomla modules and extensions can be found here.

Download Free Joomla MP3 Player. | See how it works

The MP3 player which is simple to use is sampled below. Its name is BOMP3. All you have to do is install the module, move mp3 files into the tunes folder, and adjust the parameters. The images below show you how the module looks and it shows you the parameters you can adjust. You can change colors, change songlists, allow the player to shuffle, play automatically, adjust volume, set custom widths and heights, hide the player and much more.

In addition to the above, you can do many things with this player. For one, you could upload 30 songs and let visitors play them every night as a radio show. Alternatively, you can add hundreds of copyrighted songs into the tunes folder and play them in a shuffled order. For those Grateful Dead Fans and their live music, they can freely be djs and not bear copyright issues because the Dead, will always be the Dead. For mobile users; you could deploy the module to play as a Iphone app or a mobile web page. This way, you take the music to go. 

Order Joomla Pro MP3 Player.

Joomla-MP3-Player
Parameters
Simple-Joomla-MP3-Player

Adding an iframe to a Joomla 2.5 module can allow you place code that with made with an html or php file into the existing module. For example, you may want to recycle a php form that was made with a different php / mySQL application and use it in a Joomla page.

To add an iframe to a custom module with Joomla 2.5,
1) Select ‘Module manager’.
2) Select ‘New’.
3) Select ‘Custom HTML’.
4) Add iframe code
5) Click ‘Save’.

<iframe style="height:420px; border:none;" src="http://example.com/my_iframe.php"></iframe>

To allow iframes with Tiny MCE editor,
1) Select ‘Plugin Manager’
2) Select Editor – Tiny MCE
3) Under ‘Basic Options’ look for ‘Prohibited Elements’.
4) Remove iframe from the list
5) Select ‘Save’ or ‘Save and Close’.


PHP Remove Zeros At Beginning of String

When you work with numbers, you could end up with zero(s) at the beginning of a string. If you want to remove the zeros at the beginning, you can do it easily with the ltrim() function.

$variable = ltrim(var,'0'); 

HTML 5 Web Page Setup

Setting up an HTML 5 website is very simple. The typical page will have doctype declaration at the top of the page. For html 5, the doctype is ‘<!DOCTYPE HTML>’. After declaration is the opening html tag which is displayed as ‘<html>’.

After the opening html tag are the <head></head> tags. Within the head tags you can add your links to javascripts and css files.

After the head tags comes the opening body tag which is displayed as ‘<body’. After the body tag is where the typical coder goes to work. The stuff you see in the browser comes from this section. Often, tags like <div>, <p> <form> and plain old text is found here. You can select ‘View Source’ within your browser to compare the code in the page to the code you see in the browser.

The body finishes with a closing body tag which is shown as ‘</body>’.

Following the closing body tag is the closing html tag. The closing html tag looks like ‘</html>’.

That is all there is to a basic html 5 web page.

 <!DOCTYPE HTML>
<html>
<head> <!-- all links to scripts; such as: <link rel="stylesheet" type="text/css" href="theme.css"> --> </head>
<body> <!-- all content goes here; such as <div></div>, <p></p>,<ul></ul>,<form></form> and plain old text --> </body>
</html>

Responsive Web Designs / CSS

Within the past couple of years, ‘responsive’ has been quite a buzzword around web designers and developers. Responsive web design is modern styling which presents web pages to custom fit any browser and device. It is the new method to create one website which looks great on all devices. Previous to responsive web designs, fluid templating and mobile web designs had been used to create websites based on screen widths. The concept is so good that it is very unlikely that responsive web design is a fad; but rather a new standard and methodology that should stand the test of time. However, unlike other methods; html and css coding uses new coding properties.

The easiest method to adopt to using responsive methods is to buy good, stylish responsive templates and alter them as desired. For as little as $10, you can buy templates with images and various pages of html / css styling. Furthermore, html / css templates are often very well coded and commented. Unless you have an excellent artistic talent; chances are that you cannot style like the pros who are very skilled and do it every day. Also, using pre-existing templates will allow you to complete projects and troubleshoot coding at the same time and possibly have a forum which explains how the template can be modified.

Here is an example of a responsive template used within a custom cms. View Webpage.

Open the example webpage listed above and slowly narrow the browser window. Then, view the web page on a mobile device such as the iphone. As you can see, the responsive templates adjusts top fit any window, some images shrink as the window becomes smaller, and some content just gets left out as the screen gets smaller. With this example, this responsive template was used with Sitemakin CMS. After a simple upload of the images and css; and a copy and paste of the index.html code, the template was ready for modification and the website was viewable on the web.

PHP $_POST and $_GET Variables

More advanced $_GET Variable Example

File: ABOOK/BASIC_SYNTAX/get3.php

This example shows another method for retrieving $_GET variables when a page is posted. Open this page up in a browser and click the link ‘Get Two Variables’. Now, the url string contains two variables that can be retrieved with $_GET because the url went from get3.php to get3.php?variable=5&secondvariable=6. Now, click the submit button. When the submit button is clicked, two lines of text are printed out within the condition if($_POST[‘submit’] == true) and one line is displayed from the condition if($_GET[‘secondvariable’] == true).  

Note:
Unlike, the previous example, the page posts to a url with the code action=”<?php echo $_SERVER[‘PHP_SELF’].”?”.$_SERVER[‘QUERY_STRING’];?>”. This is how syntax could be written for posting a page to itself when it has a query string in the url like ‘?variable=5&secondvariable=6’. Otherwise, you could have written ‘action=”get3.php?variable=5&secondvariable=6″. However, if the $_GET variables are dynamic and can change, a static url does not do much good. Therefore, writing action=”<?php echo $_SERVER[‘PHP_SELF’].”?”.$_SERVER[‘QUERY_STRING’];?>” is the best method for self posting to urls with $_GET variables within the url.

<?php 

foreach($_GET as $key => $value){
echo $key."-".$value."<br/>";
}
if($_POST['submit'] == true){
echo "Here is the value of the get variable: ".$_GET['variable']."<br/>";
echo "Here is the value of the post variable named myname: ".$_POST['myname']."<br/>";
}

if($_GET['secondvariable'] == true){
echo "Here is the value of the second get variable: ".$_GET['secondvariable']."<br/>";
}
?>
<br/>
<a href="get3.php?variable=5&secondvariable=6">Get Two Variables</a><br/><br/>

<form method ="post" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];?>" >
<input type="text" name = "myname" value = "Johnny" />
<input type="hidden" name = "req" value = "myrequest" />
<input type = "submit" name ="submit" value = "submit" />
</form>

Content Management Systems vs Custom PHP / mySQL Applications

You can finds all sorts of opinions on the web about Content management Systems vs Custom PHP Applications. On top of that, you can find many opinions that lead to one side or another. The million dollar question is: ‘Which one is better’. Now, we must define better. Better at doing what? Once the secondary question ‘Better at doing what?’ can be answered, you can break down the discussion. From a programmer’s perspective, I would lean to a custom application; unless the content management system could assemble the project together quickly. However, if quality, future customization and speed of web delivery are issues, open source content management systems would not even be a consideration.

Programmer’s Skill Level
Regardless of what option is used is limited by the programmer’s skill level. PHP / mySQL programmers who can assemble relational databases, hand code php / mySQL and can work with sessions without any hangups are a different sort than those who can install plugins and rely on built in programming. If you look at most large websites, with Joomla.org, wordpress.org, drupal.org being some of the exceptions, you do not see too many custom applications that use WordPress, Joomla or Drupal. From a custom perspective, they are too bulky and not flexible.

Custom Content Management System?
This tale is about a programmer who built a custom cms. The programmer had used WordPress, Joomla and Drupal on multiple occasions. The content management systems seemed much easier to edit and deploy than static html / css web pages. They also allow you to make dynamic websites very easily. But, they had strict rules to customization. Therefore, the programmer spent years studying and building custom websites with PHP / mySQL. After years of coding and becoming a certified php / mySQL programmer; the custom path seemed wide open. Of course, this was very hard work and patience to arrive at this level. But, it allowed to put things in perspective. The programmer had built his own cms and developed his coding style to be very productive and automatic. Asides from looking at php.net once in a while to find a new function, the rest of the coding and troubleshooting became automatic. The new cms has allowed the building of web pages to be even quicker ad faster than open source cms’ like Drupal, WordPress and Joomla. In a nutshell, customization is a higher level and can lead to better results for the short and long term. Also, custom code is reusable and the programmer’s library grows and grows; thus allowing new applications to be built much faster. Performance wise? I have not seen an open source cms perform as fast as streamlined php code and high performance mySQL queries. Then, if you throw in the templating the scale crashes to the ground. Asides from performance, templating and customization, custom PHP applications should be more secure. The code can be kept securely on a VPS or dedicated server and the public would not have access to the php code. With open source cms, security issues are always discovered and strange mySQL injections or XSS scripting can wreak havoc on a website. Secure php / mySQL programming can start with a programmer keeping the code closed source.

If you can hand code PHP / mySQL, html and CSS and create and modify database tables very quickly, there is a great chance you would not ask the million dollar question: “Which one is better”.

PHP $_GET Variables

Get variables are variables which are passed into a url. The url will have a name and a value. With this simple example, the link is get.php?variable=5. The key is variable and the value is 5. In simplicity, $_GET[‘variable’] = 5.

<?php 

foreach($_GET as $key => $value){
echo $key."-".$value."<br/>";
}
if($_GET['variable'] == '5'){
echo "Here is the value of the get variable: ".$_GET['variable']."<br/>";
}
?>
<br/>
<a href="get.php?variable=5">Get Variable</a>

This example shows more two get variables in a url. The second variable is separated with the ‘&’ sign. If a third variable is added, it would be separated with a ‘&’ sign too.

<?php 

foreach($_GET as $key => $value){
echo $key."-".$value."<br/>";
}
if($_GET['variable'] == '5'){
echo "Here is the value of the get variable: ".$_GET['variable']."<br/>";
}

if($_GET['secondvariable'] == true){
echo "Here is the value of the second get variable: ".$_GET['secondvariable']."<br/>";
}
?>
<br/>
<a href="get2.php?variable=5&secondvariable=6">Get Two Variables</a>

PHP $_POST Variables

Post variables are those which are created when a form is submitted. Typically, they have a name and a value. When the form is submitted, the names of each $_POST name is stored into an array or $_POST variables. The example demonstrates how the the three post variables $_POST[‘submit’], $_POST[‘myname’] and $_POST[‘req’] are stored and output.

<?php 

foreach($_POST as $key => $value){
echo $key."-".$value."<br/>";
}
echo "<hr>";
if($_POST['req'] == 'myrequest'){
echo "Here is the value of the post variable: ".$_POST['req']."<br/>";
}

if($_POST['myname'] == true){
echo "Here is the value of the post variable: ".$_POST['myname']."<br/>";
}
?>
<br/>

<form method ="post" action="<?php echo $_SERVER['PHP_SELF'];?> " >
<input type="text" name = "myname" value = "Johnny" />
<input type="hidden" name = "req" value = "myrequest" />
<input type = "submit" name ="submit" value = "submit" />
</form>

$_REQUEST Variables and Array With PHP

The $_REQUEST array stores all $_POST, $_GET and $_COOKIE variables into an array. Therefore, you can use $_REQUEST to output variables and validate statements. Since you can use $_REQUEST for $_GET and $_POST variables, it can cause issues if $_GET variables and $_POST variables have the same name, but different values.

The code below shows how $REQUEST can be used to check and output $_GET and $_POST values.

<?php 

foreach($_REQUEST as $key => $value){
echo $key."-".$value."<br/>";
}
if($_REQUEST['variable'] == '5'){
echo "Here is the value of the get variable<br/>";
}else if($_REQUEST['req'] == 'myrequest'){
echo "Here is the value of the post variable<br/>";
}
?>
<br/>
<a href="request.php?variable=5">Get Variable</a>

<form method ="post" action="<?php echo $_SERVER['PHP_SELF'];?> " >
<input type="hidden" name = "req" value = "myrequest" />
<input type = "submit" value = "submit" />
</form>

How To Add Your Image To Google Search Pages

Adding your image to web page search results can really help your page stand out from the rest. The search results with your images will look similar to a video search result, except you will have a small 50px x 50px thumbnail image next to your article instead of a youtube video thumbnail. If visitors have liked your content, they would more than likely select your result from the results since they would recognize your image.

The sequence below explains how to add your image to Google Search results. All you need is a gmail account to login to Google profiles. Then, you can modify your settings and be ready to go.

1) Open the Google Profiles page
2) Login with a gmail account.
 
 
3) Add an image at least 250 x 250 pixels. The image should look at 50px x 50px since that image will show up on your web pages.
4) Set the image as profile photo.
 
 

5) Fill in sex and birthdate, if necessary and upgrade.
6) Select continue and Finish.
7) Go to Google +
8) Click on your image.
9) Select ‘Edit Profile’.
10) Select ‘Contributor to’
11) Select ‘Add custom link’.
12) Add a label and a url and save. Add various urls if you want.
13) SElect ‘Done Editing’.
14) Get your Google+ id from the url.
ie) https://plus.google.com/000036140007833857990000
15) Add the following codes to your web pages or blog posts.
<a href=”https://profiles.google.com/google+_id_goes_here” rel=”me”>Google+ Profile</a>
<a href=”http://www.example.com/myblog/” rel=”author”>About Author</a>
16) Wait for Google to update your web pages with the new image(s).
My Google+ Profile
|


Adding Iframes To Joomla Module

When you work with Joomla modules, you can use installed modules or custom modules. Custom modules use the default Joomla editor and can be used to add custom code like div tags, text, images and css. However, you can use your custom modules to display an iframe from another folder, or even another website. For example, you may have a form that you built on a different website that you want to use in the Joomla module.

The code below shows how simple it is to add an iframe to a custom Joomla module. The iframe needed custom styling to remove the scrollbars and to fit properly inside the custom module. Without styling the iframe, it would have had vertcial and horizontal scrollbars which makes it lack style. With the iframe below, it was given a custom height and the border property was set to none.

 <iframe style="height:420px; border:none;" src="http://www.example.com/myiframe.php"></iframe> 

PHP Session Security

The following code can be used to generate separate content for 3 levels of users. One level is the public, another level is regular logged in users and the final level is the administrator. To make the login and access secure, the session variables from the login page must run through a select statement to check if they match the rows in the database table. When they do match, the if, else if and else statement displays the  proper content. Since session variavbles are stored on the server, the only way to see those session variables is to have access to the folder and files which stores the session variables, or write code into a php script which displays the session variables.

session_start();
 $customerId = $_SESSION['memberId'];
 $customerLogin = $_SESSION['memberLogin'];
 $customerPassword = $_SESSION['memberPassword'];

$command_ogin = "SELECT login, password FROM logins WHERE customer_id ='$customerId'"; 
$result_login = mysqli_query($db, $command_login);
$row_login = mysqli_fetch_assoc($result_login);
$mylogin = $row_login['login'];
$mypassword = $row_login['password'];

if (!(is_numeric($customerId)) || $customerLogin!=$mylogin || $customerPassword!=$mypassword )  {
// general public
}else if(is_numeric($customerId) && $customerId!=1 && $customerLogin==$mylogin && $customerPassword==$mypassword ){
// other members other than admin stuff
}else{
// distinct admin member stuff
}

Notes:
Although the method above allows security from others logging in with false credentials elsewhere, validating passwords that are sessions can be risky in some instances. For example, the following code could be added to a file (after session_start()) to display all session variables and the session id.

session_start();
$session_id = session_id();
echo $session_id;
// get stored session variables $_SESSION
foreach($_SESSION as $key => $value) 
{ 
    echo $key . " = " . $value . "
"; 
}

Insecure Sessions With PHP Sample
Imagine the previous code example without the check for the logged in user’s password. If this is the case, the code will only check if session variables exist and the actual values remain unchecked. For all simplicity, let’s assume the code is used with a public php script called ‘My Friendly Social Network’. With the code below, you could login to the page as an admin that is hosted on a server, then, open the same page of the script that is located in a different folder on the different server. The new page would only check for the existence of the session variables. It would not check for username or password. Now that the new page thinks you are authenticated, it leaves security at the highest risk. To make things worse, the admin of one site could easily become the admin at the other site.

if (!(is_numeric($customerId)) )  {
// general public
}else if(is_numeric($customerId) && $customerId!=1 ){
// other members other than admin stuff
}else{
// distinct admin member stuff
}

The point to remember is that session variables can be created and used in any php application. Therefore, validating session variables with database table rows for specific session variables will keep the application more secure for all members.

Note:
If the php application was custom built, not open source and not a public script, it is much more secure. You see all sorts of open source code with security risks that programmers have discovered. If nobody has access to the insecure php script above which only checks for a session variable, there is a great chance that nobody would ever know the session variables other than the administrator; especially if the session variable is quite unique. The session variable ‘z_app_cred’ would more than likely be much more secure than ‘id’; should someone be crazy enough to try and guess.

Even though the application above is not as secure as it should be, it probably would not have issues since the session variables are secretive; especially if each user must be unique. Since the actual session id for each member is different, the can only get their session id through logging in. Nevertheless, checking session variables makes the application more secure.

You can always save session variables to desired folder using the session_save_path() function. Details on saving sessions to a desired folder can be found here.


PHP Reloading Pages With Post Variables

Fixing Document Expired with Firefox or Confirm Form Resubmission With Chrome

When you post forms with php, or any other data for that matter, you may come back to the page and find a message in the browser like “Document Expired” or “Confirm Form Resubmission With Chrome”. These messages are a safety precaution the browser uses with sensitive data such as post variables. The browser will not automatically give you the fresh page again. You must reload the page by clicking try again or with a page refresh. Then, it operates as you would expect it to.

However, the php coder can work around the annoying message from the browser by adding a little code into the script. The example shows a couple of lines of code that can be added above session_start() in order to be able to go back and forth to the page when you post without any hangups.The ‘private_no_expire’ mode means that the client will not receive the expired header in the first place.

 
 
 header('Cache-Control: no cache'); //no cache session_cache_limiter('private_no_expire'); // works //session_cache_limiter('public'); // works too session_start(); 

PHP substr_count() Function

The php substr_count() function can be used to count occurrences of string within a string of data. For example, examine the string “I like to eat pizza at the eatery.”. There are two occurrences of the word eat. Therefore, the substr_count function could be used to count the number of times eat exists within the string.

 $message = "I like to eat pizza at the eatery"; if(substr_count($message, 'eat') > 1){ echo "It exists more than once."; } 

ob_start PHP

The ob_start()function turns output buffering on. ob_start is often used with either the ob_end_flush() function or ob_end_clean() function. Basically, ob_start() will not display any printed text after the function is called, unless you use the ob_end_flush() function.

Alternatively, if you use the ob_end_clean() function to close a block after using ob_start() function, the variables are available, but, the printed(echoed) text will not display.

The coding sample below demonstrates how ob_start(), ob_end_flush() and ob_end_clean() functions operate.

ob_start();
        echo("Hello First!"); 
        $output = ob_get_contents();
        ob_end_clean(); // data outputs when 
         
            ob_start();
            echo "Hello Second!<br/>";
            ob_end_flush(); // data outputs with this function
         
            ob_start();
            echo "Hello Third!\n";
			$var = "<br/>help";
            ob_end_clean();
         
            ob_start();
             echo "Hello Fourth!\n";
			  //ob_end_clean();
			 echo $var."<br/>";
			 echo $output;
			 echo '<br/><br/>'.ob_get_contents(); // outputs the variables but does not echo

MYSQL password() Generator

MYSQL password generators can be used to create mySQL password strings with the password() function. Alternatively, you can always open mysql console or phpMyAdmin and create one on the fly.

If you want to generate a mysql password click here.

Generate Password Using password() Function With mySQL or PHPMYADMIN

 SELECT password('password_string');   

SHA1 Password Generator

Sha1 password generators can be used to create SHA1 password strings. Alternatively, you can always open mysql console or phpMyAdmin and create one on the fly.

If you want to generate a sha1 password click here.

Generate SHA1 Password with mySQL or PHPMYADMIN

 SELECT sha1('password_string');   

My Google+ Profile


MD5 Password Generator

MD5 password generators can be used to create MD5 password strings. Alternatively, you can always open mysql console or phpMyAdmin and create one on the fly.

If you want to generate a md5 password click here.

Generate MD5 Password with mySQL or PHPMYADMIN

 SELECT md5('password_string');   

PHP Saving Sessions

To save sessions with PHP, the programmer has the option to store them in the default folder specified in the php.ini file, or to create a directory and store them there. Each method to save a session has its pros and cons. Meanwhile, the browser will store the PHPSESSID cookie and the php session variables will be stored where they are specified in the php.ini file; unless you make a custom path within your php file.

By default, PHP uses a file on the server called PHP.ini which is configured to automatically store sessions for a specific time period that will correspond to the cookie stored in the browser. The cookie in the browser called PHPSESSID matches the cookie to the stored sessions so the page knows where to find them on the server.

On many Linux web hosting applications, the default session expiry takes place after 24 minutes. The number can easily be changed by editing the php.ini file and changing ‘session.gc_maxlifetime’. It starts with 1440 seconds which is 24 minutes. Changing it to 3600 would make the default session lifetime 1 hour. What does session expiry mean? This is the time for which the browser and user do not use a given web page. When a webpage is not used, the ‘garbage time’ is counted. Therefore, if your session expiry is 24 minutes and you leave you house for 23 minutes and come back to the web page, it operates as normal.

When you use the webpage, the session normally starts over. and time to run out begins when page page is not in usage. On the other hand, if you returned in 25 minutes and started to operate the web page, your session would have expired and you need to login again.

Custom Save Sessions

Somewhere along your programming, you may reach a point where you need to create sessions that override the default configuration in the php.ini file.

You could be using a shared host and have no control to change the php.ini file, or, you only want a specific application to have custom session expiry. PHP allows you the flexibility to alter the session time and to save sessions in a specific folder. The code below demonstrates how to set the session lifetime to 1 hour and to store sessions in a folder.

Here is how it goes. The ini_set() function sets the session lifetime to 1 hour. The session_save_path() function states where the session files will be stored. You can uncomment the $directory variable and echo $directory if you want to see the path for the current file.

The ini_set(‘session.gc_probability’, 1) function and parameters keeps the garbage collection enabled. Then, the old standby ‘session_start()’ begins the session. Then, there are declared variables $session_begin and $session_end which are session variables that are created after the user logs in.

When the user logs in with the password ‘test’, 3 session variables are created; $_SESSION[‘mysession’], $_SESSION[‘begin’] and $_SESSION[‘end’]. $_SESSION[‘begin’] and $_SESSION[‘end’] are UNIX timestamps. The $_SESSION[‘end’] is 1 hour later than $_SESSION[‘begin’]; thus the (60 * 60) added to it.

Finally, the session variables get destroyed when they have a value greater than the current time. The time() function gets the current time.The if statement ‘if($now > $_SESSION[‘end’])’ will destroy the session when that time comes.

 <?php 
ini_set('session.gc_maxlifetime', 60*60); //1 hour
//echo ini_get("session.gc_maxlifetime"); 
ini_get("session.gc_maxlifetime"); 
//$directory = dirname(__FILE__); // this is /home/user/public_html/myfolder
//echo $directory;
//session_save_path('/home/user/public_html/myfolder/store_sessions');
session_save_path('C:\wamp\www\WEB_APPLICATION\SESSIONS\store_sessions');
ini_set('session.gc_probability', 1);

session_start(); 
 
$session_begin = $_SESSION['begin'];
 
$session_end = $_SESSION['end'];

if($_POST['session'] == "test") {

$_SESSION['mysession'] = $_POST['session'];

if(!$session_begin || !$session_end){
 
$_SESSION['begin'] = time(); // taking now logged in time
 
$_SESSION['end'] = $_SESSION['begin'] + (60 * 60) ; // ending a session in 1 hour
 
}
 
$now = time();
 
echo $_SESSION['begin']."-".$_SESSION['end']."-".$now;
 
if($now > $_SESSION['end']){
session_destroy();
session_unset();
 
echo "Session ended";
}
}

$now = time();
echo "<br/>".$_SESSION['begin']."-".$_SESSION['end']."-".$now;
if($now > $_SESSION['end']){
session_destroy();
session_unset();
 
echo "Session ended";
}else{echo "<br/>Session still in progress";}
?>

<form method ="post"action="<?php echo $_SERVER['PHP_SELF'] ;?>">
<input type = "text" name="session" value ="" />
<input type = "submit" name="submit" value ="Submit" />
</form>
New Session File:

The new session file is stores in the stored_sessions folder with a name like sess_i08fdukpmpu3dbuv9smncr60i3. You can view the file with Notepad.

Contents of session file:

mysession|s:4:”test”;begin|i:1351339877;end|i:1351343477;

PHP / MYSQL Update Multiple Rows With a Foreach Loop

This exercise will show how to output all rows of table data and do a mass update at the same time using a foreach loop.The following can be used to update multiple rows

using a foreach loop. Here is how it works. All form inputs make arrays for each value. Thus, ids, firstnames, emails, etc become separate arrays when the submit button is clicked. However, what we want to do is match all keys from each array to make new arrays based on keys. For example, the first key in the id array is the id for the first element in the firstnames array. The array of ids is is run through a foreach loop. We take the key and id. Then, the $members_info array is created which uses each member’s id and its matching key to match the keys for each other array. Here is a simple explanation. Since the first member in the array will have a key for its id to be [0], we grab each other value from the other arrays where the key is [0]. The members_info array does this for each and every entry.

After all the members_info arrays are built, each member is separated into a string called $member_info. Then, we simply select this member’s id and update the table for each and every member. If new output is inserted, it gets updated. If no info changes, the data remains intact.

<?php 
include ('connect.inc');
$db=public_db_connect();   
if(!empty($_POST['submit'])) {

### Here we get post variables for each person

$ids			= $_POST['id'];
$firstname 		= $_POST['firstname'];
$lastname	    = $_POST['lastname'];
$email 			= $_POST['email'];
$height 	 	= $_POST['height'];
$age  			= $_POST['age'];
$weight		 	= $_POST['weight'];
$mydate 		= date("Y-m-d"); 

foreach ($ids as $key => $id){
//echo $key."-".$id."<br/>";
$members_info[] = $id.",".$firstname[$key].",".$lastname[$key].",".$email[$key].",".$height[$key].",".$age[$key].",".$weight[$key].",".$mydate;

if(!in_array($key, $firstname)){
continue;
}

}

//print_r($members_info);

#The loop below takes in account of all the rows in the table. Then an update is applied to each row; whether it is changed or not. If the row is unchanged, it updates based on the original values. 

foreach ($members_info as $member_info) {
$all = explode(",",$member_info);

$id 			= $all[0];
$firstname    	= $all[1];
$lastname   	= $all[2];
$email  		= $all[3];
$height	     	= $all[4];
$age 			= $all[5];
$weight 		= $all[6];

$command = "SELECT * FROM table_sort WHERE id='$id' ";
$result = mysqli_query($db, $command);

if (mysqli_num_rows($result) > 0) {

$command = "UPDATE table_sort SET firstname='$firstname', lastname='".addslashes($lastname)."', email='$email', height='$height', age='$age', weight='$weight' WHERE id='$id' ";
$result = mysqli_query($db, $command);	

} else {
echo "There are no records!";
}

} 
print_r($all_post_variables_array);
?>
	<div>Directory has been updated!</div>
<?php
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="directory">
<div><p><input type="submit" name="submit" value="Update" /></p></div>
<div style="clear:both;"></div>
<?php
?>
<div>
<table style="width:100%;">
<tr><th>id</th><th>Last Name</th><th>First Name</th><th>Email</th><th>Height</th><th>Age</th><th>Weight</th><th>Date</th>
</tr>
<?php
################ Here we create the list of all entries from the database table and the form names use [] to create arrays of post variables for each entry.

		$command	= "SELECT * FROM table_sort WHERE id >0 ORDER BY id ASC ";
		$result = mysqli_query($db, $command); 
		while ($row = mysqli_fetch_assoc($result)) {
	//Remove a person if you want
		//if($row['lastname'] == 'Zhang') { continue; }		
		$myid			= $row['id'];
		$first			= $row['firstname'];
		$last 			= stripslashes($row['lastname']);
		$email_address  = $row['email'];
		$height  		= $row['height'];
		$age  			= $row['age'];
		$weight  		= $row['weight'];
		$mydate  		= $row['date'];		
		
		echo '<tr>';
		echo '<input type="hidden" name="id[]" value="'.$myid.'" />';
		echo '<td>'.$myid.'</td>';
		echo '<td><input type="text" name="lastname[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$last.'"/></td>';
		echo '<td><input type="text" name="firstname[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$first.'"/></td>';
		echo '<td><input type="text" name="email[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$email_address.'"/></td>';
		echo '<td><input type="text" name="height[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$height.'"/></td>';
		echo '<td><input type="text" name="age[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$age.'"/></td>';
		echo '<td><input type="text" name="weight[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$weight.'"/></td>';
		echo '<td><input type="text" name="date[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$mydate.'"/></td>';
		echo '</tr>';
		}
?>
</table>
</div>
<p><input type="submit" name="submit" value="Update" /></p>
</form>

Update Multiple Rows With PHP

The purpose of this tutorial is to output rows of data into input fields. Then, you can update any number of rows at the same time.

The following can be used to update multiple rows using a for loop. Here is how it works. All form inputs make arrays for each value. Thus, ids, firstnames, emails, etc become separate arrays when the submit button is clicked. To organize each array and singular member data, the id array is counted. Then, the incrementing i++ value is added to each member to make them distinct. Since each member will have all separate values from the for loop, mass updates can take place for each and every member.

<?php 
include ('connect.inc');
$db=public_db_connect();   
if(!empty($_POST['submit'])) {

### Here we get post variables for each person

$id				= $_POST['id'];
$firstname 		= $_POST['firstname'];
$lastname	    = $_POST['lastname'];
$email 			= $_POST['email'];
$height 	 	= $_POST['height'];
$age  			= $_POST['age'];
$weight		 	= $_POST['weight'];
$mydate 		= date("Y-m-d"); 
 
// count the array of ids
$count = count($id);

// shows array of ids when submitted
print_r($id);

#The loop below takes in account of all the rows in the table. Then an update is applied to each row; whether it is changed or not. If the row is unchanged, it updates based on the original values. 

$i=0;

for ($i=0; $i < $count; $i++) {

// append the value of $i to each member
$id_from_loop 			= mysqli_real_escape_string($db, $id[$i]);
$lastname_from_loop 	= mysqli_real_escape_string($db, $lastname[$i]);
$firstname_from_loop 	= mysqli_real_escape_string($db, $firstname[$i]);
$email_from_loop		= mysqli_real_escape_string($db, $email[$i]);
$height_from_loop		= mysqli_real_escape_string($db, $height[$i]);
$age_from_loop 			= mysqli_real_escape_string($db, $age[$i]);
$weight_from_loop 		= mysqli_real_escape_string($db, $weight[$i]);

$command = "SELECT * FROM table_sort WHERE id='$id_from_loop' ";
$result = mysqli_query($db, $command);

if (mysqli_num_rows($result) > 0) {

$command = "UPDATE table_sort SET firstname='$firstname_from_loop', lastname='$lastname_from_loop', email='$email_from_loop', height='$height_from_loop', age='$age_from_loop', weight='$weight_from_loop' WHERE id='$id_from_loop' ";
$result = mysqli_query($db, $command);	

} else {
echo "There are no records!";
}

} 
?>
	<div>Directory has been updated!</div>
<?php
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="directory">
<div><p><input type="submit" name="submit" value="Update" /></p></div>
<div style="clear:both;"></div>
<?php
?>
<div>
<table style="width:100%;">
<tr><th>id</th><th>Last Name</th><th>First Name</th><th>Email</th><th>Height</th><th>Age</th><th>Weight</th><th>Date</th>
</tr>
<?php
################ Here we create the list of all entries from the database table and the form names use [] to create arrays of post variables for each entry.

		$command	= "SELECT * FROM table_sort ORDER BY id ASC ";
		$result = mysqli_query($db, $command); 
		while ($row = mysqli_fetch_assoc($result)) {
	//Remove a person if you want
		//if($row['lastname'] == 'Zhang') { continue; }		
		$myid			= $row['id'];
		$first			= $row['firstname'];
		$last 			= $row['lastname'];
		$email_address  = $row['email'];
		$height  		= $row['height'];
		$age  			= $row['age'];
		$weight  		= $row['weight'];
		$mydate  		= $row['date'];		
		
		echo '<tr>';
		echo '<input type="hidden" name="id[]" value="'.$myid.'" />';
		echo '<td>'.$myid.'</td>';
		echo '<td><input type="text" name="lastname[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$last.'"/></td>';
		echo '<td><input type="text" name="firstname[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$first.'"/></td>';
		echo '<td><input type="text" name="email[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$email_address.'"/></td>';
		echo '<td><input type="text" name="height[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$height.'"/></td>';
		echo '<td><input type="text" name="age[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$age.'"/></td>';
		echo '<td><input type="text" name="weight[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$weight.'"/></td>';
		echo '<td><input type="text" name="date[]" style="width: 95%; padding: 3px; margin: 3px;" value="'.$mydate.'"/></td>';
		echo '</tr>';
		}
?>
</table>
</div>
<p><input type="submit" name="submit" value="Update" /></p>
</form>

Jquery Pagination and PHP

This example uses a Jquery plugin called DataTables to paginate results from PHP or mySQL. For example, the results could be many items from an rss feed or rows from a mySQL query. The plugin can be dowloaded at http://datatables.net. This plugin makes it very easy to automatically sort ant amount of data into a clean, paginated, stylish table.

To use DataTables,
1) Download it.
2) Add the plugin script into the head of your file.
3) Add a Jquery function to initialize it:
Function:
$(document).ready(function(){
$(‘#example’).dataTable();
});
4) Make sure your <table> has id=”example” and you use <thead> and <tbody> tags. The file pagination_datatables_bare_bones.php already has done this.
5) Customize the css.
<?php
//session_start();
include('connect.inc');
$db= public_db_connect();

?>

<html>
<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script src="DataTables/media/js/jquery.dataTables.min.js" type="text/javascript"></script>
</head>
 

  <script>
  $(document).ready(function(){
    $('#example').dataTable();
});
  </script>
 <?php

####can put links too.
$link1= "{$_SERVER['PHP_SELF']}?orderby=lastname";
//$my link = '<td align="left"><a href="'.$link1.'"><b>First Name</b></a></td>';
		//echo $order_by;		
	echo '<table  class="display" id="example" align="center" cellspacing="0" cellpadding="5" bgcolor="#E0606B" width="100%">
	<thead><tr>
		<th align="left"><b>Last Name</b>'.' '.'<a href="'.$_SERVER['PHP_SELF'].'?orderby=lastname asc"><b>asc</b></a>'.' '.'<a href="'.$_SERVER['PHP_SELF'].'?orderby=lastname desc"><b>desc</b></a></th>
		<th align="left"><a href="'.$_SERVER['PHP_SELF'].'?orderby=lname"><b>First Name</b></a></th>
		<th align="left"><b>Email</b></th>
		<th align="left"><b>Age</b></th>
		<th align="left"><b>Weight</b></th>
		<th align="left"><b>Height</b></th>
		<th align="left"><b>Date</b></th>
	</thead></tr>';


$command = "select * from table_sort ORDER by date DESC"; 
$result = mysqli_query($db, $command);
 
				$command2= "SELECT DISTINCT email, firstname, lastname, age, weight, height, date FROM table_sort ORDER BY lastname asc ";
				$result2 = mysqli_query($db, $command2);
				if ($result2 && mysqli_num_rows($result2) > 0) {
		
			    echo  '<tbody>';
			   while ($row = mysqli_fetch_assoc($result2)) {
			 
								
		$bg =($bg=='#A7C6BA' ? '#f9f9f9' : '#A7C6BA');
		echo '<tr bgcolor="' . $bg . '">
			<td align="left">' .$row["lastname"]. '</td>
			<td align="left">' .$row["firstname"]. '</td>
			<td align="left">' .$row["email"]. '</td>
			<td align="left">' .$row["height"]. '</td>
			<td align="left">' .$row["age"]. '</td>			
			<td align="left">' .$row["weight"]. '</td>
			<td align="left">' .$row["date"]. '</td>
			</tr>';
			}			
			
	echo '</tbody></table>';	

}

 ?>
<div style="text-align:center;"></div>
</div>


Css Transparent Background

When you work with css and many divs nested within div tags, you will often want to use the background of the parent div. The transparent background makes this fast and simple.

To inherit background within a nested div,

 background:transparent; 

Ajax, Jquery and GET Variables

This example uses jquery to make an Ajax call via the ‘GET’ method. This method is coded almost identically to the previous ‘POST’ sample. For example, when you select the checkbox, the Jquery change() function is triggered.

After that, if the check box is checked, a variable = 1 is created. If it is deselected, the variable becomes = 2. Then, asyncronous ajax takes places with the proper data and url. Essentially, new get variables are created when you click the checkbox. Finally, the get variables are used to update the database table with basic php / mySQL.

<?php
header('Cache-Control: no cache'); //no chache but no error
session_start();
include ("connect.inc");
$db=public_db_connect();
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
//alert("hi");
	$(document).ready(function(){
	
		$("input[name*='mycheckbox']").change(function(){
		
			var variable = $(this).attr("id");
			
			if ($(this).is(':checked')) {
			
			var variable2 = 1;
			
			} else {
			var variable2 = 2;
			}
						
			alert(variable);
			
			alert(variable2);
			/*var dataString = 'variable=' + variable + '&variable2=' + variable2;*/
			$.ajax({
				type: "GET",
				cache: false,
				url: "ajax-get-jquery.php",
				data: "variable="+variable +"&variable2="+variable2,
				/*data: { variable2: "variable2" },*/
				/*data: dataString,*/
				success: function(msg){
					alert("Success!");
					/*alert(variable2);*/
				}
			});
			
		});
	});
</script>
  	</head>
	<body>
	<?php
	$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	}

	$variable2 = $_GET['variable2'];
    $variable = $_GET['variable'];

$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	//echo $row['checking'];
	}

if($_GET['variable2']){
echo $variable2;
	$commandb = "UPDATE ajax SET checking='{$_GET['variable2']}' WHERE id=1";
	$resultb = mysqli_query($db, $commandb) ; 
	}	else{
	$commandc = "UPDATE ajax SET checking=3 WHERE id=1";
	$resultc = mysqli_query($db, $commandc) ; 
	}
	?>	
	
	<form method ="post" action = "">
<input type= "checkbox" name="mycheckbox" id="checker" value="1" />
</form>

Ajax Jquery and Post Variables

This example uses jquery to make an Ajax call via the ‘POST’ method. Here is how it works. When you select the checkbox, the Jquery change() function is triggered. Then, if the check box is checked, a variable = 1 is created. If it is deselected, the variable becomes = 2. Then, asyncronous ajax takes places with the proper data and url. Essentially, new post variables are created without needing to click a ‘submit’ button. Finally, the post variables are used to update the database table.

<?php
header('Cache-Control: no cache'); //no chache but no error
session_start();
include ("connect.inc");
$db=public_db_connect();
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

	$(document).ready(function(){

		$("input[name*='mycheckbox']").change(function(){
	
			var variable = $(this).attr("id");
		
			if ($(this).is(':checked')) {
		
			var variable2 = 1;
			
			} else {
			var variable2 = 2;
			
			}
						
			alert(variable);
		
			alert(variable2);
			/*var dataString = 'variable=' + variable + '&variable2=' + variable2;*/
			$.ajax({
				type: "POST",
				cache: false,
				url: "ajax-post.php",
				data: "variable="+variable +"&variable2="+variable2,
				/*data: { variable2: "variable2" },*/
				/*data: dataString,*/
				success: function(msg){
					alert("Success!");
					/*alert(variable2);*/
				}
			});
			
		});
	});
</script>
  	</head>
	<body>
	<?php
	$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	}

	$variable2 = $_POST['variable2'];
    $variable = $_POST['variable'];

$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	//echo $row['checking'];
	}

if($_POST['variable2']){
echo $variable2;
	$commandb = "UPDATE ajax SET checking='{$_POST['variable2']}' WHERE id=1";
	$resultb = mysqli_query($db, $commandb); 
	}	else{
	$commandc = "UPDATE ajax SET checking=3 WHERE id=1";
	$resultc = mysqli_query($db, $commandc) ; 
	}
	?>	
	
	<form method ="post" action = "">
<input type= "checkbox" name="mycheckbox" id="checker" value="1" />
</form>

Convert PHP Integers Array Into Javascript Array With Jquery

This tutorial shows how we can take an array of numbers from php and use it an array in Javascript. Here is how it works. We have a web page with a list of entries. Each entry has a checkbox next to it and its value is the entry’s id.

With Jquery, we use the change() function for the checkboxes. If a check box is selected or deselected and it is greater than 15, we use the alert() function to show the id of the changed checkbox.

Then, we use php / mySQL to make an array of numbers. To be useful in Javascript, we use the implode function to turn the array into a string that separates the ids with commas. Then, the $ids_string variable is the new Javascript variable that is equal to the php string.

We can use use the string, or convert it to an array with ‘myArray = new Array(ids_string);’ or ‘var myArray = $.makeArray(ids_string);’. Then, the each() function is used to sort the array.

<script type="text/javascript">
$(document).ready(function(){
	$("input.check").change(function() {
	var value = $(this).val(); 
	
	var Class = $(this).attr('class');
	
	if(value > 15 && Class == "check"){
		$(this).css("color", "red");
		alert(value);
		<?
		$command = "SELECT * FROM leads ";
		$result = mysqli_query($db, $command);
		while ($row = mysqli_fetch_assoc($result)){
		//$val = $row['id'];
		$val = $row['id'];
		$names_array[] = $val;
		}
		## PHP Array to Javascript String
		$ids_string = implode(",", $names_array); // create a string from the array of ids
		?>
		//alert ("<?php echo $ids_string; ?>");
		ids_string = "<?php echo $ids_string; ?>"; // now the javascript variable is set
		alert (ids_string);

		// sort through string  ie) if the value is in string		
		
        //PHP STRING to Javascript Array
		//myArray = new Array(ids_string); //convert string to array method a
		var myArray = $.makeArray(ids_string); //convert string to array method b 
		var myArray = ids_string.split(','); // for names 
		$.each(myArray,  function(k, v){
    alert( "Key: " + k + ", Value: " + v );
	});
// sort through array and look for id in the array

	}	
	else {
	$(this).css("color", "#000000");
	}		
	});	
});		
</script>

Converting PHP Array Into Javascript Array

The purpose of this tutorial is to demonstrate how we can take an array from php and use it an array in Javascript. Here is the basics of the code. We have a web page with a list of entries. Each entry has a checkbox next to it and its value is the entry’s id.

With Jquery, we use the change() function for the checkboxes. If a check box is selected or deselected and it is greater than 15, we use the alert() function to show the id of the changed checkbox.

Then, we use php / mySQL to make an array of names. To be useful in Javascript, we use the implode function to turn the array into a string that separates the names with commas.

Then, the $names_string variable is the new Javascript variable that is equal to the php string. We can use use the string, or convert it to an array with ‘myArray = new Array(names_string);’ or ‘var myArray = $.makeArray(names_string);’.

Finally, the each() function is used to sort the array.

<script type="text/javascript">
$(document).ready(function(){
	$("input.check").change(function() {
	var value = $(this).val(); 
	
	var Class = $(this).attr('class');
	
	if(value > 15 && Class == "check"){
		//$(this).css("color", "red");
		alert(value);
		<?
		$command = "SELECT * FROM tablename ";
		$result = mysqli_query($db, $command);
		while ($row = mysqli_fetch_assoc($result)){
		//$val = $row['id'];
		$val = $row['firstname'];
		$names_array[] = $val;
		}
		## PHP Array to Javascript String
		$names_string = implode(",", $names_array); // create a string from the array of ids
		?>
		//alert ("<?php echo $names_string; ?>");
		names_string = "<?php echo "".$names_string.""; ?>"; // now the javascript variable is set
		alert (names_string);

		// sort through string  ie) if the value is in string		
		
        //PHP STRING to Javascript Array
		//myArray = new Array(names_string); //convert string to array method a
		var myArray = $.makeArray(names_string); //convert string to array method b 
		var myArray = names_string.split(','); // for names 
		$.each(myArray,  function(k, v){
    alert( "Key: " + k + ", Value: " + v );
	});
// sort through array and look for id in the array

	}	
	else {
	$(this).css("color", "#000000");
	}		
	});	
});		
</script>

Copying All Files To a New Folder With PHP

The simple objective is to move all files from one folder to another another folder. The files could be images, css files, javascript files, or anything else.

Let’s analyze the code. The variable $mydir is the name of your new directory where you want to move files. If there is no directory, we make the directory with the mkdir() function. Now that the directory is in place, the files must be moved from point a to point b. The glob() function is used to make an array of all the files from the current images directory where the original images are located. Then, a foreach loop is used to move each file from the array into the new folder. The copy() function actually moves the files from one directory to another.

 // images folder creation
	   $mydir = dirname( __FILE__ )."/html/images";
	   if(!is_dir($mydir)){
	   mkdir("html/images");
	   }
	   // Move all images files
	   $files = glob("images/*.*");
	   foreach($files as $file){
	   $file_to_go = str_replace("images/","html/images/",$file);
       copy($file, $file_to_go);
	   }

Submitting Passwords With PHP

When you build websites with user registration and passwords, you may find you will need to allow users to update passwords and other fields. However, there are some slight differences you must take into consideration when you update text and passwords. With text, you often use a sanitizing function like addslashes or mysql_real_escape_string() to escape the data. With passwords, you will sanitize the string with the mysql_real_escape_string() function and use a password function like sha() or md5() to convert the text into an encrypted password string.

Is is very important to note that when you work with passwords, an empty $_POST variable and a password function applied to the $_POST variable are note the same thing. The latter is actually a encrypted string.

xxx
$password = $_POST['password']; // This is empty
$password = mysql_real_escape_string($_POST['password']); // This is empty
$password = mysql_real_escape_string(sha1($_POST['password'])); // This is not empty

if(empty($password)){
echo "Posted password is empty";
}else{
echo "Posted password is not empty";
}


PHP MYSQL Transactions and Rollbacks

If you decide to create a php / mySQL application which will use a fair amount of insert, update and delete queries, you may want to use transactions with your mySQL queries. Transactions allows for data integrity. It can only help keep your data more precise. In order to use transactions, the database table storage engine should use the InnoDB.

Transactions work like this. Multiple mySQL statements will be executed only if the requirements are met. If anything is off, nothing happens.

The code below shows a simple transaction. If there is asuccess, the loop runs. If there is no success, the loop does dot show anything.

include('connect.inc');

	   $success = true;  // transaction success

       //start transaction
       $command = "SET AUTOCOMMIT=0"; // this command sets mysql up to make sure that COMMIT or ROLLBACK command is used to execute a query.
       $result = mysqli_query($db, $command);
       $command = "BEGIN"; // this starts the transaction
       $result = mysqli_query($db, $command);
                 
       $command = "SELECT id FROM table_sort ";
       $result = mysqli_query($db, $command);  
       while($row = mysqli_fetch_assoc($result)){
       $id = $row['id'];
	   $ids[] = $id;
	    echo "We got the array!";
		}	        		  
			  if (mysqli_num_rows($result) <2) { // checking for success here
                   $success = false;
              }  else if (mysqli_num_rows($result) >2){
			     $success = true;
			  echo "We got the array!";
			  }
           
       if (!$success) { // if success is false, do this
              $command = "ROLLBACK"; // this command does not allow the statement "We go the array" to display if the $result is false
              $result = mysqli_query($db, $command);
              $error = "We've rolled back and did not create the array because something went wrong along the way.";
			  echo $error;
       }
       else {
	          $command = "COMMIT"; // transaction will now occur since everything went well
              $result = mysqli_query($db, $command);
      }
       $command = "SET AUTOCOMMIT=1";  // Now, mysql continues on without transactions
	   $result = mysqli_query($db, $command);

Passing An Array Into A Function

With PHP, it is a great thing to be able to pass arrays or strings into an array. The following example shows a simple array being passed into function. Once the array is in the function, the print_r($members) function displays the array keys and values.

function getmembers($input){
print_r($input);

}

include('connect.inc');
$db = public_db_connect();
$command = "SELECT * FROM table_sort WHERE id < 10";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
$memberID = $row['id'];
$members[] = $memberID;
}

$myvar = getmembers($members); 
//print_r($members);

PHP preg_replace() Function

The preg_replace() function makes it very easy to change data between a starting character and ending the character. The example code below demonstrates how it can be used to remove anything in between angle brackets(<>) and in between regular brackets.

include('connect.inc');
$db = public_db_connect();
$command = "SELECT * FROM cms ";
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)){
$tags = $row['mid'];
echo "Look at source code:".$tags."</br/>";
$tag = preg_replace('#\<.*?\>#s', '', $tags); 
echo $tag;
}

$brackets = "(in brackets)";
echo "<br/>".$brackets;
$no_brackets = preg_replace('#\(.*?\)#s', 'no brackets', $brackets); 
echo "<br/>".$no_brackets;

PHP in_array Function

The in_array() function for php can be quite useful at sometimes. It allows you to check if data is in an array. If there is data, you can customize the next step and if there is no match in array you can execute a different command. In simple English, it is similar to the following expression.

Expression:
“I have an orange. If there is an orange in the bag of fruit, do not add the second orange there. But, if there is not an orange, add my orange to the bag of fruit.

The code below is an example where the in_array() function is used to check an array for a matching row from the database. If it does not find a match, the row is added to the members array. If it does find a match, the loop continues without adding the row to the array.

Advanced Note
The in_array() function can be very useful and perhaps the best method to use when you need to grab the desired data from a table when you cannot sort it through mySQL. For example, in a large database application, there may not be a matching index for the table where you need to select exact data.

include('connect.inc');
$db = public_db_connect();
$command = "SELECT * FROM table_sort WHERE id > 0";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
$memberID = $row['id'];
$first_name = $row['firstname'];
$last_name = $row['lastname'];
//echo $memberID;

if(in_array($row['id'], $members)){continue;}
$members[] = $memberID.",".$first_name.",".$last_name;
}

print_r($members);

Creating HTML Web Pages From PHP Files With PHP

This tutorial below explains how you can grab a php file on the Internet and rewrite and save it as an html file using php.

Note: This tutorial must be used in a file that exists in the same directory. For example, this example grabs all website urls like page1.php, page2.php that exists in the tablename table. Then, it grabs the html content of each url that has a file within the the same folder; such as example.com/myfolder/page1.php. After the contents for the web page is grabbed, it writes a new file to a folder called html. Thefore, the original file example.com/myfolder/page1.php actually becomes example.com/myfolder/html/page1.php.

Alternatively, you could just have made a hard coded array for the urls; like
$urls = array(‘example.com/myfolder/page1.php’, example.com/myfolder/page2.php”);

## FUNCTION TO GRAB URL
function my_page_URL() {

$page_URL = 'http';
if ($_SERVER["HTTPS"] == "on") {$page_URL .= "s";}
$page_URL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$page_URL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$page_URL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $page_URL;
}

## GET WEB PAGE
## We use curl to get the url because file_get_contents() function will interpret example.com/myfile.php different than myfile.php
## if the absolute url is not grabbed and the relative url is grabbed, file_get_contents() will grab the actual file code and not ## what ouputs in a browser.
$mycurl=my_page_URL();

       ##GET URLS
       $command = "SELECT urls FROM tablename ";
       $result = mysqli_query($db, $command);  
       while($row = mysqli_fetch_assoc($result)){
       $url = $row['url'];
       $urls[] = $url;
		}	

           ##LOOP EACH PAGE		
	   foreach($urls as $url){
	   //echo $url;
	   # we don't want the file downloads.php so we skip it from making a page called downloads.html
	   if($url == "downloads.php"){continue;}
	   echo $url;
	   $myurl = str_replace("make_html.php",$url,$mycurl);
	   $htmla = file_get_contents($myurl);
	   echo $htmla;
	   $html = str_replace(".php",".html",$url);
	   // echo $html;
	   $file = "html/".$html;
	   $fp = fopen($file, 'w');
	   fwrite($fp, $htmla);
	   fclose($fp);
	   }

Example #2 Grabbing Any Web Page and Making It HTML

## FUNCTION TO GRAB URL

function my_page_URL() {

$page_URL = 'http';
if ($_SERVER["HTTPS"] == "on") {$page_URL .= "s";}
$page_URL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$page_URL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$page_URL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $page_URL;
}
## This tutorial below explains how you can grab a php file on the Internet and rewrite and save it as an html file using php. 

##GET WEB PAGE
## We use curl to get the url because file_get_contents() function will interpret example.com/myfile.php different than myfile.php
## if the absolute url is not grabbed and the relative url is grabbed, file_get_contents() will grab the actual file code and not ## what ouputs in a browser.
$mycurl=my_page_URL();

$urls = array('http://example.com/learn-web-design.php','http://example.com/services.php');		

##LOOP EACH PAGE		
	   foreach($urls as $url){
	   //echo $url;
	   # we don't want the file downloads.php so we skip it from making a page called downloads.html
	   if($url == "downloads.php"){continue;}
	   echo $url;
	   //$myurl = str_replace("write_new_file.php",$url,$mycurl);
	   $htmla = file_get_contents($url);
	   echo $htmla;
	   
	   // echo $html;
	   $html = str_replace("http://example.com/","",$url);
	   $html = str_replace(".php",".html",$html);
	   $file = "html/".$html;
	   $fp = fopen($file, 'w');
	   fwrite($fp, $htmla);
	   fclose($fp);
	   }

PHP MYSQL Using Two or More Database Connections

In vast majority of php applications, one database is sufficient to run the application. However, you could encounter a situation where you need to use two database connections because you want to sink user data. One such reason could be that you want to allow a user to login into another application from the current running application. Bridging the two logins can allow applications to connect and thus; you can do more. Another reason why you may want to use another database is that you just want to grab the data from a different application.

The code below shows how you can simply connect and select data from two databases. However, you could run insert, update and delete commands from either database.

include ("connect.inc");
$db=public_db_connect();

$command_a = "SELECT * FROM table_sort WHERE id > '1' ";
	$result_a = mysqli_query($db, $command_a);
	while($row_a = mysqli_fetch_assoc($result_a)){
	$firstnamea = trim($row_a['firstname']);
	echo "From Database #1: ".$firstnamea."<br/>";
	}
	
	echo "<br/><br/>";
	
require ('header.inc');
$db2=public_db_connectb();
	$command_b = "SELECT * FROM table_sort WHERE id > 1 ";
	$result_b = mysqli_query($db2, $command_b);
	while($row_b = mysqli_fetch_assoc($result_b)){
	$firstnameb = $row_b['firstname'];
	echo "From Database #2: ".$firstnameb."<br/>";
	}
	
mysqli_close($db);

Using Databases With Web Host Manager and Cpanel

By now, you may know that Web Host Manager is quite a fine tool to administrate accounts and your Linux Hosting account. Having the ability to create new accounts with new cpanels allows for all sorts of web management.

Although you may want to keep all database usage and files within specific accounts, you are not required to do so. You do have the option to use databases from different accounts. For example, if you have one account called mainaccount and another account called mysecondaccount, you could connect to databases from mainaccount. The simple trick is to just use the aaccount prefix which appends to all database usernames and databases.

The examples below show how you can connect to a database from another account. You simply add the specific connection variables into your file(s).

Database Connection to mainaccount:
    $host = “localhost”;  
    $user = “mainaccount_name”;
    $pw = “add_password_here”;
    $database = “mainaccount_databasename”;

Database Connection to mysecondaccount:
    $host = “localhost”;  
    $user = “mysecondaccount_name”;
    $pw = “add_password_here”;
    $database = “mysecondaccount_databasename”;


Web Host Manager Accounts and Databases

Web Host Manager is a fantastic tool to order accounts and databases. Generally speaking, Web Host Manager is used to create accounts where you want to keep accounts organized and separated.

Here are various reasons why you may want to create separate accounts with Web Host Manager:
1) Some clients may require their own cpanel. Therfore, you only want them to administrate their own websites, emails and databases.
2) You want to add an SSL certificate to a specific account.
3) You want to keep a large project in one place. Addon domains and multiple databases can get messy after a while.
4) if you need more resources., tIt makes it easy to move an entire account to a new server.


Web Host Manager Moving Addon Domain To New Account

Web Host Manager allows webmasters to remove addon domains from one account and move it to a new account. In fact, that order must be done first. The tutorial below explains how to perform this procedure.

To move an addon domain to its own account,
1) Save all files and databases that you want to change. You do this with the Cpanel where the addon domain is located.
2) Remove all dns records.
To delete the DNS zone,
a) Go to DNS Functions >Select ‘Delete a DNS Zone’.
3) Unpark the domain with WHM.
To unpark a domain,
a) Go to Account information >List parked Domains >Select Unpark for the desired domain name.
4) Create a New Account.
To create a New account,
a) Select Main > Account Functions >Create New Account
b) Fill in domain, username, password, email
c) Choose package
d) Select ‘Create’

Note:
You may need to make a few adjustments during or after you create the new account; such as editing the package.
To edit a package,
1) Look for packages in left column.
2) Select ‘Edit package’ >Modify >Save as desired

Update DNS Zones
You may need to update the DNS zones.
To edit a DNS zone,
1) Select ‘DNS Functions’ >Edit DNS Zone
2) Modify and save, if necessary.

GET THE SITE RUNNING
To get the new site up and running,
1) Login to the new Cpanel account.
2) Add any databases that are needed.
3) FTP all files into the new account.
4) Change any database connection files so that the new prefix and login credentials for your new account. For example, if your site was previously in an account called myname, and the new account is called newname, you will need to change all database prefixes and database names to the newname.
5) Troubleshoot the website. At this point, you should be able to open up the website in your browser.


Joomla RSS Feed Links

Joomla has all sorts of plugins and methods for which to create rss feeds. All in all, the RSS feeds will have a specific url like http://example.com/Subscribe-to-blog-rss-feed.html

Once you have the link, you can use it on your page to allow your users to subscribe to your feeds. If you have good, regular content, it is a simple method to allow your subscribers to keep up to date.


RSS Feeds and SEO

Most regular bloggers have a common goal; get more traffic and more regular readers. Therefore, giving users the ability to subscribe to your RSS feeds is one such useful feature to keep them coming back. Some people like feeds and will seek your new articles. However, an additional gem is that RSS feeds on your website that are stored with Google Reader apparently gives you better rankings on your website. Since ‘Google Reader’ is the most popular method to subscribe and view feeds, this simple rss feed subscription service should not be overlooked.

PHP Rss Feeds With Magpie

This lesson explains the usage of Magpie to parse multiple rss feeds. Installing Magpie is shown here.

Firstly, the file rss_fetch.inc needs to be imported with the require() function in order to parse the feeds in the first place. Then, an array of urls is created for the various RSS feeds. Then, one at a time, the rss feed urls go through the fetch_rss() function located in the Magpie installation. Next, Magpie returns an array called $items and that data is parsed. Finally, the data is printed. Note, the feeds will output the data from the first url, then output the second url. If you want to combine the feeds and order them all like they come from the same place, please see this tutorial for parsing rss feeds.

require('magpie/rss_fetch.inc');
	
	$urls = array('http://vancouver.en.craigslist.ca/cta/index.rss', 'http://vancouver.kijiji.ca/f-SearchAdRss?CatId=174&Location=80003');
	
	foreach($urls as $url) {
	$rss = fetch_rss($url);

foreach ($rss->items as $item ) {
	$title = $item[title];
	$url   = $item[link];
	$description   = $item[description];
	$date = $item['dc']['date'];
	echo "<a href='".$url."'>".$title."</a>-".$description."-".$date."<br>";
//make array here
}
}


Code Samples:
Parse Single URL RSS Feed
Parse Multiple URLs RSS Feed Into a Table Part 2

PHP Rss Feeds With Magpie

This tutorial shows how to use Magpie to parse multiple rss feed. If you need to know how to install Magpie in 30 seconds, please see this RSS Feed tutorial.

Here is how php parses the multiple rss feeds. First of all, we require the file rss_fetch.inc so that we can parse the feeds in the first place. Then, we create an array of urls for the various RSS feeds. Then, one at a time, the rss feed urls go through the fetch_rss() function located in the Magpie installation. Next, Magpie returns an array called $items, and that data is parsed. Within the foreach loop, the $tot_array array is made. The array contains each item that we wanted. The array eventually got huge. The date is the first element in the array for sorting purposes. Therefore, after using the rsort() function, we got the array ordered by date descending. Finally, the $tot_array was output into a table.

require('magpie/rss_fetch.inc');
	
	$urls = array('http://vancouver.en.craigslist.ca/cta/index.rss', 'http://vancouver.kijiji.ca/f-SearchAdRss?CatId=174&Location=80003');
	
	foreach($urls as $url) {
	$rss = fetch_rss($url);

foreach ($rss->items as $item ) {
	$title = $item[title];
	$url   = $item[link];
	$description   = $item[description];
	$date = $item['dc']['date'];

	//make array here
$tot_array[] = $date.",".$title.",".$url.",".$description;
}
}

//print_r($tot_array);
rsort($tot_array);

echo '<table>
<thead>
<th>Title</th>
<th>Description</th>
<th>Date</th>
</thead>';

foreach($tot_array as $tot) {
$all = explode(",",$tot);
$date = date("Y-m-d",strtotime($all[0]));
$title = $all[1];
$url = $all[2];
$description = $all[3];
//echo $tot."<br/>";
echo '<tr>';
echo '<td><a href="'.$url.'">'.$title.'</a></td>';
echo '<td>'.$description.'</td>';
echo '<td>'.$date.'</td>';
echo '</tr>';
}
echo '</table>';


More Coding Samples:
Parse Single URL RSS Feed
Parse Multiple URLs From RSS Feed Part 1

PHP Rss Feeds With Magpie

This tutorial shows how to use Magpie to parse an rss feed. If you need to know how to install Magpie in 30 seconds, please see this PHP RSS Feed tutorial.

Here is how php parses the rss feed. We require the file rss_fetch.inc so that we can parse the feed. Then, we set which RSS feed url is used for the feed. Then, the rss feed url is run through the fetch_rss() function located in the Magpie installation. Then, Magpie returns an array called $items and that data is parsed. Within the foreach loop, all data for each rss feed entry is printed.

require('magpie/rss_fetch.inc');
	
	$url = 'http://vancouver.en.craigslist.ca/cta/index.rss';
	$rss = fetch_rss($url);

foreach ($rss->items as $item ) {
	$title = $item[title];
	$url   = $item[link];
	$description   = $item[description];
	$date = $item['dc']['date'];
	echo "<a href='".$url."'>".$title."</a>-".$description."-".$date."<br>";
}


More Code Samples:
Parse Multiple URLs From RSS Feed Part 1
Parse Multiple URLs RSS Feed Into a Table Part 2

PHP Parse and Read RSS Feeds With Magpie

There are many methods for which xml files and rss feeds can be parsed. In a nutshell, they all take the feed or xml format and take data from organized tags and turn the output into elegant HTML.

Although many methods can be used, one freely available parser that deserves heavy consideration is Magpie.

Magpie is a low memory consuming script that can be used to parse the rss feeds. All you have to do is download the scripts, unzip the folder and move the files into a desired location.

Magpie RSS parser takes in a rss feed url and sends you back an array of items. Once you have an array, you just use good old php to do whatever you want with it.

Magpie RSS Instructions

To use Magpie,
1) Download magpie from http://magpierss.sourceforge.net/
2) Upzip folder and move into your a custom directory. Rename the folder to magpie. Initially, the unzipped folder is called something like magpierss-0.72.
3) Make another folder and add the unzipped magpie folder into it. Then, create a file called index.php.
4) Add the following code to the top of the file.
<?php
require(‘magpie/rss_fetch.inc’);
$rss = fetch_rss($url);
5)Add code to parse the desired items.
Example:

 foreach ($rss->items as $item ) {     
$title = $item[title];     
$url   = $item[link];     
$description = $item[description];     
$date = $item['dc']['date'];     
echo "<a href='".$url."'>".$title."</a>-".$description."-".$date."<br>"; }

Code Samples:
Parse Single URL RSS Feed
Parse Multiple URLs From RSS Feed Part 1
Parse Multiple URLs RSS Feed Into a Table Part 2


Website Down Time in Cpanel

From time to time, a website can shut down for several reasons. One very common reason is that the server is running out of memory. Many websites consume many resources because they are built with Joomla, WordPress, Drupal and so on. With that in mind, you may want to know how log a website went down. Well, Cpanel offers an array of methods to find that out. You can use the ‘Logs’and the features.

Method #1: Bandwidth

To see bandwidth options during hours or days,
1) Login to Cpanel.
2) Go to logs > Select ‘Bandwidth’.
3) Look for downtime.

Method #2: Error Log

To see recent errors and track when site went down,
1) Login to Cpanel.
2) Go to logs > Select ‘Error Log’.
3) Look for downtime. You can track ip and where site went down; such as memory allocation. If the ip was suspicious, you can ban it.

Method #3: Latest Visitors

To see latest vistors,
1) Login to Cpanel.
2) Go to logs > Select ‘Latest Visitors’.
3) Select ‘View’ next to the desired website.


Securing PHP Scripts

There are countless numbers of PHP scripts that are available. Some scripts require no coding experience while others do. However, coding experience will allow a developer to customize the script as he desires, and it allows the coder to apply security fixes, if necessary. With many scripts, you will always see this patch for this software and this patch for that. What this means is that the code was probably vulnerable to sql injections or xss cross scripting since online users could add malicious into a form or a url and create database changes. It is always a good idea to stay secure for obvious reasons.

One good plan of attack when installing a script is to change or customize the database prefix so that online uses do not know what it is. Often, a hacker tries to inject code into a database with a default prefix, like jos, wp, or AT. If you can simply alter your database tables to a new prefix you have just added a good layer of security.


Remove Errors With Wamp

Remove the checkmark next to display errors.

WAMP PHP settings


MYSQL Change Storage Engine

Every MYSQL tables uses a storage engine. By default, MYISAM is the default table. Howver, when you create a new table, you can set the engine to something other other than MYISAM, such as the popular option InnoDB. InnoDB makes it safe to develope web applications without hangups; whereas MYISAM has limitations.

To change a table with mySQL console,
1) Type: ALTER TABLE tablename ENGINE = InnoDB;

To change a table with phpMyAdmin,
1) Open the database and select the table.
2) Select ‘Operations’.
3) Change ‘Storage Engine’
4) Select ‘Go’.

Sanitizing Form Data With PHP

No matter where you first learn about sql injections, xss scripting, or form form handling security, one common phrase seems to popup everywhere. The phrase is “Never trust the user’s input’. This phrase can be turned around to read ‘Protect Yourself From Hackers who will try to add malice code into your forms’. With that in mind, you should always try to make your forms with code that will sanitize user input. The code below will get you off to a decent start.

### CHANGE
### SANITIZE LOGIN
$my_username = mysql_real_escape_string(htmlspecialchars(trim($_POST['login'])));
$my_username = mb_convert_encoding($my_username, 'UTF-8', 'UTF-8');
$my_username = htmlentities($my_username, ENT_QUOTES, 'UTF-8');

$my_password = mysql_real_escape_string(htmlspecialchars(md5(trim($_POST['password']))));
$my_password = mb_convert_encoding($my_password, 'UTF-8', 'UTF-8');
$my_password = htmlentities($my_password, ENT_QUOTES, 'UTF-8');
### END SANITIZE

PHP / MYSQL Inner Joins or Various Loops

The code below shows how you can get the first and last names for users. The first output is an inner join while the second output is two while loops. It is two ways to get the same results. However, the single query looks a little cleaner. This inner join was done with two tables, but, you could use more tables if you wanted data such as login name from another table.

<?php
include('connect.inc');
$db = public_db_connect();

$command = "SELECT t1.firstname, t1.lastname FROM table_sort as t1, table_sort2 as t2 WHERE t1.id = t2.id ";
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)){
$first = $row['firstname'];
$last = $row['lastname'];
echo "<br/>".$first."-".$last;
}

//or 

//run multiple selects

$command = "SELECT id from table_sort2";
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];

$command_b = "SELECT firstname, lastname from table_sort WHERE id = '$id' ";
$result_b = mysqli_query($db, $command_b);
while($row = mysqli_fetch_assoc($result_b)){
$first = $row['firstname'];
$last = $row['lastname'];
echo "<br/>".$first."-".$last;

}

}

?>

Optimizing MYSQL Join Queries

Using join queries can make it quite convenient to retrieve data from two or more tables. However, when you use an ORDER BY or GROUP BY expression with a join it should make reference to a column from just one able. For example, you may want to order by article id from one table.

The code below shows a query that orders the data from a join based on the id order from table 1.. 

$command = "SELECT table1.id, table1.firstname, table1.lastname, table2.email FROM tablename1 as table1, tablename2 as table2 WHERE table1.id=table2.client_id ORDER BY table1.id ASC ";

PHP Programming Possibilities

With php programming, there many possibilities for how such skills will be applied. You could end up using open source php scripts, create custom hand-coded applications or any combination of the two.

Although the programming can move in all sorts of directions; one such fact should not be ignored. In order to create, understand and read various applications; the stronger the php / mySQL and OOP coding skills are will determine what you can handle or create.

On a custom level, using OOP or procedural PHP can be a preference. But, if you have no solid OOP skills, you will not understand how classes, objects, and methods work.

Then, when you try to modify a sscript or add a class to your program, you could be in real trouble. Asides from a solid knowledgebase, repetition and practice will make all coding flow and keep trouble shooting down to a minimum.

As a BC and Vancouver php programmer, I hope these words can offer some help or a reference point to see what PHP / mySQL programming is all about.

If you think PHP / mySQL programming is installing and using an open source application like Joomla or WordPress, you will find serious issues when it comes to customizing websites.

If you can hand code yourself, you can practically build with anything.

Returning A String From 2 Functions

The purpose of the code below is to show you how you can take rows within a while loop and call a function. Then, you call another function within a function.

In the second function, you will return a string that gets stacked into a larger array.

Finally, the array is parsed outside of the loop with two foreach loops.

Sounds confusing? Code like this can be quite commonplace when you work with other people’s scripts. Therefore, knowing the logic can make life simpler for a an average or expert php programmer.

Note: You can get the same results by returning a single function as described on this page.

<?php
include('connect.inc');
$db=public_db_connect();

function second_func($var2,$date2){
global $db; 

$my_values2 = $var2.",".$date2;
return $my_values2; //return a string
}


function get_data($var1,$date){
global $db; 

$my_values = second_func($var1,$date);
return $my_values; //return a string
}
 
$command = "SELECT DISTINCT id, email FROM table_sort WHERE id IN (1,2,3,4,5,6,7) ORDER BY id ASC";
$result = mysqli_query($db, $command);
 
while($row = mysql_fetch_assoc($result)) {
$var1 = $row['id'];
 
$command2= "SELECT min(date) as date FROM table_sort WHERE id ='$var1' ORDER BY id ASC";
$result2 = mysqli_query($db, $command2);
 
while($row2 = mysqli_fetch_assoc($result2)){
 
$date = $row2['date'];
echo $var1."-".$date."<br/>";
$get_data = get_data($var1,$date);
$my_array[] = $get_data;
}
}

print_r($my_array);

foreach($my_array as $key => $value) {
echo "<br/>".$key."-".$value;
}

foreach($my_array as $key => $value) {
$all = explode(",",$value);
$id = $all[0];
$date = $all[1];
echo "<br/>".$id."-".$date;
}
 
?>

Returing An Array From 2 Functions

The purpose of the code below is to show you how you can take rows within a while loop and call a function.

Then, you call another function within a function. In the second function, you will return an array that get stacked into a larger array.

Finally, the array is parsed outside of the loop. PHP programmers can face this type of logic when they work with other people’s scripts.

Note: You can get the same results by returning a single function as described on this page.

<?php
include('connect.inc');
$db=public_db_connect();

function second_func($var2,$date2){
global $db; 

$my_values2[] = $var2.",".$date2;
return $my_values2; //return an array
}


function get_data($var1,$date){
global $db; 

$my_values = second_func($var1,$date);
return $my_values; //return an array
}
 
$command = "SELECT DISTINCT id, email FROM table_sort WHERE id IN (1,2,3,4,5,6,7) ORDER BY id ASC ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)) {
$var1 = $row['id'];
 
$command2= "SELECT min(date) as date FROM table_sort WHERE id ='$var1' ORDER BY id ASC";
$result2 = mysqli_query($db, $command2);
 
while($row2 = mysqli_fetch_assoc($result2)){
 
$date = $row2['date'];
echo $var1."-".$date."<br/>";
$get_data = get_data($var1,$date);
$my_array[] = $get_data;
}
}

print_r($my_array);

foreach ($my_array as $key => $value) {
$value = implode(",",$value);
echo "<br/>".$key."-".$value;
$value2 = str_replace(",","-",$value);
echo "<br/>".$value2;

}
?>

Returning A Variable or String From Functions With PHP

The purpose of this tutorial is to explain how to return a string from a function, which will become part of an array that is created in a double while loop.

<?php
include('connect.inc');
$db=public_db_connect();

$count = 0;
function get_data($var1,$date){
global $db; 


$my_values = $var1.",".$date;
return $my_values; //return a string
}
 
$command = "SELECT DISTINCT id, email FROM table_sort WHERE id IN (1,2,3,4,5,6,7) ORDER BY id ASC";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)) {
$var1 = $row['id'];
 
$command2= "SELECT min(date) as date FROM table_sort WHERE id ='$var1' ORDER BY id ASC";
$result2 = mysqli_query($db, $command2);
 
while($row2 = mysqli_fetch_assoc($result2)){
 
$date = $row2['date'];
echo $var1."-".$date."<br/>";
$get_data = get_data($var1,$date);
$my_array[] = $get_data;
}
}

print_r($my_array);

foreach($my_array as $key => $value) {
echo "<br/>".$key."-".$value;
}

foreach($my_array as $key => $value) {
$all = explode(",",$value);
$id = $all[0];
$date = $all[1];
echo "<br/>".$id."-".$date;
}
 
?>

Returning Array From Functions PHP

The purpose of this tutorial is to explain how to return and array from a function, which will become part of another array. With PHP, you can return a string or array from a function. The string or array that is returned can become combined into another array.

<?php
include('connect.inc');
$db=public_db_connect();

$count = 0;
function get_data($var1,$date){
global $db; 


$my_values[] = $var1.",".$date;
return $my_values; //return an array
}
 
$command = "SELECT DISTINCT id, email FROM table_sort WHERE id IN (1,2,3,4,5,6,7) ORDER BY id ASC ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)) {
$var1 = $row['id'];
 
$command2= "SELECT min(date) as date FROM table_sort WHERE id ='$var1' ORDER BY id ASC";
$result2 = mysqli_query($db, $command2);
 
while($row2 = mysqli_fetch_assoc($result2)){
 
$date = $row2['date'];
echo $var1."-".$date."<br/>";
$get_data = get_data($var1,$date);
$my_array[] = $get_data;
}
}

print_r($my_array);

foreach ($my_array as $key => $value) {
$value = implode(",",$value);
echo "<br/>".$key."-".$value;
$value2 = str_replace(",","-",$value);
echo "<br/>".$value2;

}
?>

PHP Integers From Database

When you grab a row from a loop with php, the rows come back at you with strings. However, using the (int) cast is a method to convert the number string into an integer. For example, say you wanted to add an integer into a json function or use it for mathematical purposes. You simple add the (int) in front of the number string to make it an integer.

Read below for details.

$command = "SELECT * FROM tablename ";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
        $myid = row['id']; // this is a string if the column is varchar
	$id = (int)$myid;
	$id2 = (int)trim($myid);	
	}

HTML Doc Types

When you build a website, it has a DTD at the top of the page which declares the type of document for the web page. These days, most web pages use various declarations for html and xhtml. Below, are two code samples for the most common types of xhtml documents and the html 5 document. Aside from the DTD, the html, body and head tags are the same.

XHTML Transitional Sample

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" > <head></head> <body> </body> </html> 

XHTML 5 Sample

 <!DOCTYPE HTML> <html> <head></head> <body> </body> </html> 

Making CSV Files With PHP

Making CSV files with PHP can de done very effectively. You may want to make custom lists that users can download in the form of csv files. Then, the file can be opened in Excel and the report can be presented at the next meeting.

The code below demostrates two methods for which csv files can be created.

Method A

function get_csv($values) {
return implode(',', $values) . "\n";
}
 
$fh = fopen('mycsv.csv','wb');
 
$command = "SELECT * FROM tablename ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)){
$id = trim($row['id']);
$name = trim($row['name']);
 
$get_csv = get_csv($row);
 
fwrite($fh, $get_csv);
}
 
fclose($fh);

Method B

$fp = fopen('myfile.csv', 'wb');
// get array from while loop
$command = "SELECT * FROM tablename ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)){
$id = trim($row['id']);
$name = trim($row['name']);
 
$vars[] = $id.",".$name;
 
fwrite($fh, $get_csv);
}
 
foreach ($vars as $field) {
   // need to make array from $field string
   fputcsv($fp, explode(',',$field));
}
 
fclose($fp);

Parse error: syntax error, unexpected ‘}’, expecting ‘]’

One of the great features with PHP error checking is the error explanation. When an error does occur, the explanation often leads you straight to the solution. The next example shows an error where ‘}’was used instead of ‘]’. The example also explains how to fix the issue.

Error:
Parse error: syntax error, unexpected ‘}’, expecting ‘]’ in /home/user/public_html/file.php on line 12

 // Change $_GET['id'}  // Change to: $_GET['id']    

PHP Equal(=) Sign Errors

When coding with PHP, you often use two symbols for the equal sign. The symbols are ‘==’ and ‘=’. However, they do not mean the same thing. When you declare variables or use mySQL queries, you always use’=’. But, when you use conditions, you must use’==’.

Here is an error that may be displayed when you use the incorrect ‘=’sign.

Parse error: syntax error, unexpected ‘=’ in /home/user/public_html/folder/file.php on line 100

The example below shows a simple error and how to fix it.

if($var=22) { echo "Hello World";}  // code should be should be   if($var==22) { echo "Hello world"; }

MYSQL MIN() Function

Using the min()function with mySQL permits developers to sort through a database and retrieve the lowest value. With date, the lowest value would be the earliest date entered for a specific column. The example below shows how to get the earliest date from a table where the user is the administrator.

$command = "SELECT min(date) as date FROM tablename WHERE date < now() and user='admin' ";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
    $date = $row['date']; //echo $date; 
}

Convert IP Address To City and Country With PHP

<?php error_reporting (E_ALL ^ E_NOTICE); 
include('connect.inc'); 
session_start();
$db = public_db_connect();

public_db_connect();

echo 'Convert IP Address To City and Country With PHP<br/><br/>';
$command = "SELECT ip FROM ips ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)){
 
$user_ip = $row['ip'];
 
$fetch_url =  'http://api.ipinfodb.com/v3/ip-city/?key=KEY_GOES_HERE&ip='.$user_ip.'&format=xml';
 
//CURL OPTION TO GET FILE
/*$mycurl = curl_init();
curl_setopt($mycurl, CURLOPT_URL,$fetch_url);
curl_setopt($mycurl, CURLOPT_FAILONERROR, true);
curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($mycurl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($mycurl, CURLOPT_TIMEOUT, 30);
 
//fetch url and send it to the browser
$myfile= curl_exec($mycurl);*/

//FILE_GET_CONTENTS OPTION
$myfile = file_get_contents($fetch_url);
 
//create the new location object 
$location = new SimpleXMLElement($myfile);

// get the variables from the class
$country = $location->countryName;
$state = $location->regionName;
$city = $location->cityName;
 
$city_country_array[] = $city.",".$country;

}

// create an array with city and country 
$count = array_count_values($city_country_array);
print_r($count);
 
foreach($city_country_array as $country_city) {
 $all = explode(",",$country_city);
 $city = $all[0];
 $country = $all[1];

}
 echo '<br/>';
// loop to get the city, country and values of each entry
foreach($count as $key => $value) {
echo "<br/>".$key."-".$value;

}
?>

Using MYSQL IN For Strings and Numbers

The mySQL IN clause allows you to search through records where values match what you are seeking. The examples below demonstrate its usage with a string or numbers.

// Querying a String
$text_1 = "hello";
$text_2 = "world";
$command = "SELECT DISTINCT id, name FROM tablename WHERE id IN('$text_1','$_text2') ";

// Querying Numbers
$command = "SELECT DISTINCT id, name FROM tablename WHERE id IN(1250,1350) ";

Using Shadowbox For Video and Images

Shadowbox is a web based application which allows users to displya text or image links that popup in a shadowbox. Shadowbox can be downloaded from shadowbox-js.com.

To use Shadowbox with youtube video,
1) Download Base(standalone) and check all options.
2)
Unzip and upload the shadowbox folder or files to the desired location on the server. Rename the folder to something different if you want to keep everything in one folder.
3) Add the following inside the <head></head> tags:

<link rel=”stylesheet” type=”text/css” href=”js/shadowbox.css”>
<script type=”text/javascript” src=”js/shadowbox.js”></script>

<script type=”text/javascript”>
Shadowbox.init();
</script>

4) Use the link format below to make popups for youtube video..

<a href=”http://www.youtube.com/v/abcde45t&hl=en&fs=1&rel=0&autoplay=1″ rel=”shadowbox;width=720;height=480;player-swf;” ><img  src=”images/img.png” /></a>
 

PHP Floor For Numbers

The floor() function with php allows you to round a number down to the nearest whole number. You must take into consideration that any decimal points will be removed.

Floor Example

$numb = floor(23.5); 
echo $number; // output is 23  
echo floor(34.67); // output is 34.  
echo "My answer to the math question is ".floor(99.9); // Output is My answer to the math question is 99.

PHP Ceiling For Numbers

The ceil() function with php allows you to round a number up to the nearest whole number. It has many benefits, but, you must take into consideration that any decimal points will be removed.

Ceiling Example

$number = ceil(21.5); 
echo $number; // output is 22  
echo ceil(33.67); // output is 34.  
echo "My answer to the math question is ".ceil(100.9); // Output is My answer to the math question is 100.

PHP Self Submit Form

With PHP, you have two options to submit a form. One option is to post it to the same page and the other is to post it to the same page. Posting it to the same page is often the easier, most tidy approach.

Posting the form to the same page

 <form method = "post" action = "<?php echo $_SERVER[PHP_SELF]; ?>"> <input type="text" name = "myname" value = "" /> <input type="submit" name = "myname" value = "Submit" /> </form> 

Posting the form to the same page With A Query String
The form below can be used to submit a form to itself if the string contains get variables within the url. An example of such a url would be example.com/page.php?id=1234&name=john.

 <form method = "post" action = "<?php echo $_SERVER[PHP_SELF]."?".$SERVER[QUERY_STRING]; ?>"> <input type="text" name = "myname" value = "" /> <input type="submit" name = "myname" value = "Submit" /> </form> 

Posting the form to a different page
The form below can be used to submit a form to another page called ‘ótherpage.php’.

 <form method = "post" action = "otherpage.php"> <input type="text" name = "myname" value = "" /> <input type="submit" name = "myname" value = "Submit" /> </form> 

PHP and MYSQL Functions

PHP and mySQL have many built-in functions that can be used to alter all sorts of data. In some cases, there are functions in mySQL and PHP that do the same thing. For example, php and mySQL both have functions to make all text upper or lower case, remove whitespace, replace characters and encrypt strings in md5 or sha1…just to name a few.

It is good to know both. As you program, yiou will find a comfort zone and may lean on one method or another to achieve your goals. Since mySQL can be used with various programming languages like PERL or Python, strong mySQL skills and its function usage can already allow you to grasp what is happening in other code too. 


MYSQL Query Cache Not Caching

The mysql query cache can be setup to cache mysql queries. For websites with large quantities of selected data; this can help performance. To set up the cache, click here.

To know what cannot be cached, read on. The mySQL query cache will not cache data that uses non-deterministic functions like now() or current_date(). Furthermore, it won’t cache transactions used with InnoDB storage engines. Although, it won’t cache some data, it could cache many other chunks of data; such as your home page or other pages on the site. 

Creating PHP Comments With Various Techniques

PHP has several methods for which you can add comments within you files.

The samples below show various commenting methods. Commenting is a en excellent method to troubleshoot and leave notes about your code; especially while you are learning or leaving code that may need editing by others.

A large query and two loops can be obvious to some programmers; but a line of English that states what is done can be easier to understand at first glance.

For example, 20 line of code could have a comment like ‘Get the members id and see if they have boughten any books from the PHP category within the last two weeks.’

## This sign is a comment  
// The double slashes comment this text  
/* The forward slash and asterisk at the beginning and end of a text block will be commented. This is a common method for which to create comments in many languages.*/  
echo 'This text is not commented and would be the only text displayed on the page!';

PHP Echo vs Print

With PHP, you have two options which can be used to print text, html, css and javascript. Those two commands are print and echo. Most php developers use echo, even though historically, print has been a common programming command to print in computer languages.

Echo outputs slightly faster than print and the shorter word makes it easier to read and write for programmers. Thus, it usage far outweighs print. Asides from that, using either will print text the way you intend to display it.

 <?php 
//To use echo, echo "Here is my double quoted sentence,";  
//To use print, print 'Here is my single quoted sentence';

MYISAM Tables vs InnoDB Storage Engine With mySQL

Whether you decide to build a php / mySQL application or use an existing application, the database storage engine should be given some priority. If you plan to only allow online readers to select data from a database; MYISAM will bee fine an do the job the well. However, if you plan to do transactions or have a website that requires, or will require substantial updating, innoDB is a better a option.

With MYISAM, the engine has table locking. This means that the table is locked during an update or insert statement. If the table is used simultaneously by another user, the data cannot update. Imagine a cron job or an update is being made to the table. If a large update script is using a table, then any logged in member cannot update to it.

On the other hand, innoDB tables have row locking, which means the table is available to update for other users. Innodb tables allow php developers to use transactions on the table. With transactions, you can run a single or multiple series of updates, inserts and delete commands that will will only occur if every command was successful. With MYISAM, using transactions does not work and the last command gets executed whether you like it or not.

PHP Scrape HTML

The example below shows how to scrape a website to get a list of all Javascript files for a specific web page.

$data = file_get_contents('http://example.com');

//$regex ='/script type="text\/javascript" src="\/media\/system\/js\/mootools.js">/'; // gets everything in script except beginning < and ending </script>
$regex = '/<script(.*)<\/script>/'; //finds all jscripts and displays everything buy beginning <script tags and ending </script> tag and WORKS

preg_match_all($regex,$data,$posts, PREG_SET_ORDER);
	
	print_r($posts);
	
	echo '<br/>';

	$cnt = count($posts);
	echo $cnt;
for($i=0; $i < $cnt; $i++){
foreach ($posts[$i] as $post) {
  	
if(strstr($post, 'text/javascript')){
echo "hi".$post."<br/>";
}else{
    // do something with data
	//echo "hoy".$post."<br/>";
	}
}
}

PHP Website Scraping

The following example explains how to scrape a page with <p> tags.

Sample
Let’s analyze the code.The file_get_contents() function aquires the html code we want to scrape. The $regex variable picks the data between the <p></p> tags. Then, the preg_match_all() function creates the $posts array based on finding the <p> tags within the website url. After the array is built, the array called $posts is counted. The resulting array is a mutlidemsional array which can be shown with print_r($posts). The for loop is used to examine the two main arrays and the foreach loop is used to sort the arrays within the main arrays.

Within the foreach loop, we add str_replace() functions to remove blocks of text we do not want. If you open the page with a browser and view the source, you can see the output of each array and make custom str_replace() functions. In our example below, we used various str_replace() functions so that we ended up with the desired text.

Within the foreach loop arrays are created that we displayed outside the loop.

$data = file_get_contents('http://example.com');

$regex = '/<p(.*)<\/p>/'; //finds p tags and gets content between tags WORKS 

preg_match_all($regex,$data,$posts, PREG_SET_ORDER);
	//var_dump($posts);
	
	print_r($posts);
	
	echo '<br/><br/>';
	
	$cnt = count($posts);
	echo $cnt;
	
	
	$loops = 0;
for($i=0; $i < $cnt; $i++){
foreach ($posts[$i] as $post) {
	$loops = $loops + 1;
	//echo "loops"."-".$loops."<br/>";

	//view source code and customize
	$post = str_replace('<p class="art-page-footer"><a href="/"></a>','',$post);
	$post = str_replace('class="art-page-footer"><a href="/"></a>','',$post);
	$post = str_replace('><a href="http://www.macromedia.com/go/getflashplayer">','',$post);
	$post = str_replace('<a href="http://www.macromedia.com/go/getflashplayer">','',$post);
	$post = str_replace('<p>','',$post);
	$post = str_replace('</p>','',$post);
	$post = str_replace('<p','',$post);
	$post = str_replace('</a>','',$post);
	$post = trim($post);	
	echo $post."<br/>";
	//$post = trim($post);
	$posts_array[] = $post;
}
}

$posts_final = array_unique($posts_array);
print_r($posts_final);

PHP Scrape Webpage Lesson

Scarping a web page with php is a procedure for which you get the html code of a foreign website and retrieve specific parts of data. Scraping a website could be a method for which to use data for analysis when no rss feeds exist. Another reason one may wish to scrape a website is to analyze page titles of highly ranked websites.

The codes below show two methods for which you can captures all text within h1 tags. Both examples use arrays to capture all blocks of desired text. With an array, anything is possible from adding the content to a database or to analyze text. Both examples use the function preg_match_all() to create arrays from a particular website.

The second example is a little longer and lengthier and uses the string_replace() function and trim() function within the foreach loop to create unique arrays.

Scraping can be a little controversial since you are capturing somebody else’s copyrighted material. Pickybacking off somebody else’s hard work may not be taken lightly. If the website used copyscape.com and finds such abuse; small or large complaints could exist. In extreme cases, Google could significantly ban your website for using black hat seo.

Sample #1
Let’s go through the code.The file_get_contents() function gets the html code we want to scrape. The $regex variable picks the data between the h1 tags. Then, the preg_match_all() function creates the $posts array. The foreach loop runs each value in the array and checks for ‘<h1’. If it exists, it outputs the value.

$data = file_get_contents('http://example.com');

$regex = '/<h1(.*)<\/h1>/'; //finds h1 tags and gets content between and WORKS

preg_match_all($regex,$data,$posts, PREG_SET_ORDER);
	
	//print_r($posts);
	
	echo '<br/>';

foreach ($posts[0] as $post) {
   	
if(strstr($post, '<h1')){
echo $post."<br/>";
}else{
    // do something with data
	//echo "hoy".$post."<br/>";
	}
}

Sample #2
Let’s analyze the code.The file_get_contents() function aquires the html code we want to scrape. The $regex variable picks the data between the h1 tags. Then, the preg_match_all() function creates the $posts array based on finding the h1 tags within the desired file. After that, all posts are counted. What we end up with is a mutlidemsional array. Therefore, the for loop is used to separate the two main arrays and the foreach loop is used to sort the arrays within each arrray.

With the foreach loop, web can add str_replace() functions to remove blocks of text we do not want. If you open the page with a browser and view the source, you can remove the codes you do not want want. In our example below, we used various str_replace() functions so that we ended up with just ‘pure text’.

Within the foreach loop arrays are created that we displayed outside the loop.

$data = file_get_contents('http://example.com');

$regex = '/<h1(.*)<\/h1>/'; //finds h1 tags and gets content between and WORKS

preg_match_all($regex,$data,$posts, PREG_SET_ORDER);
	
	//print_r($posts);
	
	echo '<br/><br/>';
	
	$cnt = count($posts);
	//echo $cnt;
	
	
	$loops = 0;
for($i=0; $i < $cnt; $i++){
foreach ($posts[$i] as $post) {
   	
	//view source code and customize
	$post = str_replace('<h1 style="margin-top: 0px; margin-bottom: 0px; padding-bottom: 0px; font-size: 22px; color: rgb(90, 89, 95); text-shadow: 0.07em 0.07em 0.07em rgb(251, 144, 40);">','',$post);
	$post = str_replace('style="margin-top: 0px; margin-bottom: 0px; padding-bottom: 0px; font-size: 22px; color: rgb(90, 89, 95); text-shadow: 0.07em 0.07em 0.07em rgb(251, 144, 40);">','',$post);
	$post = str_replace('</h1>','',$post);
	$post = trim($post);	
	echo $post."<br/>";
	//$post = trim($post);
	$posts_array[] = $post;

}
}

echo "<br/>Array Details:<br/>";
$posts_final = array_unique($posts_array);
print_r($posts_final);

PHP dirname(__FILENAME__) Function

The php function dirname(__FILENAME__) is used to get the working directory for files and include files.

The code below can be used to see how the function works.

$dir = dirname(__FILENAME__); 
echo $dir;

PHP getcwd() Function

The php function getcwd() is used to get the current working directory.

The code below can be used to see how the function works.

$dir =  getcwd(); 
echo $dir;

PHP unlink() Function

The PHP unlink() function can be used to delete files within specified directories. One such use of this function could be to remove images for a dynamic image gallery.

The code below can be used to delete multiple images in a specific folder. The post variables for $_POST[‘filenames’] is an array of each file which was selected for deleting. The foreach loop takes each file that you want to delete and uses the unlink($newdir) function to delete the file.

if ($_POST['mysubmit2']) {
foreach ($_POST["filenames"] as $filename) {
echo $filename;
// $newdir = getcwd()."/images/gallery/".$filename; // for live hosting
$newdir = getcwd()."\images\gallery\\".$filename;
unlink($newdir);
}
}




THE FORM

 //$dir =  getcwd()."/images/gallery" ; //for live host
        $dir =  getcwd()."\images\gallery" ; //for WAMP
        
        ?>

<form name="mydelete" method="post" action="<?php echo $_SERVER['PHP_SELF'] ; ?>" >        

<?php
//$dir    = $directory;
$files1 = scandir($dir);
foreach($files1 as $file){
if(strlen($file) >=3){
//$foil = strstr($file, 'jpg'); // As of PHP 5.3.0
$foil = $file;
//$pos = strpos($file, 'css');
if ($foil==true){
echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />';
// echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host
echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/$file' /><br/>";
}
}
}?>
<input type="submit" name="mysubmit2" value="Delete">
</form>

PHP glob() Function

The glob() function can be used to get an array which lists files from a chosen directory. For example, the command below will return an array of the image names from the images/gallery folder.

$files = glob(“images/gallery/*.*”);

The code below shows how to use glob() function to get an array of filnames for images for which a for loop is used to create thumnails and images links for each image.

$files = glob("images/gallery/*.*");

for ($i=0; $i<count($files); $i++)
{
    $num = $files[$i];
    /*print "<a href='".$SERVER[PHP_SELF]."?myeditor=".$num."'>".$num."</a><br />";
    echo '<img src="'.$num.'" alt="random image" />'."<br /><br />";*/
    
    echo '<div class="image_align">
                            <div class="myimage"><a href="'.$num.'" rel="shadowbox"><img alt="placeholder" height="98" src="'.$num.'" width="130"> </a></div>
                        </div>';
}

Simple Machines Forum Moderation

After installing SMF forum, you may find that approved regular members may be able to create new posts that get published without moderation. Therefore, if you want to moderate posts prior to being published, you must adjust a few settings.

To set up moderation with Simple Machines Forum version 2.02,
1) Login as admin
2) Select Admin >Features and Options >Configuration >Core Features >Select Post Moderation > Save >Go To Admin >Permissions >Select Modify Next to regular users > Look for ‘Post Topics and Replies to board’ and ‘Post Topics and Replies to board only after they have been approved’.

3) Deselect ‘Post Topics and Replies to board’ and select the check boxes for ‘Post Topics and Replies to board only after they have been approved’. Now, new posts can be moderated prior to being published.

PHP scandir() Function

The scandir() function can be used to generate a list of filenames from a chosen folder. The following code demonstrates how to generate such a list.

First of all, a directory is chosen by creating the $dir variable.

Secondly, the $files1 array is created by obtaining all images with the scandir($dir) function.

Finally, a foreach loop is created to output a check box and images for each file in the array.

$dir =  getcwd()."/images/gallery" ;

$files1 = scandir($dir);

foreach($files1 as $file){
if(strlen($file) >=3){
//$foil = strstr($file, 'jpg'); // As of PHP 5.3.0
$foil = $file;
//$pos = strpos($file, 'css');
if ($foil==true){
echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />';
// echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host
echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/$file' /><br/>";
}
}

PHP Image Gallery

This example shows how to create a simple image gallery with php. No database is required. The first file displays the galler while the second file is used to manage the php gallery images. You can view the example here, or download the entire php gallery script here.

Gallery Code

The first block of code can be used to show the php photo gallery to the viewer. This code uses the glob() function to select files in a particular folder, which in this this case is the gallery folder. The for loop displays all the files to the viewer. The for loops stop after all images are displayed.

$files = glob("images/gallery/*.*");
for ($i=0; $i<count($files); $i++)
{
	$num = $files[$i];
	/*print "<a href='".$SERVER[PHP_SELF]."?myeditor=".$num."'>".$num."</a><br />";
	echo '<img src="'.$num.'" alt="random image" />'."<br /><br />";*/
	
	echo '<div class="image_align">
							<div class="myimage"><a href="'.$num.'" rel="shadowbox"><img alt="placeholder" height="98" src="'.$num.'" width="130"> </a></div>
						</div>';
}

Upload Code
The following block of code can be used to upload and delete photos. If an image is uploaded, it goes into the adequate directory, which in this case is the gallery folder. The image uploaded is idential to that on the pc. There is a sufficient amout of commented text that can be used to create resized jpeg images; in case you want to add that feature. 

if (ISSET($_POST['mysubmit'])) {
	
	if (($_FILES["img_upload"]["type"] == "image/jpeg" || $_FILES["img_upload"]["type"] == "image/pjpeg" || $_FILES["img_upload"]["type"] == "image/jpg" || $_FILES["img_upload"]["type"] == "image/pjpg" || $_FILES["img_upload"]["type"] == "image/gif" || $_FILES["img_upload"]["type"] == "image/x-png") && ($_FILES["img_upload"]["size"] < 1000000))
	{  
		$max_upload_width = 2592;
		$max_upload_height = 1944;
		  
		if(isset($_REQUEST['max_img_width']) and $_REQUEST['max_img_width']!='' and $_REQUEST['max_img_width']<=$max_upload_width){
			$max_upload_width = $_REQUEST['max_img_width'];
			
		}    
		if(isset($_REQUEST['max_img_height']) and $_REQUEST['max_img_height']!='' and $_REQUEST['max_img_height']<=$max_upload_height){
			$max_upload_height = $_REQUEST['max_img_height'];
		}	
		
		if($_FILES["img_upload"]["type"] == "image/jpeg" || $_FILES["img_upload"]["type"] == "image/pjpeg" || $_FILES["img_upload"]["type"] == "image/jpg" || $_FILES["img_upload"]["type"] == "image/pjpg"){	
			$image_source = imagecreatefromjpeg($_FILES["img_upload"]["tmp_name"]);
			
		}		
		
		if($_FILES["img_upload"]["type"] == "image/gif"){	
			$image_source = imagecreatefromgif($_FILES["img_upload"]["tmp_name"]);
			
		}	
	
		if($_FILES["img_upload"]["type"] == "image/x-png"){
			$image_source = imagecreatefrompng($_FILES["img_upload"]["tmp_name"]);
			
		}
		
		//CREATING NEW IMAGE
		/*$remote_file = "images/gallery/SM-".$_FILES["img_upload"]["name"];
		//echo $remote_file;
		imagejpeg($image_source,$remote_file,100);
		chmod($remote_file,0644);	

		list($image_width, $image_height) = getimagesize($remote_file);*/
	
	//ADD A SECOND FILE	ORIGINAL LENGTH AND WIDTH
		$upload_original = move_uploaded_file($_FILES["img_upload"]['tmp_name'], "images/gallery/LG-".$_FILES["img_upload"]["name"]);
		
		if ($upload_original)
		{
		echo "Upload Successful!<br/>";
		}
		//echo "hoy".$image_width;
	
		/*if($image_width>$max_upload_width || $image_height >$max_upload_height){
			$proportions = $image_width/$image_height;
			
			if($image_width>$image_height){
				$new_width = $max_upload_width;
				$new_height = round($max_upload_width/$proportions);
				
			}		
			else{
				$new_height = $max_upload_height;
				$new_width = round($max_upload_height*$proportions);
			}		
			
			$new_image = imagecreatetruecolor($new_width , $new_height);
			$image_source = imagecreatefromjpeg($remote_file);
			
			imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
			imagejpeg($new_image,$remote_file,100);
			
			imagedestroy($new_image);
		}*/
		
		imagedestroy($image_source);		
	}
	else{
		
	}
	}	
	
	/*echo "<b><a href=\"logout.php\">Logout!</a></b>"." | &nbsp "." <b><a href=\"login.php\"> Update Content</a></b> | <b><a href=\"edit.php\">&nbsp Edit Content</a></b><br/>";*/
?>
<form name="myform" method="post" action="<?php echo $_SERVER['PHP_SELF'] ; ?>" enctype="multipart/form-data">
	
	<label>Maximum 1MB. Accepted Formats: jpg, gif and png:</label><br />
          <input name="img_upload" type="file" id="img_upload" size="40" />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />	     
		
      <input style="display:none;" name="max_img_width" type="visible" value="" size="4">          
     
      <input style="display:none;" name="max_img_height" type="visible" value="" size="4">      
<input name="tmp_name" type="hidden" value="myfile.jpg" >   	  
      
<input type="submit" name="mysubmit" value="Submit">

</form>
<?php 
$dir = dirname(__FILENAME__)."/images/gallery" ;
if ($_POST['mysubmit2']) {
foreach ($_POST["filenames"] as $filename) {
echo $filename;
// $newdir = getcwd()."/images/gallery/".$filename; // for live hosting
$newdir = getcwd()."\images\gallery\\".$filename;
unlink($newdir);
}
}
        //$dir =  getcwd()."/images/gallery" ; //for live host
		$dir =  getcwd()."\images\gallery" ; //for WAMP
		
		?>

<form name="mydelete" method="post" action="<?php echo $_SERVER['PHP_SELF'] ; ?>" >		

<?php
//$dir    = $directory;
$files1 = scandir($dir);
foreach($files1 as $file){
if(strlen($file) >=3){
//$foil = strstr($file, 'jpg'); // As of PHP 5.3.0
$foil = $file;
//$pos = strpos($file, 'css');
if ($foil==true){
echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />';
// echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host
echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/$file' /><br/>";
}
}
}?>
<input type="submit" name="mysubmit2" value="Delete">
</form>

<?php //} ?>

Redirect With PHP header()

Redirecting with the php header() function is just one of the many uses of the function. However, to use it safely in your applications it is a good practice to use it before outputting any text or html. Otherwise, you may get the error ‘Headers Already Sent”. The code below shows its usage at the top of your file which analyzes posted data before outputting any html.

$member_id = $_POST['member_id'];

if($_POST['member_id']){
$command = "INSERT INTO tablename VALUES (NULL, '{$_SESSION['id']}', '$friend_id', '{$_POST['name']}',now()) ";
$resulta = mysqli_query($db, $command);
}else {
## redirect if $_POST['member_id'] variable exists
header("Location: filename.php");
exit();

include("html_header_file.inc");
}


}

Combining Identical Arrays With PHP

The code below shows how data from two different tables can be merged into a single array.

$command = "select * from tablename where member_id = '{$_SESSION['member_id']}'";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
        $my_array['id'] =  $row['id'];
$my_array['title'] = $row['mytext'];  
$my_array['title'] = date("ga", strtotime($row['date']))." ".substr($row['mytext'], 0, 10)."..."; 
        $my_array['start'] = date("D, j M Y G:i:s T", strtotime($row['date']));
$my_array['color'] = '#000000';  
$my_array['url'] = "filename.php?mydid=".$row['id'];
        $big_array[] = $my_array;
}
 
$command_b = "select * tablename2 where member_id = '{$_SESSION['member_id']}' ";
$result_b = mysqli_query($db, $command_b);

while ($row = mysqli_fetch_assoc($result_b)) {
        $my_array['id'] =  $row['id'];
$my_array['title'] = $row['column'];  
$my_array['title'] = "Note:  ".substr($row['column'], 0, 10)."..."; 
        $my_array['start'] = date("D, j M Y G:i:s T", strtotime($row['date']));
$my_array['color'] = '#dc4000';  
$my_array['url'] = "filename.php?myid=".$row['id'];
        $big_array[] = $my_array;
}
 
print_r($big_array);
?>

Trim Function With mySQL

The trim() function with mySQL behaves like the trim() function with PHP. Both strip white space at the beginning and end of a string. The following example shows how the trim() function can be used with the mysqli_real_escape_string() function.

When functions like trim() and mysql_real_escape_string() are used within a query there is much less code to work with. However, you could apply the php trim() and mysqli_real_escape_string() functions to each post variable instead of adding it into the command.

 

Method A

$firstname = mysqli_real_escape_string($db, trim($_POST[firstname]));
$lastname = mysqli_real_escape_string($db, trim($_POST[lastname]));
$phone = mysqli_real_escape_string($db, trim($_POST['phone']));
$email = mysqli_real_escape_string($db, trim($_POST['email']));

$command = "INSERT INTO tablename VALUES (NULL, '$firstname', '$lastname', '$phone', '$email', now()) ";

$result = mysqli_query($db, $command);

Method B

$firstname = mysqli_real_escape_string($db, $_POST[firstname]);
$lastname = mysqli_real_escape_string($db, $_POST[lastname]);
$phone = mysqli_real_escape_string($db, $_POST['phone']);
$email = mysqli_real_escape_string($db, $_POST['email']);

$command = "INSERT INTO tablename VALUES (NULL, TRIM('$firstname'), TRIM('$lastname'), TRIM('$phone'), TRIM('$email'), now()) ";

$result = mysqli_query($db, $command);

MYSQL Process List

There could come a time when the database or website seems to lag and the pages take longer than normal to load. The problem could exist if there are relational database queries which do not use indexes, or queries are written in a manner for which poor performance occurs.

Web Host Manager

To see processes with Web Host Manager,  
1) Select 'Home' >'SQL Services' >'Show MYSQL Processes'

Shell command
The command below will give you all mySQL running and sleeping process status then select the sleeping process id and kill it using SSH. Open SSH and show the process ids. Then, open mySQL and kill the id.

Show processes with Linux
# mysqladmin pr 

Show processes with mySQL
mysql> show processes;


Kill Process
mysql> kill process Id# ;

PHP Blog

PHP Blogs are the common blogs on the Internet. In fact, rumor has it that WordPress accounts for 20% of all new websites.

WordPress is a very popular php blog for many reasons; it easy to learn, it ranks well with Google and other search engines, there are many good plugins and many web developers use it.

However, there are many other open source applications and php scripts which function as blogging platforms. For example, Joomla works okay as a blog, especially with the components Myblog or Jaggy Blog.

High Performance Blogging

Although the majority of web development leans towards the usage of assembly line open source products like WordPress, Joomla and Drupal for php blogging; there are many lightweight php / mySQL blogs which can be very effective.

Custom blogs can outperform the open source applications much like a custom chopper outperforms an assembly line product.

Here is where creating a very custom project gets easier than open source applications like WordPress since templating an exact html / css template can be done very quickly; and performance would be like night and day.

We could talk benchmarks all day; but the Bootstrap and PhpBlogifier Blog samples displays help to create a fast loading blog. You can check typical WordPress blogging benchmarks and you may find that that many results don’t even come close to the 1/100th of a second to execute all php code.

Come to PHP Blog and view more details about php blogs.


Web Host Manager; Customize Apache and PHP

SOFTWARE

PHP / mySQL runs on the Apache server. You can configure the Apache server and update PHP in one shot using ‘Easy Apache’.

To upgrade Apache Server and PHP,
1) Select ‘Easy Apache’.

2) Select ‘Start customizing based on profile’ to upgrade from existing settings.

3) Select Apache version >Next.
4) Select a PHP Version.

5) Select ‘Next Step’.
6) Select From ‘Short Options’ or scroll down and select ‘Exhaustive Options List’.

7) Customize Options. The options here can be checked if you want them. For example, checking ‘GD’ means you can use many image image functions within your programming. The GD library is very useful to create and resize images with PHP.

8) Select ‘Save and Build’. Now, you simply wait for the build to finish, then reboot Apache server and you are good to go.


SQL SERVICES WEB HOST MANAGER

SQL SERVICES

SQL Services has many useful features. Nevertheless, two standout features are ‘phpMyAdmin’ and ‘MYSQL Root Password’.

phpMyAdmin

When it comes to usage, ‘phpMyAdmin’ might be the feature which get the most clicks. The ‘phpMyAdmin’ option allows the root user to access all mySQL databases for the webmaster. If you have four cpanel accounts, you can access each and every mySQL database for all accounts.

MYSQL Root Password

By default, the mySQL root password is the same as the root password. The advantage is simplicity, the disadvantage is security. With Putty, you can login to your Linux hosting account with your root username and password.

To login to mySQL with Putty,
1) Login to Linux hosting as ‘root’.
2) Type: mysql

Wasn’t that easy? Well, you can add another layer of protection by updating the ‘Root mySQL’ password’.

To update the ‘Root mySQL Password’,
1) Select ‘mySQL Root Password’.
2) Add the password and password again.
3) Click ‘Change Password’.


DNS Web Host Manager

DNS FUNCTIONS

DNS functions allow the web developer to control the DNS for a particular domain. When you register a domain name, you must point the DNS to yours. Often, the hosting company sets it to its own DNS by default, which means you cannot view the website hosted elsewhere. After pointing the DNS to your server, you may need to login to Web Host Manager and edit the DNS after you create a new account or addon domain.

Edit DNS

Off all the DNS functions, there is a good chance that ‘Edit DNS’ would be used the most, or exclusively from the others. When you create an an account or an addon domain, its DNS will have a default value. Thus, arriving at this setting to change any dns nameservers is an obvious option.

To create a website with proper dns,
1) Register domain name.  
2) Create a new account for the domain name or create an addon domain.
3) Login to Web Host Manager and Edit DNS for the domain name; if necessary.

To edit the DNS so that it works with your hosting account,

1) Select ‘DNS Functions’.

2) Select ‘Edit DNS Zone’.
3) Select a domain.
4) Select ‘Edit’.
5) Set the DNS to your account. In this case, the main domain is example.com and the dns nameservers are ns1.example.com and ns2.example.com.
6) Select ‘Save’.


PHP.ini Change With Web Host Manager

To change php.ini file in web host manager,
1) Open Web Host manager
2) Under ‘Service Configuration’ select PHP Configuration editor. The advanced view will allow the file the most possibility to edit various settings.

Some of the setting you can change here are error reporting, max_execution_time, log_errors_max_length, upload_max_filesize, post_max_size and memory_limit.

3) Select ‘Save’.


Edit Account With Web Host Manager

 

To edit an existing account,
1) Select ‘List accounts’ under the heading ‘Account Information’ or select Home >’Account Information’  >’List Accounts’.

2) Select the desired account.

3) Select ‘Modify Account’.
4) Modify the fields.

5) Select ‘Save’.


Web Host Manager Create New Account

ACCOUNT INFORMATION

‘Account Information’ is where you create, edit and modify accounts. New accounts makes it easy to create new website(s) with a dedicated ip address. There are many reasons why you may want to do that. For instance, you may have a client who publishes controversial subject matter or sends mass amounts of spam email. Therefore, putting the client at his own address could be beneficial for other clients. One spammer can ruin it for others.

To create a new account,
1) Select ‘Account Functions’ or select ‘Home’ >’Account Functions’.

2) Create ‘New Account’.

3) Fill out web site details.
4) Select Create.


System Reboot With Web Host Manager

SYSTEM REBOOT

One of the first features the administrator of a VPS or dedicated server needs to be familiar with is ‘System Reboot’. You can reboot a server if the memory becomes depleted or you notice the site is down for some unknown reason. Furthermore, you will reboot the server if you alter system files like php.ini, my.cnf or, you rebuild the Apache server.

To reboot a VPS or dedicated server,
1) Login to WHM.
2) Select `System Reboot` from the home menu, or scroll down on the left menu until you see `System Reboot`.
3) Select `Graceful Server reboot`or ‘Forceful Server Reboot’. ‘Graceful Server Reboot’ will finish executing unfinished processes and reboot while a ‘Forceful Server Reboot’ will not wait until processes finish. Often, the wait for a ‘Graceful Server Reboot’ is very short.


Using Web Host Manager

Web Host Manager is a server admin control panel which allows an administrator to control Cpanel accounts. With WHM(Web Host manager), you have access and control to each and every reseller account through its unique interface. But, there is many built-in features. You can control the php settings with the php.ini file, reboot the Apache server, customize DNS and email MX settings. The chapter will not discuss each detail about Web Host Manager, but, you will have the necessary tips and tools needed to keep a healthy server up and running.

Web Host Manager is a very good and popular admin tool that is offered by giant hosting comapnies like Hostgator, Peer1 while cpanel is used by many too. Using a hosting service with Web Host Manager is a common practice for people who have outgrown a simple shared hosting account. There are many reasons why there is a need to upgrade such as; your websites get sufficinet traffic and / or you use too many shared resources. With shared hosting, you share memory and PHP server resources with others who use the same server. Eventually, as websites grow, the web host may ban or suspend your account based on your over-usage of resources. The best way to solve this problem, is to remove the sharing part. From experience, you often get what you pay more. The more you pay, the better the reources, the better the website performance.

Normally, when you upgrade from a basic shared hosting account, your options are a reseller account, VPS hosting and Dedicated server. A reseller account has access to Web Host Manager. However, the sharing part still exists. This really can be a potential bottleneck; especially is someone runs cron jobs on scripts that hog resources. The only advantage of reseller plans over VPS are ease of use. With a reseller plan, you don’t have the responsibility of keeping the server up and running.

With VPS and dedicated servers, you have access to all root files and can control, modify and configure your server as you want. But, when you must know how to manage your resources like memory, know if hardware failed,  and reboot the server if it goes down. Most companies have monthly fees for this service, but, with some practice and patience using a VPS or dedicated server can become second nature. This chapter covers the requirements for keeping a VPS or dedicated server live and well.


Remove Cron Job With Cpanel

To remove a cron job, 

1) Select ‘Cron Jobs’.
2) Select ‘Delete’. 


Cpanel Cron Jobs

Cpanel Advanced Settings

The ‘Advanced’ settings can be of use to particular individual. However, one such feature which may catch your attention is ‘Cron Jobs’. Cron jobs allow you to schedule events to happen at a certain time. An example of a cron job is to execute a php file which copies and resets a database each day. An cron could be compared to a browser automatically opening a php file each day and executing the code. 


 
Cron Jobs
 
To set a cron job, 
1) Select ‘Cron Jobs’.
2) Select options and file. 


Cpanel Optimize Website

SOFTWARE / SERVICES

The Software / Services features come with programmer perks like Pear Packages. But, the gold may lie with ‘Optimize Website’. The optimize website feature can be used to compress all websites. This can make websites load faster in a browser. When you test with a tool like Yahoo YSlow, it often recommends gzip compression for websites.

Optimize Website

To optimize website,
1) Select ‘Optimize Website’.
2) Select ‘Compress All Content’.
3) Select ‘Update Settings’.


Remove Redirect With Cpanel

To remove a redirect with Cpanel,
1) Select ‘Redirects’.
2) Find the redirects near the bottom of the page.
3) Select ‘Remove’.


Cpanel Redirecting

Redirects do the obvious. You take the traffic that arrives at a specific domain and send it elsewhere.

To set a redirect,
1) Select ‘Redirects’.
2) Select an address to redirect from.
3) Select an address to redirect to.
4) Select ‘Add’.


Cpanel Addon Domains

Domains helps you manage subdomains, addon domains and redirects. Although there are more features, addon domains and redirects are popular selections.

The addon domain button allows you to create an addon domain for the account. For example, if you have a main account with the domain example.com, you can reside the domain example2.com here as well. For shared hosting, it can be a pretty good bang for the buck.

Redirects allow you to redirect domains to other web addresses. For example, you may want all traffic that goes to example.com to redirect to example2.com.

To create an addon domain,
1) Select ‘Addon Domains’.
2) Type in domain name, username and password.
3) Select ‘Add Domain’.


Unblock IP With Cpanel

To unblock an ip address with Cpanel,
1) Select ‘IP Deny Manager’.
2) Delete the ip you are denying.


Deny IP Address With Cpanel

To deny an ip with Cpanel,
1) Select ‘IP Deny Manager’.
2) Add the ip address you want to deny.
3) Select ‘Add’.


Passowrd Protect Directories in Cpanel

Cpanel has a few security features which can be implemented quickly. Two features which could see some usage from time to time are ‘Protect Password Directories’ and ‘IP Deny Manager’.

To password protect a directory,
1) Select ‘Password Protect Directories’.
2) Select a domain.
3) Select ‘Go’.

4) Select a folder.

5) Select the checkbox >add a name >Save.


Cpanel Spam Assassin

Spam Assassin

Spam Assassin cannbe used to filter the good email from the bad. If you ever have spread your email addrerss around, you may have noticed how junk mail starts flowing in. But, spam assassin can be used to blacklist and whitelist ip addresses.

To get Spam Assassin working,

1) Select ‘Spam Assassin’.
2) Select ‘Configure Spam Assassin’.

3) Add ip addresses to filter. As you fill up the spaces, Spam Assassin automatically adds new fields.


4) Select ‘Save’.


Cpanel Webmail Access

To access webmail with Cpanel,
1) Select ‘Webmail’ > ‘Go to Secure Webmail Login’
2) Select an email option; such as ‘Horde’.

3) Select an email address from the list. At this point, using one of the email services is much like using a service such as hotmail or gmail.

As far a your clients are concered, they may want to access their webmail with their domain. It looks a little cleaner. One such trick is to add their domain into the url. For example, http://example.com:2095/ could be used to access webmail for any account at example.com; cuch as info@example.com.


Manage Email Account With Cpanel

To manage an email account,
1) Select an option from the desired email account.

 

To configure an email client,
1) Select ‘More’.
2) Select ‘Configure Email Client’.

3) Use the settings displayed to configure your email client such as Outlook or Eudora.


Setup Email With Cpanel

Handling email is one of the features that comes with Cpanel. You may be wondering, what does email have to do with PHP / mySQL? Well, it doesn’t. But, any web developer who builds PHP / mySQL websites will use these tools to administer email accounts for clients and others.

The email options appear under the heading ‘Mail’.

To create an email account,
1) Select ‘Email Accounts’.
2) Enter email address, password and quota size
3) Select ‘Create Account’.


 


Firebug Troubleshooting

FIREBUG

Firebug is an addon for Firefox or Google Chrome. It is so valuable, that it is hard to imagine a day, when it does not get used by any working web developer. Although Firebug is oftent used to troubleshoot html, css and Javascript

Get Firebug

You can simply Google ‘Firebug’ and you will have instant access to download Firebug.

Using Firebug

To open Firebug,
1) Select the Firebug icon that resembles a beetle.

Firebug opens in the bottom of the browser window.

To troubleshoot code,
1) Select the pointer next to the Firebug.
2) Mouse over the page to see the code.

At this point, you have a few simple choices to test and troubleshoot code.
3) Option A: Add css to the small window on the right hand side.
Option B: Add text to the main window.
Option C: Select a div tag or block of text >Right click the mouse >Edit HTML >Edit the html and test your new code. The changes will look as though they are live.


Object Oriented PHP Parent Constructor

These two files demonstrate how inheritance works with constructors and the parent constructor. The first file shows how properties are declared within the constructor, while the second file uses the parent constructor(parent::__construct()) to inherit properties. Both files are available for previewing.

Accessing Properties Without Parent Constructor

<?php class Bohemia
{
    protected $_category;
    public $_first_name;
    
    public  function __construct($category, $first_name)
    {
        $this->category = $category;
        $this->first_name = $first_name;
    }
    
    public function get_category()
    {
        return $this->category;
    }
    
    public function get_first_name()
    {
        return $this->first_name;
    }
}

class Blogger extends Bohemia
{
    protected $_email;
    
    public function __construct($category, $first_name, $email)
    {
    $this->first_name = $first_name.” and his friend Eugene can be contacted at”;
    $this->category = $category;
    $this->email = $email;
    }
    
    public function get_email()
    {
        return $this->email;
    }
}

$blogger = new Blogger(‘PHP’, ‘Johnny’, ‘nerdos@example.com’);
echo  $blogger->get_first_name().’ the email address “‘.$blogger->get_email().'”. They love ‘.$blogger->get_category().’.’;
?>

Accessing Properties With Parent Constructor

<?php class Bohemia
{
    protected $_category;
    public $_first_name;
    
    public  function __construct($category, $first_name)
    {
        $this->category = $category;
        $this->first_name = $first_name.” and his friend Eugene can be contacted at”;
    }
    
    public function get_category()
    {
        return $this->category;
    }
    
    public function get_first_name()
    {
        return $this->first_name;
    }
}

class Blogger extends Bohemia
{
    protected $_email;
    
    public function __construct($category, $first_name, $email)
    {
    parent::__construct($category, $first_name);
    $this->email = $email;
    }
    
    public function get_email()
    {
        return $this->email;
    }
}

$blogger = new Blogger(‘PHP’, ‘Johnny’, ‘nerdos@example.com’);
echo  $blogger->get_first_name().’ the email address “‘.$blogger->get_email().'”. They love ‘.$blogger->get_category().’.’;
?>


MYSQL NULL And IS NOT NULL

Using ‘Null’ for a database column(field) will give any row a value of ‘NULL’. That part should be obvious. But, why not just leave it blank? Why should I use ‘NULL’ and not juts use an empty string? Well, there are a few differences. First of all, Null means “a missing unknown value” while an empty string is actually a value. Therefore, when you have 0 or an empty string in a column it is NOT NULL. Only a value of ‘NULL’ is null. If you use an empty string, you can always write a clause like WHERE tablename1.columnname = tablename2.columnname. But, if one of the columns is NULL you cannot join on a NULL value. You would need the query to read WHERE tablename1.columnname IS NULL AND tablename2.columnname IS NULL.

With MySQL, a NULL value cannot be compared to anything else. To see if a column is ‘NULL’ you use ‘IS NULL’ in a query, while ‘IS NOT NULL’ can be used for NOT NULL values. The query cannot use a clause like columnname=NULL. Alternatively, columnname<=>NULL can be used to find ‘NULL’ values.

IS NULL:
$command = “SELECT * FROM table where columnname IS NULL”;

IS NOT NULL:
$command = “SELECT * FROM table where columnname IS NOT NULL”;

You can add indexes on InnoDB or MyISAM tables that contain NULL values. Since indexes enhance performance, this a good feature. When you use a clause like ORDER BY or GROUP BY, all; NULL values are equal; just like ordering by lastname asc where three people have the same name ‘Anderson’. When NULL values exist in a column, they will show up first if the data is output by ascending order.