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

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="https://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 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'];
}

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 https://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.


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.

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;
    }
}

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();
}

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'];

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 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.


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

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:
https://fullstackwebstudio.com/locations/coding-blog/sqlite-vs-mysql.html
https://fullstackwebstudio.com/locations/coding-blog/connecting-to-mysql-with-pdo.html
https://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');

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 https://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

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 https://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 https://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);

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 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 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

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);

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


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 https://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 

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

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 https://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


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.

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>

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} 

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.


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.

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
));*/


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.

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


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); 

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 https://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.

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.


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;

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.


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.  


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


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.


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","https://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('https://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","https://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

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'); 

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>

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>

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);

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


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);	
	}

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) ";

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.


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.

PHP Event Calendar Script

Using a PHP calendar Script can be a convenient method for which to keep track of upcoming events. The script could be integrated for use with Google Calendar or as a stand alone application. One free php calendar script can be found here. The php calendar script demo can be seen here.

Calendar scripts are very popular additions to websites. Hair salons, bed and breakfasts, and event promoters can benefit from online bookings.

Calendar scripts can be built for various access levels. The entire could be private, or only the calendar is available to the public. On the other hand, the script could allow the public to post events on the calendar with or without administrator approval.

The code example below shows how you can take a url array with PHP and use it as a string within Javascript. The urls array could include a file and links to a public Google Calendar.

Make Array in PHP For Google Calendar :

$command = “SELECT * FROM calendar_urls “;
$result = mysqli_query($db, $command);

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

$url =  $row[‘calendar_array’];
$urls[] = $url;
}

Add To Array To javascript With Google Calendar :

eventSources: [
<?php echo implode(“,”, $urls); ?>

Selecting Only Numbers From Rows With MYSQL

When it comes to altering data from the database, PHP usually has an answer. In this particular situation, we are outputting weight from the database. The rows from the database output with lbs. For example, the weight for John Sims may be 175 lbs. Now, we want to remove the lbs because the plan is to use the 175 for comparison with Google Chart Tools.

How to we remove the lbs from each row that outputs? We use the preg_replace() function to select only digits.

$command = “SELECT firstname, lastname, weight FROM table_sort WHERE height<>” AND weight<>” “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$firstname = trim(addslashes($row[‘firstname’]));
$lastname = trim(addslashes($row[‘lastname’]));
$height = $row[‘height’];
$height = preg_replace(‘/\D/’, ”, $height);
}

PHP Header Function

The header() function has various uses. It can output headers for an xml file, force downloads and redirect pages to a new url. If it is used to redirect a url, there must not be any html or text of any sort.

Redirect With Header() Function

To redirect with header(),
1) Type: header(“Location: filename.php”);

PHP Force Downloading

   header(“Content-Type: application/force-download”);
   //the filename will be given below
   header(“Content-Disposition:filename=\”$myfilename\””);
   
   header(‘Content-Description: File Transfer’);
    header(‘Content-Type: application/octet-stream’);
    header(‘Content-Disposition: attachment; filename=’.basename($myfilename));
    header(‘Content-Transfer-Encoding: binary’);
    header(‘Expires: 0’);
    header(‘Cache-Control: must-revalidate’);
    header(‘Pragma: public’);

CREATING XML File

header(‘Content-Type: application/xml’);
echo ‘<?xml version=”1.0″ encoding=”UTF-8″ ?>’.'<?xml-stylesheet type=”text/xsl” href=”sitemap.xsl”?>’;

echo ‘<urlset xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd” xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″>’;

Google Bar Chart With PHP MYSQL

The example below takes the names, height and age from a database table and outputs it into a simple chart. The original chart was a yearly chart which displayed year, sales and expenses. The key to this example, is to get the desired code into the Javascript.

Here is what we want to change:

var data = google.visualization.arrayToDataTable([
[‘Year’, ‘Sales’, ‘Expenses’], [‘2004’, 1000, 400], [‘2005’, 1170, 460], [‘2006’, 660, 1120], [‘2007’, 1030, 540] ]);

Here is what we want to change it to:

var data = google.visualization.arrayToDataTable([
[‘Name’, ‘Height’, ‘Weight’],
<?php echo implode(“,”, $myurl); ?>
]);

Full Code:

<?php
session_start();
include(‘connect.inc’);
$db=public_db_connect();

//get columnname id
$command = “SELECT firstname, lastname, height, weight FROM table_sort WHERE height<>’’ AND weight<>’’ “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$firstname = trim(addslashes($row[‘firstname’]));
$lastname = trim(addslashes($row[‘lastname’]));
$height = $row[‘height’];
$height = preg_replace(‘/\D/’, ‘’, $height);
$weight = $row[‘weight’];
$weight  = preg_replace(‘/\D/’, ‘’, $weight);

$myurl[] = “[‘”.$firstname.” “.$lastname.”’, “.$height.”,”.$weight.”]”;

}

print_r($myurl);
echo implode(“,”, $myurl);
?>
<html>
<head>
<script type=”text/javascript” src=”https://www.google.com/jsapi”></script>
<script type=”text/javascript”>
google.load(“visualization”, “1”, {packages:[“corechart”]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[‘Name’, ‘Height’, ‘Weight’],
/* [‘2004’,  1000,      400],
[‘2005’,  1170,      460],
[‘2006’,  660,       1120],
[‘2007’,  1030,      540]*/
<?php echo implode(“,”, $myurl); ?>
]);

var options = {
title: ‘Company Height and Weight’,
vAxis: {title: ‘Members’,  titleTextStyle: {color: ‘red’}}
};

var chart = new google.visualization.BarChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id=”chart_div” style=”width: 900px; height: 500px;”></div>
</body>
</html>

Google Pie Chart With PHP

The Google pie chart below is made from querying the mySQL database. Then, an array is made. The array must fit exactly the same way as it is presented in the javascript file. After the array is built, you add PHP code into the Javascript.

Add the code:
<?php echo implode(“,”, $myurl); ?>

This code turns the array into a string that replaces hard coded values.

<?php
session_start();
include(‘connect.inc’);
$db=public_db_connect();

//get columnname id
$command = “SELECT DISTINCT lastname FROM table_sort “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$lastname = trim(addslashes($row[‘lastname’]));
$lastnamearray[] = $lastname;

//get the count
$commandb = “SELECT count(*) as cnt FROM table_sort WHERE lastname =’$lastname’ “;
$resultb = mysqli_query($db, $commandb);
while($row = mysqli_fetch_assoc($resultb)) {
$cnt = $row[‘cnt’];
$myurl[] = “[‘”.$lastname.”’,”.$cnt.”]”;
}
}

?>
<style>
#chartArea{background:red;}
#chart_div{background-color:white;}</style>

<!–Load the AJAX API–>
<script type=”text/javascript” src=”https://www.google.com/jsapi”></script>
<script type=”text/javascript”>

// Load the Visualization API and the piechart package.
google.load(‘visualization’, ‘1.0’, {‘packages’:[‘corechart’]});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn(‘string’, ‘Rep’);
data.addColumn(‘number’, ‘Assigned Leads’);
data.addRows([
/* [‘Mushrooms’, 3],
[‘Onions’, 1],
[‘Olives’, 1],
[‘Zucchini’, 1],
[‘Pepperoni’, 2]*/

<?php echo implode(“,”, $myurl); ?>
]);

// Set chart options
var options = {‘title’:’Display Last Names’,
‘width’:500,
‘height’:450};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
}
</script>
</head>

<body>
<!–Div that will hold the pie chart–>
<div id=”chart_div”></div>
</body>
</html>


GOOGLE CHART TOOLS FOR DEVELOPERS

Google has many free tools and javascripts for which a developer can download and use. A very good set of tools for a PHP programmer are the chart tools. Basically, the chart tools are javascripts provided by Google. But, php developers can use them with PHP / mySQL queries to put the data into the charts. They keyo to most charts is the usage of php tags within the Javascript. Since most charts use an array of data; PHP allows you to print a string within the Javascript so that you can input desired data from the database. This section will demonstrate how to effectively use the charts with php tags within Javascript code.

Many Google Codes can be found at the ‘Code Playground’.
The Google Playground can be found at http://code.google.com/apis/ajax/playground/?type=visualization
For example, pie charts can be found at the playground.

To get a desired chart at the ‘Google Playground’,

1) Select an option under ‘Pick Api’.
2) Select ‘View Docs’.

Google Pie Charts
If you want to add a Google pie chart to your website, you can find them at https://developers.google.com/chart/interactive/docs/quick_start or https://developers.google.com/chart/interactive/docs/gallery/piechart

Find MYSQL Errors

To locate mysql errors, you can use the code below after you run a query. Then, load the page in the browser and locate the error.

print (“Query: “.$command.” Error Message: “.mysqli_error($db));

Full Code:

$command = “SELECT firstname, lastname, height, weight FROM table_sort WHERE height<>” AND weight<>” “;
$result = mysqli_query($db, $command);
print (“Query: “.$command.” Error Message: “.mysqli_error($db));


Wamp Not Working (Yellow Icon)

This tutorial explains how to fix Wamp server when it does not work properly. After many reliable uses, Wamp could suddenly not work as expected.

To deal with a failed boot,
1) Check for other programs(particularly Skype) using port 80. If Skype is on, quite Skype and run Wamp first. The conflict disables Wamp but Wamp won’t disable Skype.

If the above fails,
1) Click wamp icon >Apache >Service >Remove Service
2) Click wamp icon >mysql >Service >Remove Service
3) Click wamp icon >Apache >Service >Install Service
4) Click wamp icon >mysql >Service >Install Service
5) Click wamp icon >Restart All Services


PHP File Download Script

Using a PHP Download Script can be a convenient method for which to keep track of uploads and downloads on a website. The script could be used in a method for which the administrator can login to the backend and set files for downloading. The files could be any extension from jpeg to mp3 to txt. One free php downkoad script can be found here. The php file download script demo can be seen here.

File upload and download scripts can be extremely useful for people who surf the web and want to store jquery plugins, javascripts and other code formats like css. File management will make code reusability much simpler and faster.

The heart of PHP upload and download scripts can be easy to make. The upload script will need a form an input box designed for file uploads while the download script will need to force downloads for various file types. 

PHP File Upload Code:

<form enctype=”multipart/form-data” action=”<? echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>

    <input type=”hidden” name=”MAX_FILE_SIZE” value=”1000000″>
    <input type=”hidden” name=”myhid” value =”hi”>
    <style type=”text/css”>

PHP File Download Code:

$myfilename=$_GET[‘filename’];
$filepath = $_SERVER[‘DOCUMENT_ROOT’].”/uploads/”.$myfilename;
if (file_exists($filepath)) {
//download application
   header(“Content-Type: application/force-download”);
   //the filename will be given below
   header(“Content-Disposition:filename=\”$myfilename\””);
  
   header(‘Content-Description: File Transfer’);
    header(‘Content-Type: application/octet-stream’);
    header(‘Content-Disposition: attachment; filename=’.basename($myfilename));
    header(‘Content-Transfer-Encoding: binary’);
    header(‘Expires: 0’);
    header(‘Cache-Control: must-revalidate’);
    header(‘Pragma: public’);
  
//open file in binary mode  
$my_file = fopen($filepath, ‘rb’);
//output data
   fpassthru($my_file);
//close file
   fclose($my_file);
   }

PHP Ajax Example

The following example for php and ajax will show how to make an input box with a specific name when a button is clicked. When a button is clicked, the id for the particular person is passed into a url. The id of the person is then used to output his first name in an input box.

Three files are used. One file is the page you see in the browser, another file connects to the database and the third file outputs the new input box.

File#1

<?php include(“connect.inc”);
$db = public_db_connect();
?>
<html>
<head>
<script type=”text/javascript”>
function listMembers(str)
{
if (str==””)
{
document.getElementById(“my_text”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“my_text”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”ajax-get-input.php?formname=”+str,true);
xmlhttp.send();
//alert(str);
}

</script>
</head>

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’].”?”.$_SERVER[‘QUERY_STRING’]; ?>”> <?php
$command= “SELECT id, firstname, lastname FROM table_sort WHERE id=3 “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

$id=$row[‘id’];
$firstname=$row[‘firstname’];
echo ‘<div id=”my_text”><input type=”button” value=”‘.$firstname.'” name=”‘.$id.'” onclick=”listMembers(this.name)” /></div>’;
}
}?>
</form>
</html>

File #2

<?php include(“connect.inc”);
$db = public_db_connect();
$myid = $_GET[‘formname’];
//echo $myid;

$command3=”SELECT firstname, lastname FROM table_sort WHERE id =’$myid’ “;
$result3 = mysqli_query($db, $command3);
while($row = mysqli_fetch_assoc($result3)){
$first_name=$row[‘firstname’];
echo “Output for: “.$first_name.”<br/>”;
echo ‘<input type=”text” value=”‘.$first_name.'” name=”members” />’;
}

mysqli_close($db);
?>

PHP Ajax Tutorial

The following tutorial for php and ajax will show how a drop down menu can be created with php and ajax.The example uses 2 files. The first file, creates a menu that changes when a user selects a value. The second file takes in the id of the person with the email address and makes a new drop down menu based on the id. In this case, the new options are those names with an id greater than the $_GET[‘mystring’] and less than that value + 4.

File#1

<?php include(“connect.inc”);
$db = public_db_connect();
?>
<html>
<head>
<script type=”text/javascript”>

function listMembers(str)
{
if (str==””)
{
document.getElementById(“my_text”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“my_text”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”ajax-get.php?mystring=”+str,true);
xmlhttp.send();
//alert(str);
}
</script>
</head>

<?php
function tablesort_menu() {
global $db;
echo ‘<select id=”my_text” name=”members” onchange=”listMembers(this.value)”>’;
$command= “SELECT DISTINCT id, email FROM table_sort “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

$id=$row[‘id’];
$name=$row[’email’];

echo “<option value=\”$id\” >$name</option>\n”;
}
}
echo ‘</select>’;
}

?>
<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’].”?”.$_SERVER[‘QUERY_STRING’]; ?>”> <?php
tablesort_menu(); ?>
</form>
</html>

File #2

<?php include(“connect.inc”);
$db = public_db_connect();
$myid = $_GET[‘mystring’];
$myid2 = $myid + 4;

$command2=”SELECT firstname, lastname FROM table_sort WHERE id>’$myid’ AND id<‘$myid2’ ORDER BY firstname ASC”;
$result2 = mysqli_query($db, $command2);
echo ‘<select name=”name_list”>’;
while($row = mysqli_fetch_assoc($result2)){
$first_name=$row[‘firstname’];
$last_name=$row[‘lastname’];
echo “<option value=\”$first_name\” >$first_name</option>\n”;

}
echo ‘</select>’;

mysqli_close($db);
?>

PHP CMS Light Weight

When you pick a CMS, it can’t hurt to do a little homework. You’ve heard of the big players; like Joomla, Drupal and WordPress. Although these CMS’ have great features and expandability, they may not offer the typical website owner the styling flexibility and performance of a Lightweight PHP CMS. From a web developer’s point of view, you get very well acquainted with how long page load times takes with some platfroms; since you saving and testing can run into the hundreds of thousands. When you do this, you can see and feel a huge difference between 1/10 of a second and 2 seconds. Throw in a slow web cafe and 2 turns to four.

After years using Joomla and WordPress for content management, we made the switch to a custom php cms since it delivered better performance, exact styling and faster completion.

As a case study,  remember an example with someone who spent countless hours to build a website with WordPress. Then, I copied his source code and dumped it into Sitemakin CMS. Then, I opened up the editor and made some changes. All of this took place in less than 2 minutes. Then, a quick eyeball even showed how much faster of a load time the new site had over the original.

Also, if you go custom coded sites you can also php code around any other templates that come with the package. Many template companies now provide so much good code at a very affordable price. Code that is much more workable on a customizable level.

PHP MYSQL Example

PHP / mySQL is used by programmers to store and output data. Well, there is a lot more to it. PHP can use a lot of built in Internet information like rss feeds, display dates and times from a server, and print html / css…just to name a few things.The 4 commands below can be implemented to select, add, update and delete data.

Select Data

$command = “SELECT * FROM table_sort where id >0”;
$result = mysqli_query($db, $command);
if($result){
echo “There are entries”;
}

Insert Data

$command = “INSERT INTO table_sort VALUES(NULL,’$value’,’$value2′,’$value3′,now()) where id =5”;
$result = mysqli_query($db, $command);
if($result){
echo “Inserted”;
}

Update Data

$command = “UPDATE INTO table_sort set name=’John’ where id = 2 “;
$result = mysqli_query($db, $command);
if($result){
echo “Updated”;
}

Delete Data

$command = “DELETE FROM table_sort where id = 2 “;
$result = mysqli_query($db, $command);
if($result){
echo “Entry Deleted”;
}

PHP MYSQL SELECT

The select statement is the basic command which grabs data from the database. The select statement can be very basic or more advanced. A basic select statement would grab all data from one database table and output it in a list or table.

Normally, the programmer grabs the desired data then lets html, css and javascript to apply special styling to the data.

Writing a Basic PHP MYSQL Select Statement

The basic SELECT statement can only take place when you connect and select a database. Once you have done that, you can select data.

include(‘connect.inc’);
$db = db_connect();

$command = “SELECT * FROM table_sort ” ;
$result= mysqli_query($db, $command);
$row = mysqli_fetch_assoc($result);
$first= $row[‘firstname’];
$last = $row[’email’];

echo “”.$first.” “.$email;

PHP MYSQL Connect

The connection to the mySQL database is the basics to php / mySQL. If this fails, all fails. Once you can connect to a database, you can select and alter data. It is like learning to walk.

Whether you plant to create a simple or elaborate PHP / mySQL application, you must connect to a mySQL database. There are many ways to write the code for which to do so, but,two functions will be present for you to do so. The two functions are mysqli_connect() and mysqli_select_db. The function mysqli_connect will appear first for obvious reasons. Doesn’t it make sense to first connect to a database then select it?

Normally, there are two methods for which the connection takes place. One technique is to use a function and the other is to just add the code into a page. Using a function is more secure and it saves on code repetition. This might not look like much now, but, an 8,000 word php/mysql application with separate database connection files used on a new server could be a hassle to fix up more than once.

Accessing Database With Function

The code below $db = public_db_connect(); calls the function and returns the $db variable. That variable can be passed into select, update, delete, and insert into queries.

function public_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 = public_db_connect();
$command = “SELECT * FROM table_sort where id >0”;
$result = mysqli_query($db, $command);
if($result){
echo “There are entries”;
}

Accessing Database Without a Function

The code below will connect to a database. The $db variable is used in the mysqli_query() function. The output is the same as the example above.

    $host = “localhost”;
$user = “root”;
$pw = “”;
$database = “ABOOK”;

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

mysqli_select_db($db, $database)
or die(“Cannot connect to database.”);

$command = “SELECT * FROM table_sort where id >0”;
$result = mysqli_query($db, $command);
if($result){
echo “There are entries”;
}

Making Cpanel Addon Domain Without Subdomain

Add on domains are a great asset to any web developer. When you have a hosting account you often have the option to have many or unlimited addon domains on one account.In most aspects, it is a great value for your buck. However, there are some differences that must be noted about addon domains. An addon domain gets made as a subdomain. You may see that the new site example.com shows up in the browser just like the main domain, and an added subdomain shows as subdomain.example.com. But, a page on the addon domain can be viewed as example.mainsite.com/mypage.html. Although this looks innocent, it can cause some of the urls of the addon domain to rank higher on Google than the actual subdomain. To solve the issue of urls shoing up as a potential subdomain or actual url, the codes below can be added to the htaccess file so your site cannot be access through the subdomain.

Web Templates

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} mainsite\.com$
RewriteRule ^(.*)$ “http\:\/\/www.addondomain\.com\/” [R=301,L]

</IfModule>

WordPress

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} mainsite\.com$
RewriteRule ^(.*)$ “http\:\/\/www.addondomain\.com\/” [R=301,L]

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>

Joomla

########## Begin – Joomla! core SEF Section
#

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteCond %{HTTP_HOST} websitebc\.com$
RewriteRule ^(.*)$ “http\:\/\/www.example\.com\/” [R=301,L]
RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
#
########## End – Joomla! core SEF Section


Real World PHP / mySQL Coding Example

Calendar Application With Database and Google Integration

You decide to make a custom calendar integrated with Google calendar. In other words, the calendar will grab data from a database and Google Calendar. You explore and discuss the options, and it comes down to a custom script, modified script or purchased script. After browsing the various options, the decision came down to a custom calendar script that will integrate with Google. You surf the web and find this JQuery Plugin called full calendar. The plugin comes with good documentation and it leaves room to do what you want. But, it needs plenty of work and adjustments to make it function exactly as desired.

Initially, the first step is to download the files and test them in wamp or Firefox. After looking into the files, you
attempt  to set it up to work seamlessly with Google Calendar. But, it is not outputting as desired. After a short investigation, adding ‘<script type=’text/javascript’ src=’fullcalendar/gcal.js’></script>’ into the head of the file made things work properly. Then, changing the extension(.html) to index.php helped make things flow perfectly. After all, this is a php/mySQL script and we will need to work with a mySQL database. Then, the files were reordered so that the files of interest were in the root folder and css and js files were in the next level of folders. In the end, we created 4 files; index.php, edit_calendar.php, events.php and connect.inc and used the remaining cs and js files which came with Fullcalendar.

Seeing out it output with Google Calendar laid down a lot of groundwork for database preparation. But, some users will not use Google calendar. Therefore, the script must be made to work with a database as well.

 In the end, we set up two database tables for the sources and one for the entries. The sources tables had two entries; one for the the Google calendar xml feed and one for a local file which made an array of the various entries for the calendar.

Then, you customize the a few pages so that entries output and you can add, edit, update and delete entries. With a little intensive date coding session; you end up with a robust system to make and adjust appointments with exact dates and times.

Then, you test to confirm the desired results. After creating, updating, editing and deleting a few entries; you have a solid calendar.  

Now that the scripts works, you find change the file order around so that the index.php


Coding Summary:

File: connect.inc
The file connect.inc was added in order to connect to the ABOOK database.

File: index.php
The file json.html became index.php

The script ‘<script type=’text/javascript’ src=’fullcalendar/gcal.js’>’ was added to the head tag

A query was written to make an array of the urls for which to get calendar events. At nearly the same time, the database table was made to hold entries which display on the calendar.

Near line 43 we loaded the url sources for events we want to publish by adding eventSources: [<?php echo implode(“,”, $urls); ?>  ]

A form was created to allow for adding events into the database.

File: File: events.php
The file json-events.php became events.php

The static array and commented it out and made the entries come out dynamically with the events array.

File: edit_calendar.php
This file was used to edit and delete entries.


Open MYSQL Console with WAMP

Using the mySQL console is a typical step to learning PHP / mySQL. The mySQL console can be accessed after you start the Apache server in your Windows, Linus or Apple environment. Typically, WAMP or XAMPP is the application which is installed on your pc which contains the mySQL console. The procedure to access the mySQL console is shown below.

1) Start Wampserver

 

 

2) Select the WAMPSERVER icon

 

 

3) Select MYSQL >MYSQL Console

 


Advantages of mySQL Console

The advantage os using a mySQL console is that you can run all database queries, connect remotely with Putty on any computer, and run other mySQL commands such as query_cache and view details about available cache memory, etc.


Advantages of Using PHPMYADMIN vs mySQL Console

The advantages of using phpMyAdmin is that it has a user interface and you can run queries within the SQL. Another advantage is that you can paste queries into the SQL to test data output; fom a simple ‘Select * FROM tablename’ to more advanced relational queries using various tables. The copying and pasting of queries is not available with the mySQL console. If you make a typo with the mySQL console, you must start again.

MYSQL password() Function

With mysql, you can create a password by typing:

select password(‘password’);

The password in this case is the string ‘*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19’

To update a password,
1) Open SQL with phpMyAdmin.
2) UPDATE tablename set password=password(`pass123`) WHERE username =’myname’

However, you can always use the password() function in a query with PHP.

For example,
$string= ‘password123’;
$command = “INSERT into tablename VALUES (NULL, ‘”.addslashes($_POST[email]).”‘, password($string));

MYSQL Whitespace Issues

With mySQL your data output could be suspicious. One such culprit could be whitespace; which is easy to miss at first glance.

However, if you are stuck 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.

Another method is to use trim() or ltrim() function with mySQL or phpMyAdmin.

Here is a query which trism whitespace for all entries in a column for which the id >0.

UPDATE tablename set columnname = rtrim(columnname) WHERE id >0;

Yet, another method is to trim whuitespace with PHP. You can add the trim() function to post variables that are inserted into a database so that whitespace is removed.

Example query:
$var = trim($_POST[‘name’]);

$command = “INSERT into tablename VALUES(NULL, ‘$var’)”;


Column Distinct Values In A Specific Column With MYSQL

The code below can be used to get the distinct values in a column. For example, if there was 4 entries which had dog, cat, cat and monkey…the result would be 3.

Objective:
Select distinct values in a specific database table.
 
Procedure:
$command = “SELECT count(DISTINCT columnname) as cnt FROM tablename WHERE id=’$id’ ORDER BY date ASC “;

MYSQL Replace() Function

The mySQL replace() function is a fantastic function for which you can select and change data from a database table. For example, let’s assume one column in a table has lbs or cm next to it; but you want to make mathematical comparisons without the letters. Well, replace() allows you to remove the lbs or cm from the values. The replace() function can be used to replace all sorts of data from a string; such as whitespace, numbers and letters.

The example below shows how the cm and lbs is stripped from selected values from a table.

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/>”;
}

PHP strtolower() and strtoupper() Functions

The strtolower() and strtoupper() php functions can be used to change the case of a variable. The example below shows how that is done.

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/>”;
}

MYSQL LOWER() And UPPER() Functions

The upper() and lower() functions with mySQL can be used to change selected data into lower case or upper case values. These functions are very similar to PHP strtolower() and strtoupper() functions.

include(‘connect.inc’);
$db = public_db_connect();
//MYSQL LOWER() and UPPER() Functions

$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/>”;
}


MYSQL Exporting CSV Files Vs Exporting SQL

With phpMyAdmin, you can export table data in all sorts of formats; such as sql and csv. However, you should make the best effort to ensure you get the data you want. When you select specific values from a table or do a relational database query with 2-4 tables, phpMyAdmin will display the data for which is seeked. However, if you want to export the exact tuples and values of desired data; you will want to export as a csv file. Howver, you will want to use the export command near the bottom of the page. To export that csv file, look for ‘Query results operations at the bottom of the page.

To export a relational database query or custom set of tuples,
1) Select Query results operations >Export >Choose CSV (for compatibility)
2) The csv file can be opened in Excel for viewing purposes.

Note:
If you export a sql file it will give entire table even though your query created custom columns with custom values.  But, if you export a csv file and make a new table with same column count you can import the csv file into a new table.

To import the csv file into a new database table,
1) Create a database table with the same number of columns.
2) Import the file into the new table.
3) Add a new column with autoincrement field if desired. The column will populate automatically.
 


Invalid Argument Suppplied foreach()

The foreach loop is a fine way to split apart an array and output separate values. Howver, you must ensure an array exists and can be output as desired. If you make a mistake and do not create an array (but thought you did), you may get an error like the one below.

Warning: Invalid argument supplied for foreach() in C:\wamp\www\ABOOK\SORTING\TABLES\filename.php on line 162

To get to the through the root of the problem you can backtrack and make sure your array and its values are properly represented. Using print_r() always help in showing your array. If the array is good, the next step would be to analyze the items within the array.


PHP Contact Form

This simple contact form can be used to validate and send email. It checks for a few basic requirements like a properly written email address, a name and a message.

<?php
$email = trim(stripslashes($_POST[’email’]));
$email_send_to = “info@example.com”;
$subject = “Enquiry From Website”;
$name = trim(stripslashes($_POST[‘name’]));
$message = trim(stripslashes($_POST[‘message’]));

if (count($_POST) >0) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || ($name == “Your Name” || $email == “Your Email” || $message == “Message”)) {
    header(‘Location: https://fullstackwebstudio.com/locations/coding-blog’);
exit();
} else {
$body = “”;
$body .= “name: “;
$body .= $name;
$body .= “\n”;
$body .= “message: “;
$body .= $message;
$body .= “\n”;

// send email
$mail_send = mail($email_send_to, $subject, $body, “From: <$email>”);

echo “Mail was successfully sent!”;
}
}
?>
<div>
                    <form method=”post” action=”contact_form.php”>
                    
                    <p><input name=”name” type=”text” onfocus=”if(this.value==’Your Name’) this.value=”” value=”Your Name” /></p>
                            <p><input name=”email” type=”text” onfocus=”if(this.value==’Your Email’) this.value=”” value=”Your Email” /></p>
                
                             <p><textarea style=”width:400px;” name=”message” onfocus=”if(this.value==’Message’) this.value=””>Message</textarea></p>
                    
                              <p><input name=”submit” type=”submit” value=”Send Message”/></p>            
                      </form>
                </div>   


Displaying Files Within a Directory

The code below is used to display the various css files with a directory.

The code below is checking if a direcory was selected from a form. The $_POST[‘dir’] was from the input box with the name=”dir”. If no directory was selected we use getcwd() function to get the current working directory.

if($_POST[‘dir’]){
        $dir = $_POST[‘dir’];
        }
        else {
        $dir = getcwd();
        //echo $directory;
        }

The code below scans the files in tye directory. The files are in an array. Then, the array is sorted with a foreach loop. If the file name is longer than 3 characters and contains ‘.css’, the file list is output.
$files1 = scandir($dir);
foreach($files1 as $file){
if(strlen($file) >=3){
$foil = strstr($file, ‘css’); // As of PHP 5.3.0
//$pos = strpos($file, ‘css’);
if ($foil==true){
echo $file.”<br/>”;
}
}
}


PHP Sort Function

The PHP sort() function is a simple way to sort an array.The sort() function removes old keys and makes new ones. Although the results can be unpredictable in some instances, it can be useful in sorting arryas alphabetically or by date.

To use the sort function,
1) Add the array inside sort().
ie) sort($myarray);

PHP Array Diff

With the array_diff() function, you can compare 2 arrays and get the difference between the two of them. The code below takes ids from one table and compares it to the ids of another table.

## Get first array
$command = “SELECT * FROM table1 “;
$result = mysqli_query($db, $command);
while($row = mysqli_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 ids

$id2[] = $id;
}
}
else{
$id2[]=0;
}

## CCompare teh difference of the ids in the 2 tables
$result_diff = array_diff($1id, $id2);

PHP Double While Loops

Using while loops, you can extract rows of data for which you and create variables with the results. Afterwards, you can use the variables to sort through more data. When sorting through databases, you can write single queries to obtain rows from one or more tables.

From time to time, you may find you need a large query to obtain the data you want. In this case, using joins is the way to go. But, the next two examples show has one query is used to capture ids from the first table. Then, the ids are used to select a url if the member_id exists in the second table. Again, this is spotting issues rather than recommending as a procedure.

Example#1

<?php require_once(‘dbconnect.inc’);
$db=dbconnect();
$start = microtime(true);

$command= ‘SELECT id FROM table_sort ‘;
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];

$command2= “SELECT url FROM members_urls WHERE member_id=’$id’ “;
$result2 = mysqli_query($db, $command2);
while($row = mysqli_fetch_assoc($result2)) {
$url = $row[‘url’];
echo $url.'<br/>’;
}

}

Example #2

This example shows how an array can be made with the second while loop. Then, the array is pulled outside the loop and individual values are printed.

<?php require_once(‘dbconnect.inc’);
$db= dbconnect();
$start = microtime(true);

$command= ‘SELECT id FROM table_sort ‘;
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];

$command2= “SELECT url FROM members_urls WHERE member_id=’$id’ “;
$result2 = mysqli_query($db, $command2);
while($row = mysqli_fetch_assoc($result2)) {
$url = $row[‘url’];
$url_array[] = $url;

}
}

$url_array = array_unique($url_array);
//print_r($url_array);

foreach($url_array as $item) {
echo $item.'<br/>’;
}


PHPMYADMIN Null Column Default Value

When an entry is added to a database, you could insert ‘NULL’ by default if wish to do so. One such example could be that you have a form and the user can insert their email address or leave it blank. If it is left blank, the default ‘NULL’ value can be inserted instead.

To make the column value NULL,
1) Open PHPMYADMIN.
2) Select Structure.
3) Select edit for the desired column.
4) Select ‘Null’ for default.
5) Click the ‘NULL” checkbox.
6) Select ‘Go’.

PHP Finding Text in a String

With PHP, you may want to see if text exists in a string. For example, you may have database output from an api and you want to search the rows for particular string. Or, you may want to make conditional statements based on the database output. For example, you may to sort the same ‘John’ from all other names in a loop. The code below shows two methods for doing so using the preg_match() function and the strpos() function.

<?php
        $complete_text = “Giants Home Game”;
        $string = “Giants”;
        $pos = strpos($complete_text, $string);
        if($pos === false ) {
        echo “It is not in the string.”;
        }else{ echo “Yes it is in the string.”; } ?>
        
        <?php

        $string_entire = “SF Giants in World Series”;
        $string_to_find = ‘SF Giants’;            
        if(preg_match(“/$string_to_find/”, $string_entire)==true) {
        echo “<br/>Found it!”;
        }
        else {
        echo “<br/>Not in the string”; }
        ?>


PHP Parse error: syntax error, unexpected ‘}’, expecting ‘]’

PHP is quite good at helping you fix errors. At times, you may make the od mistake by closing a bracket with a square bracket when it should be a curly brace. The code below is an example for which you should go to line 22 and fix the error.

Parse error: syntax error, unexpected ‘}’, expecting ‘]’ in /home/myaccount/file.php on line 22

PHP Parse error: syntax error, unexpected T_STRING

PHP programmers will see error codes during development. One such error is ‘unexpected T_STRING’. This error usually means a semi-colon is missing. The error code will give a line number and it is best to start from there. Then, correct the error and try again. below is an example of the error as it would be displayed in a browser.

Parse error: syntax error, unexpected T_STRING in /home/myaccount/public_html/myfile.php on line 42

PHP Loops and Resources

First of all, not all loops are created equal. When coding in PHP or any other language for that matter, it never hurts to write code that is highly optimized. With PHP, there are so many ways to do things that you will see code written in all sorts of ways. And loops are particularly vulnerable to such unorthodox ways for which they can be written.

Since loops are often written within loops, a multitude of options are available. For example, you may query a database and obtain an array of ids in a while loop. Then, you may want to run another while loop within the while loop to check another table for data where the ids match.

Here are 2 examples for which the output is exactly the same. The first sample uses a single loop to print out data while the second example will make an array of the ids in the first loop, then use that array to find other data in a second loop. As you can see with a timing function called microtime(), example one not only outperforms example 2; it blows it away.

The small time might seem unnoticeable to the eye, but with larger websites, larger traffic and more loops added into the equations; writing optimized code can sure pay dividends. The overall performance will be better since less resources will be consumed. If you want to go big, you will want your queries as optimized as possible.

Example #1

$db=db_connect();
$start = microtime(true);
//$ids_all = array();
$id=array();
$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/>”;
}
$end = microtime(true);
$elapsed_time = number_format($end – $start,4);

echo “Time took $elapsed_time seconds\n”;

Example#2

$db=db_connect();
$start = microtime(true);
//$ids_all = array();
$id=array();
$command= ‘SELECT id FROM table_sort’;
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];
$ids_all[] = $id;

}

$ids_all = array_unique($ids_all);

foreach($ids_all as $id_user){
echo “<h2>Hi id #”.$id_user.”</h2>”;
$command = “SELECT age, firstname FROM table_sort where id=’$id_user’ “;
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$user_age = $row[‘age’];
$user_firstname= $row[‘firstname’];
echo “Firstname: “.$user_firstname.” | Age: “.$user_age.”<br/>”;
}
}

$end = microtime(true);
$elapsed_time = number_format($end – $start,4);

echo “Time took $elapsed_time seconds\n”;

Opening A Web page At A Specific Spot

You probably have noticed that you had seen a website load that did not start at the top. Instead, it started somewhere in the middle. When you link to a page, or post a form with PHP, you can always specify where you want the top of the page. The link or code to start a page at a specific spot looks like http://excample.com/#article_id. The code below shows a couple of samples of how the codes will look as a link and a form post field in PHP.

HTML Link
<a href=”http://example.com/#article_id”>Link Text Here</a>

PHP Form

<html><body>
<div style=””><form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’].”#article_id”;?>” name=”myform” >
<div style=”float:left; “><textarea style=”height:2000px; width:600px;” name=”article”>
Add text here.
</textarea></div>
<input type=”hidden” name=”hidden_name” value=”” />
<div style=”float:left; margin-top:20px; margin-left:10px;”>
<input name=”submit” style=”display:visible; width=”150″ type=”submit” value=”Add Post” height=”25″ border=”0″ alt=”Submit Form” /></div>
</form></div>
<div style=”clear:both;”></div>
<div id=”article_id”>Here is the text at the top.<br/>Here is the text at the top.<br/>Here is the text at the top.<br/>Here is the text at the top.<br/>Here is the text at the top.<br/>Here is the text at the top.<br/>Here is the text at the top.<br/></div>
</body></html>

PHP / MYSQL Updating Multiple Rows

Update is one of the main features for CRUD (Create, Read, Update and Delete). Normally, updating a database is performed on single entries or rows; such as users changing a profile or updating an address. However, using the for loop, you can update multiple records at once.

For example, you could have a list of players on a football team and you need to adjust their weights for a particular reason. The script below shows how all entries of a table can be output with editable input fields for each player. Upon submit, any adjustments to any row happens almost instantly.

<?php
include (‘myconnect.inc’);
$db=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”);

$i=0;
$count = count($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.
for ($i=0; $i < $count; $i++) {

$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) or die(mysqli_error($db));

} 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>


Using PHP Continue

PHP continue is a ‘control structure’ that belongs to a group with other control structures such as if, else, while, foreach and more. Its main use is to skip something. A popular place you may encounter ‘continue’ is within a loop. When it is used within a loops, it is used to ‘skip something’. The code belowe shows how it can be used to skip an item in an array.

$myarray = array(Pete,Sam,John);
foreach($myarray as $name) {
  if($name == Sam) {
    continue;
  }
  print $name.”<br/>”;
}

Output is:
Pete
John


PHP Download Multiple Files

Below is the code which grabs file names to download and passes those names into the url.

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<input type=”submit” name=”file1″ value=”file1.pdf”/>
<input type=”submit” name=”file2″ value =”file2.pdf”/>
<input type=”hidden” name=”getfile” value =””/>
</form>

<?php if($_POST[‘file1’]){
$filename=$_POST[‘file1’];
echo ‘<a href=”mydownload_multi.php?filename=’.$filename.'”><b>Download file!</b></a>’;
}
else if($_POST[‘file2’]){
$filename=$_POST[‘file2’];
echo ‘<a href=”mydownload_multi.php?filename=’.$filename.'”><b>Download file!</b></a>’;
}
?>

The code below is the actual file which makes it possible to download the selected download.

$myfilename=$_GET[‘filename’];
$filepath = $_SERVER[‘DOCUMENT_ROOT’].”/ABOOK/MISC/downloading/”.$myfilename;
//echo $_SERVER[‘DOCUMENT_ROOT’];
if (file_exists($filepath)) {
//download application
   header(“Content-Type: application/force-download”);
   //the filename will be given below
   header(“Content-Disposition:filename=\”$myfilename\””);
//open file in binary mode   
$my_file = fopen($filepath, ‘rb’);
//output data
   fpassthru($my_file);
//close file
   fclose($my_file);
}

PHP Download Script

With PHP, you can easily make a file accessible to download. PHP goes through a series of steps to make the downloading possible. The code below shows how PHP can find a file, make an application for it to download, name the new downloadable file, open the file, output the file data and close the data. 

To download a file,
1) Make a link to the download PHP page.
Code:
2) Add the code to the my_download.php page.
Code:
<a href=”mydownload.php”><b>Download file!</b></a>

$filepath = $_SERVER[‘DOCUMENT_ROOT’].”/downloads/my_downloadable_file.pdf”;
if (file_exists($filepath)) {
//download application
   header(“Content-Type: application/force-download”);
   //the filename will be given below
   header(“Content-Disposition:filename=\”my_downloadable_file.pdf\””);
//open file in binary mode   
$my_file = fopen($filepath, ‘rb’);
//output data
   fpassthru($my_file);
//close file
   fclose($my_file);
}

Get Maximum Value of Column with MYSQL with MAX() and ORDER BY

With mysql, you can use the MAX() function to get the highest value in a column. The column could have data like ages, auto incrementing ids or weights. If you want just the highest value, the max() function will output that value.

If you want a list of values starting with the highest number, you use the ‘ORDER BY’ condition in a mysql query to output the data based on what you want; such as highest value or most recent date. The example below explains how such data is sorted.

require_once(‘connect.inc’);
$db=public_db_connect();
$command = “SELECT MAX(id) as maxid FROM table_sort”;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)){
$myid = $row[‘maxid’];
echo “<br/>”;
$name = $row[‘firstname’];
echo “Here is the max id: “.$myid.”<hr>”;
}$command = “SELECT id, firstname FROM table_sort ORDER BY id desc”;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)){
$myid = $row[‘id’];
$name = $row[‘firstname’];
echo “My id is “.$myid.” and first name is “.$name.”<br/>”;
}

Using Hidden Post Variables From Database Queries and Loops

When you access data from a mysql table and use loops to output all rows of data, you can add forms inside each loop which can trap the row values for which they can be tranferred into form hidden fields? Sounds confusing? The code below will show how easy it is to do that.

<?php

if (ISSET($_POST[‘submit’])){
$my_id = $_POST[‘myid’];
$myname = $_POST[‘myname’];
echo “My id is “.$my_id.” and my name is “.$myname;
echo “<br/><br/><strong>What just happened?</strong><br/><br/>
We selected the entire rows from the database where the id is less than 3; which are ids 1 and 2. Since there are 2 ids 1 and 2, the loop create 2 results and hence 2 forms. Each result will show a submit button; since other input fields are hidden. Now, when submit is clicked, we could make any query do what we want since we could use the myname and myid post variables. <br/><br/>”;
}

require_once(‘connect.inc’);
$db=public_db_connect();
$command = “SELECT * FROM table_sort where id<3 “;
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)){
$myid = $row[‘id’];
$name = $row[‘firstname’];
?>
<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<input type=”hidden” name=”myid” value=”<?php echo $myid;?>” />
<input type=”hidden” name=”myname” value=”<?php echo $name; ?>” />
<input type=”submit” name=”submit” value=”Submit Form” />
</form>
<?php
}
?>


Submitting PHP Forms With URLs Containing Strings

When you submit forms with PHP, the URL may or may not contain query strings. URLS with query strings look like http://example.com/page.php?id=22&name=Betty. URLS with query strings can pose problems when you submit a form to itself. Below, shows typical code that is used to submit a form to itself and code which can be used with query strings in the url.

The code below would work fine if the url was simple and had no query string; such as example.com/page.php

Here is typical code to submit a form to itself:

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’];?>”>

The code below would work fine if the url had a query string; such as example.com/page.php?id=2

Here are 2 code samples which can be used to submit a form to itself where the url the query string shown above:

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’].”?”.$_SERVER[‘QUERY_STRING’];?>”>

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’].”?id=”.$id ;?>”>


MYSQL Explain

When you use EXPLAIN before a mysql query, you can gather details ablout a database table such as possible keys and rows. The data can be useful to determine how a table can be optimized. On the other hand, you can use PHPMYADMIN and analyze the structure and indexes. When you select a table and click structure, the indexes and table information is simple to analyze. The data can be crucial in the adjustment of the tables in order to make optimized queries.

To use explain,
1) Open PHPMYADMIN or mysql console.
2) Type:
explain select * from tablename;

PHP Validate Email Address

Back in the day, you could validate email with javascript, Jquery, and php using regex. Regex will check the input and make sure it is what the web developer wants to accept. Back in the day is still valid today. Regex is still a good option to validate input.

But,today in the day, a web developer can keep on top of new and recent other built-in PHP functions which do the same thing. One such function is one which validates email addresses.

The function will check the email row from the database and make sure it comes out like blahbalh@example.com. It will not output garbage like aaaaa.com or anything not resembling a real email address. It does not go all the way and check if the address exists, but the output still looks good on the screen.

below is an example of the PHP built-in function to validate email addresses.

$command = “SELECT email from email_list “;
$result=mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$email_address = $row[’email’];
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
echo ” “.$email_address.”; “;
}

Optimizing MYSQL Queries

Getting queries to work with mysql will help you gain confidence that you can select and output the data you had wanted. But, as time goes on and the demands to pull data with relational databases or the need to build applications with the need for speed is a factor, it will become obvious that output is only one factor while query optimization is another.

Fortunately, there are a few simple rules that can be followed to ensure you write better, optimized mysql queries. Three very important rules to use are; select only what you need, use indexes to match columns in various tables and matching columns should have the same structure.  

Select What You Need
Selecting what you need should be fairly obvious. For example, select  *  takes rows from all columns and selecting unused columns adds time to a query. If you just need to select and id from a column in a table that has id, firstname, lastname, email and so forth, you are better off to just select that id in the first place.

Using Indexes
Using indexes on columns which are used in relational queries can create results in a fraction of time, especially if there are hundreds or thousands of rows of data. If you do not use indexes when writing relational queries with 2-4 tables, you could wait, wait and wait for the page to load. We could be taking up to a minute in serious cases while same data using indexes loads in less than a few seconds. So, the next time you are using where statements to match colums on various tables, those matching columns should be indexed. You can add an index with mysql or phpmyadmin. 

To add an index with phpmyadmin,

1) Select the database table
2) Select Structure
3)Next to the desired column and under action, select ‘More’ next to the column
4) Click Add Index
5) You will see the list of indexes under the subheading indexes and it will include the newly made index on the column for which you made an index.

To add an index with the command line,

1) alter table `tablename` add index index_name (columnname);

Matching Columns

Finally, to keep speed as a priority, your columns structures should match. For example, if you have an indexed column  called members_id in one column and mymembers_id in another column that hold the same values to define a specific member, it is better to have them with proper structure and exact structure values; such as int(3). If you never plan to have more than 999 members, then int(3) would be about as good as it could get. If one column type was varchar(3) and the other type was int(3) the query would run slower; with all other things equal.


PHP, Apache and GD Library

PHP has quite an array of built-in functions which can be used to create, delete and manipulate images. Many image functions which need the GD library, such as getimagesize(), imagecreate(), imagedestroy(), imagetypes(), imagecreatetruecolor(), imagejpg() and getimagesize() can be found here:
http://www.php.net/manual/en/ref.image.php

However, in order to use these functions without generating errors, you need the GD library installed. It is likely to be available on shared hosting accounts, but, you may need to install and enable the module with a VPS or dedicated server.

Is the GD Library Installed?

If you attempt to use a function that is not part of the core PHP(like GD library) nd you have not loaded the

module for it, you will get an error like:

    Fatal error: Call to undefined function: imagecreate()

Adding the GD Library

Web Host Manager is a very popular Linux application that runs on CENTOS servers. One simple method to have GD library up and running is to follow the instructions given below.

1) Login to WHM(Web Host Manager)
2) Select Software -> EasyApache
3) Near step 5, click Exhaustive Options List which shows many more options
4) Scroll down under PHP and check GD >Build with new features


.HTACCESS Custom Rewrite Rules

When you use an .htaccess file within a root or other directory, you can set rules to write search engine friendly urls. For example, you may have a dynamic url like example.com/blog/id=100&title=mytitle. With a little work, you could make a rule so that an address in the browser such as example.com/blog/100-mytitle. When you make rewrite rules with htaccess, the original url and the new sef url will display the same content.

In order to make rules for htaccess usable, mod_rewrite must be installed and enabled on the server. It is often installed and enabled for shared hosting and can simply be enabled with a VPS or dedicated server.

HTACCESS RULES and CODE

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

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

What Does the above code do?

The above code gives you the option to take the url example.com/blog/id=100&title=mytitle and be able to use it as example.com/blog/100-mytitle.html

The key code is RewriteRule. All rules with the comment ‘#’ in front are inactive. The line that does the rewriting is:
RewriteRule ^(.*)-(.*).html$ blog/blog\.php?id=$1&title=$2 [NC]

Code Usage Example

Rewriting a url is one thing and is simple to use if we just link to the new sef url. However, if you have code that uses $_GET variables in the string you need to rewrite the php code so that it will point to the sef url. Here is an example of that.

Original code that will produce non-sef url like example.com/blog/id=100&title=mytitle

<div style=”font-size:18px; margin-left:5px; display:none;”><a href=”blog.php?id=<?php echo htmlentities(stripslashes($row[‘bookmark_id’])); ?>&title=<?php echo htmlentities(stripslashes($row[‘title’])); ?>”><?
   echo htmlentities(stripslashes($row[‘title’])).'</a></div>’;?>
  
New Code to rewrite SEF URLS that will make sef url like example.com/blog/100-mytitle.html
     <div style=”font-size:18px; margin-left:5px;”><a href=”<?php echo htmlentities(stripslashes($row[‘bookmark_id’])).”-“.htmlentities(stripslashes($row[‘title’])).”.html”; ?>”><?
   echo htmlentities(stripslashes($row[‘title’])).'</a></div>’;?>


Troubleshooting PHP Errors and Syntax

When using PHP, you will often need to troubleshoot scripts to find and fix errors. Two very popular methods for which to do so are to use echo statements and the die() function.

The echo statement will print out text so you can pinpoint what works and what does not. Echo statements can be used to troubleshoot an entire script or functions. Not only do echo statements help you find where problems exists, they can be very valuable to print out arrays and variables made from relational database queries. This can help find many sysntax problems and saves lots of troubleshooting time.  

The die() statement can be used with text. The die statement will stop the script and output the text inside its parenthesees.
Example:

Common trouble shooting techniques:

die(“If you are a non-member the script stops here!”);

print_r($myarray);

echo $row[‘name’];
echo “hello does this print?”;


HTACCESS Hiding Files

When you build applications, you may want to disallow some files from being opened. Such files you may want to hide are those with .inc and .sql extensions. You may want to hide those files since you do not them to be able to be read in a browser.

Although directories with index.php or index.html files will not allow someone to search for a directory list of files, someone could see the sensitive information if they tyled a url like http://example.com/databseconnect.inc. If databaseconnect.php was used, the data would not be visible.

The simple method to hide files using .htaccess is shown below.

Hide all files with inc extension:
<Files ~ “.inc”>
Order allow,deny
Deny from all
</Files>

Hide files with inc or sql extension:
<Files ~ \”\\.(inc|sql|…other_name_extensions…)$\”>
  order allow,deny
  deny from all
</Files>


How To Use PHPLIST

PHPLIST is an open source php script which allows you to send mass email and organize newsletters. Here are some quick tips to set it up and use it.

1) Download php list from phplist.com
2) Unzip file
3) Open php-list folder and public_html folder
4) FTP list folder to desired location
5) Create a new database
ie) database: mydb_phplist
username:mydb_phplist
password: my_passxyz
6) Alter .htaccess if necessary
7) Open both the front end and admin pages to load the database.
http://example.com/lists/ and http://example.com/lists/admin
8) Create a newsletter
Subcribe Pages >Add a new one >select Lists >Check Active >Save Changes
9) Test mesage:
Set TEST constant to false
Near line 192:
change:
define (“TEST”,1);
Change to:
define (“TEST”,0);
10) Go to a new browser and open the front end page>Sign up for a newsletter
11) Go to admin >Select Send a message

To create a list,
1) Select ‘Lists’ >Add a List >Add a List Name >Select ‘Check this box to make this list active (listed)’ >Add description if desired >Save
2) Go to Subscribe pages >Edit >Alter text areas, checkboxes and radio buttons as desired >Save Changes
Note:
When you add a second list and alter subscribe pages, you have the option to offer various mailing lists when the user decides to subscribe to a list.

With phplist you can custom placeholders into the message. This can help turn a generic message like Dear Sir into a personal message like ‘Dear Tom’. They placeholders can be found at http://docs.phplist.com/Placeholders

To add an attribute(such as first name),
1) Manage User >User attributes >Add a name >Save Changes
Note: The attributes will be saved in the table called phplist_user_attribute
Note: When you make an attribute like First Name in the name column of the phplist_user_attribute table, you can use a tag placeholder [FIRST NAME] in the email body to make the users name appear where you want.
Advanced Note: Whe you create a new attribute, it will up show when they sign up. The value for the attribute(ie. First name) goes into the table phplist_user_user_attribute. The userid in this table and id from the phplist_user_user table are matching keys. Whenever a new attribute is made, new people signing up will have the values and existing people on the list will have ‘NULL”. You can update the value if desired.

To enable an attribute at any time,
1) Select Subscribe Pages >Edit >Check the box in the attribute that says ‘Check this box to use this attribute in the page’.

To delete an attribute(such as first name),
1) Manage User >User attributes >Delete

To customize sign up page,
1) Select Subscribe Pages >Edit >Alter text areas, checkboxes and radio buttons as desired >Save Changes

What Happens when a user(with attributes) signs up for the newsletter?
1) The client receives a confirmation email.
2) The user`s id and email goes into the user table.
3) The name goes into the user_attribute table and matches the id from the user table.
Note: These 2 tables can be used to dump a large list. However, the user_attribute table does not have autoincrement for the userid. Therefore, careful dumping must take place for which the userids will match in both tables.

To dump an email list with a first name,
1) Change user_attribute table and make userid a primary key and autoincrement
2) The csv file should have the id from the attribute table in the first column (they will a be the same number), then a blank second column, then the value(i.e.first name) in the 3rd column.
It looks something like this for the entire list.
| 1 |  | Joe |
| 1 |  | Jan |
3) Dump complete list into the table. The table will now have attributeid, userid and value. Now, put the structure back to how it was by removing the autoincrement userid and the primary key.
4) Now go back the original csv file and import the users into the user table. The id will be autoincrement and should matck exactly as the userid from the dump into the user_attribute table. You must set the Excel spreadsheet to match the 16 columns. The first column will be blank since it is for autoincrement id, the second will be email address, the 3rd can be 0 or 1 for the confirmed column…etc.

After the import, check the last records to see that they got updated properly.


RESET QUERY CACHE MYSQL

If you have a query cache set up, you can restart the cache to start caching queries again.

mysql> RESET QUERY CACHE;

Flush MYSQL Cache

If you are using mysql_query_cache and you want to defragment the memory from time to time, you can flush the query cache.

mysql>FLUSH QUERY CACHE;

PHP OOP Abstract Classes

Abstact classes use the abstract keyword. It would start as shown below.
abstract class Myabstract{

You cannot instantiate an abstract class. Thus ‘$myclass = new Myabstract;’ does not work. Abstract classes use abstract methods.

Abstract classes are used when you want to make sure that each new child class uses its own method; even though the method exists in the parent class.

Abstract Method

An abstract method would be written like any other method except it contains ‘abstract’ at the beginning. When an abstract method is declared in the parent class, the child classes must their own function under the same name as declared in the parent class.

Example:

abstract class Myabstract{

abstract function get_var();
}

class childa extends Myabstract{

function get_var() {
echo “Hello World”;
}

}

$mychilda = new childa;
$mychilda->get_var();


How To Access Web Hosting PHPMYADMIN On Local WAMP Server

You can access PHPMYADMIN from your web hosting account using WAMP that is installed on your home PC.

Procedure:

1) Access phpmyadmin from wamp
2) Copy file C:\wamp\apps\phpmyadmin3.4.5(or your version) and rename it to something like phpmyadmin3.4.5-hosted
3) Open config.inc.php
Here is default configuration:

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg[‘Servers’][$i][‘verbose’] = ‘localhost’;
$cfg[‘Servers’][$i][‘host’] = ‘localhost’;
$cfg[‘Servers’][$i][‘port’] = ”;
$cfg[‘Servers’][$i][‘socket’] = ”;
$cfg[‘Servers’][$i][‘connect_type’] = ‘tcp’;
$cfg[‘Servers’][$i][‘extension’] = ‘mysqli’;
$cfg[‘Servers’][$i][‘auth_type’] = ‘config’;
$cfg[‘Servers’][$i][‘user’] = ‘root’;
$cfg[‘Servers’][$i][‘password’] = ”;
$cfg[‘Servers’][$i][‘AllowNoPassword’] = true;

/* End of servers configuration */

$cfg[‘DefaultLang’] = ‘en-utf-8’;
$cfg[‘ServerDefault’] = 1;
$cfg[‘UploadDir’] = ”;
$cfg[‘SaveDir’] = ”;

/* rajk – for blobstreaming */
$cfg[‘Servers’][$i][‘bs_garbage_threshold’] = 50;
$cfg[‘Servers’][$i][‘bs_repository_threshold’] = ’32M’;
$cfg[‘Servers’][$i][‘bs_temp_blob_timeout’] = 600;
$cfg[‘Servers’][$i][‘bs_temp_log_threshold’] = ’32M’;

4) Change these lines:
$cfg[‘Servers’][$i][‘host’] = ‘localhost’;
$cfg[‘Servers’][$i][‘user’] = ‘root’;
$cfg[‘Servers’][$i][‘password’] = ”;

The new code will look like:

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg[‘Servers’][$i][‘verbose’] = ‘localhost’;
$cfg[‘Servers’][$i][‘host’] = ‘127.0.0.0’; // change to actual ip address
$cfg[‘Servers’][$i][‘port’] = ”;
$cfg[‘Servers’][$i][‘socket’] = ”;
$cfg[‘Servers’][$i][‘connect_type’] = ‘tcp’;
$cfg[‘Servers’][$i][‘extension’] = ‘mysql’;
$cfg[‘Servers’][$i][‘auth_type’] = ‘config’;
$cfg[‘Servers’][$i][‘user’] = ‘myaccount_myuser’; //change this to the user
$cfg[‘Servers’][$i][‘password’] = ‘password_here’; // change this to the password
//$cfg[‘Servers’][$i][‘AllowNoPassword’] = true;

/* End of servers configuration */

$cfg[‘DefaultLang’] = ‘en-utf-8’;
$cfg[‘ServerDefault’] = 1;
$cfg[‘UploadDir’] = ”;
$cfg[‘SaveDir’] = ”;


PHP Return Array

With PHP, you can return a variable or an array from a function. The example below demonstrates how to return a simple array.

<?php
function people(){
    $myarray = array(‘jane’,’bob’,’mike’,’phil’);
    print_r($myarray);
    return $myarray;
}

//The function will make variable called $mytotal which can be returned from the function
$total = people();
echo “<br/><br/>”;

//$total is setting the variable equal to the function
//The value $mytotal is returned and is printed below
echo “The array are the people $total[0], $total[1], $total[2] and $total[3].”;
?>


PHP Returing Variables OOP vs Procedural PHP

Returning variables from PHP OOP is slightly different from that of returning variables with procedural PHP.

With procedural PHP, the function can return a single variable, but it is accessed by setting a function equal to a variable.

With OOP PHP, you can call a method and return your desired variable. The variable returned from an OOP PHP function is output immediately.

An easy way to remember this is that returned variables with procedural need to come from a variable that is equal to a function and OOP PHP just returns it without any questions asked.


Delete All Entries From MYSQL Database Table With Truncate

Database tables can load up quickly with data. As data becomes obsolete you may want to remove all entries from a table. The command below explains how to remove all entries within a mysql table.

TRUNCATE TABLE tablename;

Return Variables With PHP

With PHP, you can return one variable or an array from a function. The example below explains how to retun a single variable.

function add_numbers($number_one,$number_two){
    $mytotal = $number_one + $number_two;
    echo $mytotal;
    return $mytotal;
}

$num1 = “1”;
$num2 = “2”;

//The function will make variable called $mytotal which can be returned from the function
$total = add_numbers($num1,$num2);
echo “<br/><br/>”;

//$total is setting the variable equal to the function
//The value $mytotal is returned and is printed below
echo “The total $total is returned from the function which can only return a single variable or array. In this case, the function returns a variable.”;


Global Variables

Global variables are variables which are defined outside of a function, but are redecalred inside the function with a global keyword. The code below shows how $var1 uses the global keyword. When you use the global keyword, the variable takes on its original value. In this case, using global $var1 inside a function makes $var1 equal to the string “Hello”.

$var1 = “Hello”;
$var2 = “World”;
$var3 = “Variable 3 is outside function”;

function myglobal_vars() {
global $var1; //$var1 has global scope
$var3 = “Hi this is var3 inside the function.”;

echo $var1.” “.$var2.” from inside the function”; //$var2 has no global scope and will not output
echo “<br/><br/>”;
echo $var3;
echo “<br/><br/><hr>”;
}

myglobal_vars();
echo “Only variable “.$var1.” can be used inside and outside the function.”;

echo “<br/><br/>”.$var3; //different output than inside the function

PHPLIST is an open source mass mailer built with php / mySQL. Here are some quick start setup tips to get the software running as desired.

1) Download php list from phplist.com
2) Unzip file
3) Open php-list folder and public_html folder
4) FTP list folder to desired location
5) Create a new database
ie) database: mydb_phplist
username:mydb_phplist
password: my_passxyz
6) Alter .htaccess if necessary
7) Open both the front end and admin pages to load the database.
http://example.com/lists/ and http://example.com/lists/admin
8) Create a newsletter
Subcribe Pages >Add a new one >select Lists >Check Active >Save Changes
9) Test mesage:
Set TEST constant to false
Near line 192:
change:
define (“TEST”,1);
Change to:
define (“TEST”,0);
10) Go to a new browser and open the front end page>Sign up for a newsletter
11) Go to admin >Select Send a message

Naming OOP PHP Properties

PHP OOP properties can be named inside or outside the class. When you create an object, it gets the property name from within the class. Howvere, when you rename an object ouside the class, it will override the previous name for that property.

The code below shows 2 new instantiated objects;
$statement1 = new myclass;
$statement2 = new myclass;

Note how the text for the property name from each object is different from each other when the get_my_method() method is triggered?

class myclass {
public $my_prop = “Randy”;

function my_method(){
echo “My property name is “.$this->my_prop.” and my function is my_method()<br/><br/>”;
}

function get_my_method() {
return $this->my_method();
}
}

$statement1 = new myclass;
$statement1->get_my_method();

$statement2 = new myclass;
$statement2->my_prop = “Roger”;
$statement2->get_my_method();


PHP OOP $this->

<?php
class this {
public $myproperty = “Randy”;

function mymethod(){
echo “My property is “.$this->myproperty.” and my function is mymethod()<br/><br/>”;
}

function get_mymethod() {
return $this->mymethod();
}
}

$my_statement = new this;
$my_statement->get_mymethod();

$my_second_statement = new this;
$my_second_statement->myproperty = “Roger”;
$my_second_statement->get_mymethod();
?>

More Advanced Note:
Generally, $this-> is always used to reference methods within a class. You cannot name an oblect $this without getting an error.

Error Example:
You make a new object with the name $this = new myobject;

$this = new myobject;
$this->get_mymethod();  
$this->myproperty = ”Bill”;

Output:
Fatal error: Cannot re-assign $this in C:\wamp\www\ABOOK\OOP\MY_OOP\this.php on line 17


PHP Change CSS Stylesheet Based On Time Of Day

<?php
date_default_timezone_set(‘America/Los_Angeles’);
$time = date(‘H’);

if($time >= 00 AND $time <= 12){
//am
$my_style = ‘style.css’;
}

else if($time > 12 AND $time <= 24){
//pm
$my_style = ‘style_night.css’;
}
?>
<link rel=”stylesheet” type=”text/css” href=”<?php echo $my_style; ?>” />

Adding a Variable Inside Array

With an array, you can use a variable to represent the value. The example below demonstrates a situation where a variable is used to display the days in the month.

$thirty_one = “Thirty one days in the month”;
$thirty = “Thirty days in the month”;
//$twenty_eight = “Twenty eight days in the month”;

$values=array(
        ”Jan” => $thirty_one,
        ”Feb” => 28,
        ”Mar” => $thirty_one,
        ”Apr” => $thirty,
        ”May” => $thirty_one,
        ”Jun” => $thirty,
        ”Jul” => $thirty_one,
        ”Aug” => $thirty_one,
        ”Sep” => $thirty,
        ”Oct” => $thirty_one,
        ”Nov” => $thirty,
        ”Dec” => $thirty_one
    );

Adding @ To PHP Functions

Life as a php programmer will raise all sorts of eyebrows as you sift through other people’s code. The ‘@” simple can be one of those small quirks. For  example, you may find a function like @mysqli_query() when you expect mysqli_query. The @ sign can be used in front of a functions (and expressions) to suppress errors. The errors will be ignored.


PHP Multidemensional Arrays

Multidemensional arrays are arrays of arrays. Multidemensional arrays will be indexed, but the arrays they index can be indexed or associative arrays. The example below consists of two associative arrays. You access the first array with the 0 index; such as $my_array[0]. To access an associative array value you need to choose the key. For example, $my_array[0][Email] selects the email value of the first array.

echo “<br/><br/>”;
$my_array = array(array( ‘Firstname’ => ‘Joe’,
                  ‘Lastname’  => ‘Rogers’,
                  ‘Email’     =>’joe@example.com’),
                  array(‘Firstname’ => ‘James’,
                  ‘Lastname’  => ‘Rogers’,
                  ‘Email’     =>’james@example.com’));

//print_r($my_array);

echo $my_array[0][Firstname].” “.$my_array[0][Lastname];

echo “<br/><br/>”;

echo $my_array[1][Firstname].” “.$my_array[1][Lastname];


PHP Associative Arrays

Associative arrays have a key and a value. For example, the array below consists of the keys firstname, alstname and email while the values are Joe, Rogers and jo@example.com.

$my_array = array();
$my_array[‘firstname’] = ‘Joe’;
$my_array[‘lastname’]  = “Rogers” ;
$my_array[’email’] = ‘joe@example.com’;

echo $my_array[‘firstname’].” “.$my_array[‘lastname’];


PHP Indexed Arrays

Indexed arrays are ordered by a numerical index. For example, the first value in the array is 0 and the second number is 1.

echo “<br/><br/>”;
$my_array = array(‘Joe’,’Rogers’,’joe@example.com’);

echo $my_array[0].” “.$my_array[1];

echo “<br/><br/>”;

PHP CRUD

WHAT IS CRUD?
CRUD stands for create, read, update and delete.  Each term is very self-explanatory.

Create
The word create inserts fresh data into a database; hence the word create.

Read
The term read refers to reading data from a database. No data in the database is altered in any way. However, you can output the data any way you see fit.

Note: when you work with filrs from other programmers you may find code is written, you may find variables, arrays and other programming methodologies varied from your own. Often, the code looks more confusing but it does the same thing.

Below is an example of extracting data from the database. The data shown represents all first names in the chosen database table.

// Obscure
$command = “select * from table_sort ORDER BY date DESC”;
$result = mysqli_query($db. $command);
if(mysqli_num_rows($result) != 0){
while($row = mysqli_fetch_assoc($result)){
$var1[$row[‘first’]] = $row[‘firstname’];
$var2[$row[‘first’]] =  $row[‘lastname’];

echo $var1[$row[‘first’]];

}
}

echo “<br/><br/>Simple:<br/><br/>”;
//Simple
$command = “select * from table_sort ORDER BY date DESC”;
$result = mysqli_query($db, $command);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$var1 = $row[‘firstname’];
$var2 =  $row[‘lastname’];

echo $var1;

}
}

Update
Update takes place when you alter data which already exists. For example, you may change a blog entry and thus it gets updated.

Delete
The delete term represents the removal of specific row(s) of data from a database. For example, you may want to delete an old blog entry.


PHP Foreach Loop

Examples using the foreach loop with PHP.

Loop Syntax #1

$items = array(‘one’, ‘two’, ‘three’, ‘four’);
foreach ($items as $item) {
echo $item.”<br/>”;
}

Loop Syntax #2

$items = array(‘First’ => ‘one’, ‘Second’ =>’two’, ‘Third’ =>’three’, ‘Fourth’ =>’four’);
//This outputs the values
foreach ($items as $item) {
echo $item.”<br/>”;
}

PHP For Loop

Examples using the for loop with PHP.

Loop Syntax #1

for($i=1; $i < 5; $i++) {
echo $i.”<br/>”;
}

Loop Syntax #2

for($myvar=1; $myvar < 5; $myvar++) {
echo $myvar.”<br/>”;
}

PHP While Loop

Examples using the while loop with PHP.

Loop Syntax #1

$i = 1;
while($i < 5) {
echo $i.”<br/>”;
$i++;
}

Loop Syntax #2

$myvar = 1;
while($myvar < 5) {
echo $myvar.”<br/>”;
$myvar++;
}

Constants in PHP

Using Constants in php can cut down a programmer’s time and keep organized code handy since one word can be used to represent an integer or string. The define() function is used to name a constant and and create a value for the constant.

The code below whows how to create two constants and output the constants’ values in an echo statement.

define(‘MYCONSTANT’, “My constant text string can have”);

define(‘MY_SECOND_CONSTANT’, ‘ double or single quotes.’);

echo MYCONSTANT.MY_SECOND_CONSTANT;

Resetting MYSQL Database Tables Upon User Login

There could come a time when you want to allow people to login and test an application. Then, you may want the application to go back to an original state. One such method to accomplish this is to drop the database tables which change. Then, create and copy backup tables into the changeable tables. Now, each new user gets a fresh look at the website upon login.

The if statement below checks to see if the session exists. If it does, the tables are dropped and are recreated with new content.

if ($_SESSION[‘SESS_id_123’]) {
$command = “DROP table tablename” ;
$result = mysqli_query($db, $command);
$command = “CREATE TABLE tablename SELECT * FROM tablename_backup “;
$result = mysqli_query($db, $command);

$command = “DROP table tablename_footer” ;
$result = mysqli_query($db, $command);
$command = “CREATE TABLE tablename_footer SELECT * FROM tablename_footer_backup “;
$result = mysqli_query($db, $command);

$command = “DROP table tablename_header” ;
$result = mysqli_query($db, $command);
$command = “CREATE TABLE tablename_header SELECT * FROM tablename_header_backup “;
$result = mysqli_query($db, $command);
}


How To Learn PHP

Overview
Since PHP is the most popular server side programming language on the Internet, many people desire to learn it. When PHP emerged, it allowed programmers to create php files for which you could combine various languages(PHP, HTML, CSS,  Javascript) into one file.  This was very convenient for a web designer or developer. Since PHP is mainly used to output HTML / CSS, it is recommended to have a decent knowledge of these languages since you will actually work with various codes in one swoop. With editors like Notepad++ which highlight various languages like HTML and PHP, it easy to see detect what code is what. People with web design skills but little PHP knowledge should be able to see the difference. If not, they should be able to determine the difference in 2 minutes. When a PHP programmer works with HTML, HTML can be located inside or outside the PHP tags. Code outside of tags is just plain old HTML while code inside quotations gets parsed by PHP on the server.  If single quotes are used, the HTML will look just as it would in plain old HTML. But, if the programmer uses double quotes, the double quotes in the HTML use backslashes.

Since PHP is mainly used to output HTML, the whole skillset is a bonus. Often, a team has members which have varied strengths. But, none should be totally  lost when looking at the code. A designer should know where to edit his html and the web developer should have a grip on everything he sees.

First Steps
PHP code exists between a starting and ending tag. The staring tag is <?php and the ending tag is ?>. Create a file called first.php and write the code below into the file. Then, save it and open it in a browser.

<?php
echo “PHP is fun!”;

echo ‘<br/>’;

 echo ‘Isn’t it?’;
?>

//Yields:
PHP is fun!
Isn’t it?

The codes below show how to create a link.  

Single Quotes
<?php
echo ‘<a href =”myfile.php”>Click Here</a>’;  
?>
//Yields :
Click Here

Double Quotes
<?php
echo “<a href =\”myfile.php”>Click Here</a>\”;  
?>
//Yields: Click Here


Open Source CMS vs Custom Programming PHP/ MYSQL

Custom Programming vs Open Source CMS

When you use need to create an application you can be faced with a decision to use an open source cms like Joomla, WordPress or Drupal, or build it from scratch. The answer is not very cut and dry. It depends upon your objectives. If you are very familiar with a cms, you may hear a client’s needs then know an open source cms could make the application in a heartbeat.  Since your read on the client was little or no changes, it could be the obvious choice. In addition to the scratch or open source cms argument,  you could always look for custom php/mysql scripts to do the job. Generally, the pure language coding is much better performance than an open source cms, and possibly easier to edit and update. A quick trial and a quick look at the code could let you know what you are in for. If you know procedural php/mySQL and can understand PHP OOP you will not have surprises.

However, if quality is a concern and specialization could be ongoing, a custom script could be the best bet. Using a language like PHP / mySQL in its pure form is always more flexible to use and build than creating a custom open source extension. For example, when I look at all the files assembled to make a custom form with a Joomla extension, it blows me away how distorted the system is when it could have been done in a couple of hours using a single file. If you can custom program and build CRUD applications by memory just by reading database tables and writing code, you are no faced with a no-brainer decision.

Beware: Look Good and Grow With Open Source CMS

When you use an open source cms for a development, you can often bridge the gap between your actual skill level and how you look on the web. It can allow a non-programmer to sell developments but not understand what the coding does. Although assembling can be easier, editing the code is another story. If you really want to follow the CMS into a new level, you will need to become familiar with its own libraries and file structures. Alternatively, you can always make custom applications using the cms database tables but not use the actual cms files. Here is where you can have the best of both worlds.

The problem in using an open source cms is that the coding is not as flexible as building an application in the PHP / mySQL language. For example, if you have strong php / mySQL skills, a solid login system, know how to handle data from the database, can create forms quickly and understand sessions inside and out, you can make data and imagery do whatever you want with much faster and leaner code.  In other words, if you really want to change the code around to accommodate a client, changing an open source cms extension could be long drawn out nightmare opposed to using 1 lean file which could be edited before you even know which files you need to edit.

PHP OOP Return String Based on Input

Here is an OOP PHP sample which inputs the age of each entry and returns a custom string based on the age of each person.

<?php

class age_level {

public $score;
public $course;

public function __construct($age_input) {

$this->score = $age_input;
}

public function convert_age(){
//set property values equal to strings based on age
if ($this->score>=’1′ && $this->score<=’12’) {

$this->course = “Kid”;
return $this->course;

}

elseif ($this->score>=’13’ && $this->score<=’19’) {

$this->course = “Teen”;
return $this->course;

}

else if ($this->score>=’20’ && $this->score<=’29’){

$this->course = “Twenties”;
return $this->course;

}

else if ($this->score>=’30’ && $this->score<=’39’){

$this->course = “Thirties”;
return $this->course;

}

else if ($this->score>=’40’ && $this->score<=’49’){

$this->course = “Forties”;
return $this->course;

}

else if ($this->score>=’50’ && $this->score<=’59’){

$this->course = “Fifties”;
return $this->course;

}

else if ($this->score>=’60’ && $this->score<=’69’){

$this->course = “Sixties”;
return $this->course;

}

else if ($this->score>=’70’ && $this->score<=’79’){

$this->course = “Seventies”;
return $this->course;

}

else if ($this->score>=’80’ && $this->score<=’100′){

$this->course = “Senior”;
return $this->course;

}

}

}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html class=”gecko win” lang=”en-gb” xml:lang=”en-gb” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
</head>
<body>

<div id=”scores”>
<?php
echo “<b>Users</b><br/><br/>”;
?>
<ul style=”margin:0px; padding:0px;”>
<?php
//include (‘class_program_level.php’);
$command = “select * from table_sort ORDER BY date DESC”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$age_input=$row[‘age’];
$myage = new age_level($age_input);
$bg =($bg==’#A7C6BA’ ? ‘#f9f9f9’ : ‘#A7C6BA’);
echo “<li style=\”padding:0px 10px 10px 10px;background: $bg;\”><span style=\”font-size:18px;display:none;\”><b>”.$row[“firstname”].”</b></span><br/><b>First Name:</b> “.$row[“firstname”].”<br/><b>Last Name:</b> “.$row[“lastname”].”<br/><b>Email:</b> “.$row[“email”].”<br/><b>Height:</b> “.$row[“height”].”<br/><b>Age:</b> “.$row[“age”].”<br/><b>Weight:</b> “.$row[“weight”].”<br/><b>Age Category:</b> “.$myage->convert_age().  “</li>”;
}

}
?>
</ul></div>

<div style=”clear:both;”></div>

</body>
</html>


PHP OOP Child Classes

Child classes belong to the parent class but can be customized. Child classes can have separate properties and methods and inherit those from the parent class. The example below shows how to write a parent class and a child class in a single file.

class my_class {
}
class my_new_class extends my_class {
}

PHP OOP Classes

PHP OOP uses classes. The classes store the properties (similar to variables in procedural PHP) and methods similar to functions in procedural PHP). When you use classes, it does matter where you put them (from a functional point of view).

For example, you can create a class and insert it into your PHP for which you want to access the class. In fact, you could stack as many classes as you want in a file. But, many other applications that use PHP OOP tend to separate the classes in files with file names which are easy to identify.

For example, the class myclass could be used in a fiule called myclass.php. If classes are kept in individual files, it is easier to find and use them later in other pages for which you want to reuse the class.

Often, if you use various third party PHP scripts you may find some programmers have disorder, some keep all classes in separate files and some keep all parent and descendant classes in a single file.

class my_class {
}

With PHP OOP, you can declare properties and methods to be public, private and protected. Depending on the circumstances, you will have the option to choose the ideal method for which to control properties and functions. All methods and properties can be defined within their class.

Public
Public properties or methods can be accessed anywhere in various classes

Public variables:

public $variable;
public $variable2;

Public function:
public function myfunction(){
}

Private
Private Private properties and methods can be accessed only in the class where it is declared. They cannot be accessed by parent or children classes.

Private variables:
private $variable;
private $variable2;

Protected
Protected properties and methods can be accessed in the class where it is declared and child classes.

Protected variables:
protected $variable;
protected $variable2;

Stripping HTML Tags From Database Output

When you output data from a mysql database, the text could be html code with various tags such as <p>, <div> and span. Therefore, if you just selected the text for output you could end up with undesired output.

Now, let’s assume that you want to convert the html into plain text just as though it was interpreted from a browser. What you need to do is remove the whitespace and html tags and display the words you want to see. With PHP you can use the clever strip_tags() function to remove the html tags and use the trim() function to remove whitespace. The code below shows how to remove all html tags from a database entry.

$command = “select text from mytable “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc) {
$myhtml = $row[‘text’];
$myhtml= substr($myhtml, 0, 100);
$myhtml = strip_tags($myhtml, ”);//strips all tags

echo ‘<p>’.$row[text].'<br /><br/>
</p>’;

}

The code below shows how to remove all html tags from a database entry except the <p> tag.

$command = “select text from mytable “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc) {
$myhtml = $row[‘text’];
$myhtml = trim(strip_tags($myhtml, ‘<p>’)); //Leaves the <p> tag but removes all other html tags
$myhtml= substr($myhtml, 0, 80); //takes only the first 80 characters of the string

echo ‘<p>’.$row[text].'<br /><br/>
</p>’;
}


OOP Programming in PHP

Depending on one’s background and learning methods, a PHP programmer is often lead to examine Procedural PHP vs OOP in PHP.

For the serious individual who want to program in PHP, learning both methods opens much more doors. Even if you never code in OOP, knowing how to read it will allow you to see what is going on in other people’s code. Chances are if you use large open source OOP in PHP you will want to edit or redo blocks of code. If you don’t know OOP and you open an application written in OOP, you will be lost. But, with a little practice and education, you can familiarize yourself with some OOP concepts like inheritance, polymorphism, instantiating objects, classes, methods, properties, constructors, objects, magic methods and encapsulation. If you don`t want to use OOP, it is recommended to avoid software which uses it. nevertheless, OOP can be found in CMS` like Joomla and PHP Frameworks like Zend and Codeigniter.

OOP uses properties, classes and methods. Properties are like variables and methods are like functions. which are variables and functions in whereas PHP functions can pass absolute parameters(like defined variables and strings), methods(functions in OOP) can take in parameters which can confuse a procedural PHP programmer. In a nutshell, classes have their own ways of doing things.

PHP Built In Functions

Here is a list of common PHP fuinctions and their usage.

Execute a mysql query
mysqli_query()

Connect To MYSQL Database
mysqli_connect()

Fetch arrays from Database Using a Select
mysqli_fetch_assoc()
mysqli_fetch_array()

Fetch Object from Database Using a Select Query
mysqli_fetch_object()

Get the number of rows from a query
mysqli_num_rows()

The two functions add slashes to special characters when inserting data into a database. “Never trust the data being inserted’.
addslashes()
mysqli_real_escape_string()


PHP Language Constructs

PHP has many built-in language constructs and functions. Language constructs can be used with or without parentheses while functions always have parentheses. Here is an example using a language construct. With brackets: require_once(‘filename.php’) Without Brackets: require_once ‘filename.php’

Here is a list of several PHP constructs which will be used quite frequently in even the simplest PHP / mySQL applications.

Printing strings and variables
echo()
print()

Unsetting a session variable
unset()

Check is a variable is set
isset()

Check if post variable is empty
empty()

Check if post variable is not empty
!empty

Include files:
include()
include_once()
require()
require_once()

End the php script
die() or die


Remove Unique Index With PHPMYADMIN

To remove unique index of a column,

1) Open PHPMYADMIN
2) Select database >database table >Structure >(Select from option a or b below)
3) Look for Indexes Table which is below the main table.
4) Change or remove the unique index


Unique MYSQL Columns With PHPMYADMIN

Alter a table to create unique columns. This will ensure there is no duplicate values in a column that is unique.

1) Open PHPMYADMIN
2) Select database >database table >Structure >(Select from option a or b below)
a) Look for Arrow next to More or U icon >Add Unique Index
b) Look for index >Click Edit next to desired field >Next to index type select Unique

Unique MYSQL Table Creation

Create a Table where only there is no duplicate firstname / lastname combinations

CREATE TABLE members
(
lastname varchar(30) NOT NULL,
firstname varchar(30) NOT NULL,
UNIQUE (lastname, firstname)
);

Unique MYSQL Table Creation

Create a Table where only there is no duplicate firstname / lastname combinations

CREATE TABLE members
(
lastname varchar(30) NOT NULL,
firstname varchar(30) NOT NULL,
UNIQUE (lastname, firstname)
);

MYSQL Add a Unique Column

The code below creates a new column called username to the table called mytable. The username must be unique. In other words, if you use an insert statement and a username already exists, the data will no be duplicated.

alter table mytable add unique (username);
ALTER TABLE `mytable` ADD UNIQUE (`username`)”;

Search A Single MYSQL Database Table For a Specific String

1) Open phpmyadmin
2) Select Database >Select Table
3) Select Search 
4) Insert Words into Desired Text Input Field
5) Refine Search with phpmyadmin operator LIKE or %like%
6) Select Go

Search All MYSQL Database Tables For a Word or Specific String

1) Open phpmyadmin
2) Select Database
3) Select Search
4) Insert Words into Text Input
5) Select Go               

Count Distinct Rows From MYSQL Table

Method A

$command= “SELECT count(distinct username) as allusername from tablename “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$myusername = $row[‘allusername’];
}
}

echo “The distinct count of usernames is “.$myusername.”<br/>”;

Method B

$command= “SELECT distinct username from tablename ORDER BY date asc “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
$myusernames= mysqli_num_rows($result);
echo “The distinct count of usernames is “.$myusernames.”<br/>”;
}

MYSQL NUM ROWS

Counting Rows with mysqli_num_rows function can provide useful pieces of data. The following example demonstrates how to gather gather distinct first names in a table sorted by date.

$names = “select distinct firstname from table_sort WHERE date<=’2012-01-27′ “;
$result= mysqli_query($db, $names);
$name_count = mysqli_num_rows($result);
echo “There are “.$name_count.” rows.<br/><br/>”;

$names2 = “select DISTINCT firstname from table_sort WHERE date>=’2012-01-01′ “;
$result= mysqli_query($db, $names2);
$name_count2 = mysqli_num_rows($result);
echo “There are “.$name_count2.” rows.<br/><br/>”;

$myvalues=array(“After_2011” => $name_count, “Before_2011” => $name_count2);

echo “There are “.count($myvalues).” values in the array.<br/><br/>
There are “.($name_count+$name_count2).” rows in total.”;


Selecting Entries With Blank Columns in MYSQL

Objective: Select all rows in a table for which there are blank values. You may want to see the values before you delete all the entries with a specified blank column.

To select entries with an empty column,
1) SELECT * FROM tablename WHERE column_name=”;

Update MYSQL Passwords

UPDATE PASSWORDS WITH MYSQL

Using mysql password function
update tablename  set password=password(‘mypass’) where id=9;

Update MD5 Passwords
update tablename  set password=md5(‘mypass’) where id=9;

Update sha1 Passwords
update tablename  set password=sha1(‘mypass’) where id=9;

Installing Sitemakin CMS

To load Sitemakin CMS into a subfolder on a website,
1)Upload folder to the desired location (i.e. example.com/test)
2) create database
3) Import data to database
4) Change database connection in the files public.php and utilities.php
5) If you use your main domain (i.e. example.com), you can login, create, edit, delete pages immediately!

Otherwise, for subfolders please follow the next set of instructions!

6) Open file page_template_no_header_no_footer.php
Near line 21:
change lines 21 and 22
i.e)
CHANGE FROM:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/’, ”, $domain);

CHANGE TO:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/test/’, ”, $domain);

7) Open file page_template_ckc.php
Near line 21:
change lines 21 and 22
i.e)
CHANGE FROM:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/’, ”, $domain);
CHANGE TO:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/test/’, ”, $domain);

7) Open file page_template.php
Near line 21:
change lines 21 and 22
i.e)
CHANGE FROM:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/’, ”, $domain);
CHANGE TO:
$domain = strstr($url, ‘example’);
$cms_page_url= str_replace(‘example.ca/test/’, ”, $domain);


Using Distinct For Output

Using distince in a query will output distince values for a chosen query.
For example, look at the following query:
“SELECT DISTINCT name from tablename;”

If there are two exact names in the names column, the query will output the second name. Who cares, right? But what of the query wanted distinct name and email like the query below:
“SELECT DISTINCT name, email from tablename;”

The result will retrieve rows with distinct name and email combinations which can be output in a table or list.

Note:
If the data in the list was submitted from a form, and some users had submitted the same email and name more than once, you will not see all entries for a distinct user. You will only see the earliest entry of a specific name / email combination.


Replace String in PHP With str_replace Function

Replacing Parts of String With str_replace Function

$string = “I like to eat.”;
echo $string; //
Output is:
I like to eat

$string = str_replace(“eat”,”drink juice”, $string);
echo $string;
New output is:
I like to drink juice.


Delete Rows From MYSQL Table

Using PHPMYADMIN
1) Select desired database.
2) Open SQL Tab in PHPMYADMIN

Using MYSQL Console
1) Open MYSQL Console (mysql>)
2) Type command:
delete FROM `test’ where id >’0′;


MYSQL Count Columns

To count all columns of a mysql database table,

1) Open PHPMYADMIN
2) Select ‘SQL’ tab.
3) Type Command:
  SELECT count(*) FROM information_schema.`COLUMNS` C
  WHERE table_name = ‘mytable’;


MYSQL Count Entries

To count all rows of a mysql database table,

1) Open PHPMYADMIN
2) Select ‘SQL’ tab.
3) Type Command:
SELECT COUNT(*) FROM tablename;


Excel Spreadsheet To MYSQL Database

Here is the basics you need to know about Excel spreadsheets in order to make, edit or move the data into a mysql database.

EXCEL Necessities for MYSQL LOAD CSV
   
Here is Just about everything you need to know about excel files if you use wamp or phpmyadmin.
 
To make an entire column with an identical value (ie. 1),
1) Click on top row.
2) Add text in first row
3) Place cursor over bottom right corner of the first cell (a small black x will appear).
4) Drag to bottom of last row. Now all columns have same value

make csv from excel comma delimited format

To add a column
with Excel,
1) Right click on a letter >Select Insert
Note:It will insert before selected column

To delete a column in Excel,
1) Right click on a letter >Select Delete

To copy text with Excel,
Right Click on cell >Copy >Paste in phpmyadmin or wherever you want

Dumping Excel CSV File Into PHP MYADMIN with autoincrement fields.
1) With php myadmin, remove id auto increment field.
2) Load data from csv.
3) Add new auto_increment field after the new rows are updated.


Populate MYSQL Database

Intention: To populate a mysql database table very quickly by copying existing rows and adding them to the existing rows.

To populate a table quickly for testing purposes,
1) open phpmyadmin
2) Select export(but do not make a file) >go
3) Copy the insert into statement.
4) Open desired table
5) SElect SQL
6) Paste Insert into statement into the text area >Alter entries if desired (especially any auto increment field) >go

List MYSQL Database Entries By Specific Day

With the following form we are trying to filter the results from an exact day. Since the date in the database uses the typical date format 2012-01-13, we can grab the date, month and day post variable and get results for that day.

This example uses a table to output data.

<?php
if (count($_POST) > 0) {
$my_date=$_POST[‘date’].’-‘.$_POST[‘month’].’-‘.$_POST[‘day’];
} ?>

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<select name=”date”>
<option value=”2012″>2012</option>
<option value=”2011″>2011</option>
<option value=”2010″>2010</option>
</select>

<select name=”month”>
<option value=”01″>January</option>
<option value=”02″>February</option>
<option value=”03″>March</option>
<option value=”04″>April</option>
<option value=”05″>May</option>
<option value=”06″>June</option>
<option value=”07″>July</option>
<option value=”08″>August</option>
<option value=”09″>September</option>
<option value=”10″>October</option>
<option value=”11″>November</option>
<option value=”12″>December</option>
</select>

<select name=”day”>
<option value=”01″>1</option>
<option value=”02″>2</option>
<option value=”03″>3</option>
<option value=”04″>4</option>
<option value=”05″>5</option>
<option value=”06″>6</option>
<option value=”07″>7</option>
<option value=”08″>8</option>
<option value=”09″>9</option>
<option value=”10″>10</option>
<option value=”11″>11</option>
<option value=”12″>12</option>
<option value=”13″>13</option>
<option value=”14″>14</option>
<option value=”15″>15</option>
<option value=”16″>16</option>
<option value=”17″>17</option>
<option value=”18″>18</option>
<option value=”19″>19</option>
<option value=”20″>20</option>
<option value=”21″>21</option>
<option value=”22″>22</option>
<option value=”23″>23</option>
<option value=”24″>24</option>
<option value=”25″>25</option>
<option value=”26″>26</option>
<option value=”27″>27</option>
<option value=”28″>28</option>
<option value=”29″>29</option>
<option value=”30″>30</option>
<option value=”31″>31</option>
</select>
<input type=”submit” name=”submit” value=”submit” /></form>
<div>

<?php
echo ‘<table align=”center” cellspacing=”0″ cellpadding=”5″>
<tr>
<td align=”left”><b># Entries</b></td>
<td align=”left”><b>Name</b></td>
<td align=”left”><b>Username</b></td>
<td align=”left”><b>Email</b></td>
<td align=”left”><b>Phone Number</b></td>
<td align=”left”><b>Date</b></td>

</tr>’;
$command= “SELECT member_id, name, username, email_address, phone_number, date FROM tablename WHERE date=’$my_date’ ORDER BY date desc”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
$number = 0;
while ($row = mysqli_fetch_assoc($result)) {
$number = $number + 1;

$bg =($bg==’#DCEDE5′ ? ‘#f9f9f9’ : ‘#DCEDE5’);
echo ‘<tr bgcolor=”‘ . $bg . ‘”>
<td align=”left”>’ .$number. ‘</td>
<td align=”left”>’ .$row[“name”]. ‘</td>
<td align=”left”>’ .$row[“username”]. ‘</td>
<td align=”left”>’ .$row[“email_address”]. ‘</td>
<td align=”left”>’ .$row[“phone_number”]. ‘</td>
<td align=”left”>’ .$row[“date”]. ‘</td>
</tr>’;
}
echo ‘</table>’;
}
?></div>

Searching MYSQL Database Entries By Timeframe

With the following form we are trying to filter the results from a period of 1 month. Since the date in the database uses the typical date format 2012-01-13, we can grab the date and month post variable and append the first date of the month and last date of the month. The last date 31 would work for any month because the last 2 digits of the date never exceed 31.

This example uses a table to output data.

<?php

if (count($_POST) > 0) {
$start_date=$_POST[‘date’].’-‘.$_POST[‘month’].’-00′;
$end_date=$_POST[‘date’].’-‘.$_POST[‘month’].’-31′;
} ?>

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<select name=”date”>
<option value=”2012″>2012</option>
<option value=”2011″>2011</option>
<option value=”2010″>2010</option>
<option value=”2009″>2009</option>
<option value=”2008″>2008</option>
<option value=”2007″>2007</option>
</select>

<select name=”month”>
<option value=”01″>January</option>
<option value=”02″>February</option>
<option value=”03″>March</option>
<option value=”04″>April</option>
<option value=”05″>May</option>
<option value=”06″>June</option>
<option value=”07″>July</option>
<option value=”08″>August</option>
<option value=”09″>September</option>
<option value=”10″>October</option>
<option value=”11″>November</option>
<option value=”12″>December</option>
</select>
<input type=”submit” name=”submit” value=”submit” /></form>
<div>

<?php
echo ‘<table align=”center” cellspacing=”0″ cellpadding=”5″>
<tr>
<td align=”left”><b># Entries</b></td>
<td align=”left”><b>Name</b></td>
<td align=”left”><b>Username</b></td>
<td align=”left”><b>Email</b></td>
<td align=”left”><b>Phone Number</b></td>
<td align=”left”><b>Date</b></td>

</tr>’;
$command= “SELECT member_id, name, username, email_address, phone_number, date FROM tablename WHERE date>=’$start_date’ AND date<=’$end_date’ ORDER BY date desc”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
$number = 0;
while ($row = mysqli_fetch_assoc($result)) {
$number = $number + 1;

$bg =($bg==’#DCEDE5′ ? ‘#f9f9f9’ : ‘#DCEDE5’);
echo ‘<tr bgcolor=”‘ . $bg . ‘”>
<td align=”left”>’ .$number. ‘</td>
<td align=”left”>’ .$row[“name”]. ‘</td>
<td align=”left”>’ .$row[“username”]. ‘</td>
<td align=”left”>’ .$row[“email_address”]. ‘</td>
<td align=”left”>’ .$row[“phone_number”]. ‘</td>
<td align=”left”>’ .$row[“date”]. ‘</td>
</tr>’;
}
echo ‘</table>’;
}
?></div>

MYSQL Real Escape String in Query Using PHP

Here is a query for which you can use the mysqli_real_escape_string function within a query.It is identical in usage to the addslashes function, except the word addslashes is replaced with mysqli_real_escape_string.

$first_name = mysqli_real_escape_string($db, $first_name);
$last_name = mysqli_real_escape_string($db, $last_name);
$phone_number = mysqli_real_escape_string($db, $phone_number);
$email_address = mysqli_real_escape_string($db, $email_address);
$command = “INSERT INTO tablename (id, first_name, last_name, phone_number, email_address, date) VALUES (NULL,’$first_name’, ‘$last_name’, ‘$phone_number’, ‘$email_address’, now())”;
$result = mysqli_query($db, $command);

PHP Concatinating Strings

In PHP, concatination is the joining of strings. The easiest way to explain this process is through the following examples.With concatinatiion, two variables can be joined with a period inserted between them.

Example 1

$var1=”My name is”;
$var2=”John”;

echo $var1.$var2;
#Ouput is My name isJohn.
 

Example 2

$var1=”My name is”;
$var2=” “; //space
$var3=”John”;

echo $var1.$var2;
#Ouput is My name is John.

Example 3

$var1=”My name is”;
$var2=”John”;

echo $var1.” “.$var2;
#Ouput is My name is John.

Notes:
With php, all text between quotes can be ended with a period. In example 3, a space was created after $var1. We simply used quotes to make a space.

Below, is the same as example 3 with the exception of using single quotes.

$var1=”My name is”;
$var2=”John”;

echo $var1.’ ‘.$var2;
#Ouput is: My name is John.


Using Parameters with PHP Functions

With PHP functions, you can pass variables and strings into a function. Then, the function uses the variables within the function.

Passing variables Into PHP Functions

function my_function($var1, $var2, $var3) {
echo $var 1;
echo $var2;
echo $var3;

}

$variable1=”Hello”;
$variable2=”World”;
$variable3=”Hello There!”;

my_function($variable1, $variable2, $variable3);

#Output Is: HelloWorldHelloThere.
 

Passing Values Into PHP Functions

function my_function($var1, $var2, $var3) {
echo $var 1;
echo $var2;
echo $var3;

}

my_function(“Hello”, “World”, “Hello There”);

#Output Is: HelloWorldHelloThere

Passing Values and Variables Into PHP Functions

function my_function($var1, $var2, $var3) {
echo $var 1;
echo $var2;
echo $var3;

}

$variable1=”Hello”;
$variable2=”World”;

my_function($variable1, $variable2, “Hello There”);

#Output Is: HelloWorldHelloThere

Passing Optional Values Into PHP Functions

function my_function($var1, $var2, $var3=”) {
echo $var 1;
echo $var2;
echo $var3;

}

$variable1=”Hello”;
$variable2=”World”;
$variable3= $_GET[‘myvalue’];

my_function($variable1, $variable2, $variable3);

#Output Is: HelloWorldHelloThere.


How To Make a Simple Facebook Application

The most basic Facebook application is one for which Facebook allows you to create an Iframe for which you page will run inside of Facebook. This is very similar to using an iframe in HTML. The applications will be listed in the apps section of your profile.

Sign Up
https://developers.facebook.com/

1) Create New App >Fill in :
App Display Name >App Namespace >App Domain

2) App on Facebook >Canvas URL ie) mysite.com >Secure canvas url(ie) https://apps.facebook.com/my_app/
Note:
Wait for canvas url to appear underneath the secure canvas url

3) Website >Site URL

4) Edit App >Settings >Advanced >Add Privacy Policy URL >Save Changes

5) Settings >Auth Dialog >Add a Headline and privacy policy url >Save Changes

6) Open Graph >Dashboard >Set Rules for people using your app
Note: At the very least you need an object type for iframe. Type ‘website’.

7) Select Apps >Desired App
It should display:
Actions         Objects         Aggregations
Use              Website         Most recent use(global)

Note: You may have to add your first or other apps to your facebook account.

After Canvas Page propagates,
Type Canvas Page in browser (ie.) http://apps.facebook.com/my_app >Click Install

Now, you should be able to see the app when you login to Facebook. You may need to make a few adjustments so that the public, friends and you can view the app.

But, you can do a few more tweaks so that it can be publicly displayed and installed. Then, other Facebook users can use it.

To get a token,
1) Select Apps >Edit App >Use Graph API Explorer >Submit

To make app publicly available,
1) Settings >Auth Dialog >Default Activity Privacy >Public

To find errors in application development,
1) Select Apps >Choose App >Use Graph API Explorer >Get Access Token and copy the token string >Apps >Edit Settings >Use Debug Tool >Insert Token >Debug >Scopes could read publish_actions or be blank

2) Select Apps >Select App >Insights >Diagnostics

Encrypting All Entries In A Column of an InnoDB Table

Imagine you just made a huge mysql dump and you want to create encryted passwords for a login script. First, you need to encrypt some data so passwords can be stored and retrieved in an encrypted format. Below is an example showing how to encrypt all entries in one of 2 database columns.

<?php

$success = true;
//start transaction
$command = “SET AUTOCOMMIT=0”;
$result = mysqli_query($db, $command);
$command = “BEGIN”;
$result = mysqli_query($db, $command);

$command = “SELECT tablename.id, tablename.username from tablename “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
echo “<br/><br/>Result 1 is:”.$result.”<br/><br/>”;
$myids = $row[‘id’];
$user_name = $row[‘username’];
$user_name= md5($user_name);
echo “hello”.$user_name;
$command2 = “UPDATE tablename SET username=’$user_name’ WHERE id=’$myids’ ORDER BY id DESC”;
$result2 = mysqli_query($db, $command2);
echo “<br/><br/>Result 2 is”.$result2.” and id is “.$myids.” and encrypted username is “.$user_name.””;
if (($result == false) ||
(mysqli_affected_rows() == 0)) {
$success = false;
}
}
}

$command = “COMMIT”;
$result = mysqli_query($db, $command);
#set session variable
$command = “SET AUTOCOMMIT=1”;  //return to autocommit
$result = mysqli_query($db, $command);
?>

Encrypting All Entries In A Column of a MYISAM Table

$command = “SELECT tablename.id, tablename.username from tablename “;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
echo “<br/><br/>Result 1 is:”.$result.”<br/><br/>”;
$myids = $row[‘id’];
$user_name = $row[‘username’];
$user_name= md5($user_name);
echo “hello”.$user_name;
$command2 = “UPDATE tablename SET username=’$user_name’ WHERE id=’$myids’ ORDER BY id DESC”;
$result2 = mysqli_query($db, $command2);
echo “<br/><br/>Result 2 is”.$result2.” and id is “.$myids.” and encrypted username is “.$user_name.””;

}
}

Items From Database

This tutorial shows the backbone for which you can create a dynamic dropdown menu from any database column. You will pull only the distinct values for an entry and autoselect the option for which the user has chosen. This is a procedure for updating entries.

function dynamic_update_menu($my_id) {

$command= “SELECT DISTINCT size from table”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
/*creates an array from the distinct names in the column. The process actually makes 3 separate arrays. You can see with print_r() function. The arrays are Array ( [0] => Small ) Array ( [0] => Small [1] => Medium ) Array ( [0] => Small [1] => Medium [2] => Large ) */
$sizes[] = $row[‘size’];
print_r($sizes);
}
}
echo ‘<select name=”sizes”>’;

$command2= “SELECT size from table where id =’$my_id’;”;
$result2 = mysqli_query($db, $command2);
if ($result2 && mysqli_num_rows($result2) > 0) {
while ($row = mysqli_fetch_assoc($result2)) {

$myname=$row[‘size’];

foreach ($sizes as $key => $value) {

if($myname==$value) {
$selected=”selected=’selected'”;
}
else {
//make other months not selected
$selected=””;
}
//output the current month as selected
echo “<option value=\”$value\” $selected>$value</option>\n”;
}
}
echo ‘</select>’;
}
}

Items From Hard-Coded Array

function dynamic_update_menu($my_id) {

$sizes = array (‘Small’, ‘Medium’, ‘Large’);

echo ‘<select name=”sizes”>’;

$command2= “SELECT size from table where id =’$my_id’;”;
$result2 = mysqli_query($db, $command2);
if ($result2 && mysqli_num_rows($result2) > 0) {
while ($row = mysqli_fetch_assoc($result2)) {

$myname=$row[‘size’];

foreach ($sizes as $key => $value) {

if($myname==$value) {
$selected=”selected=’selected'”;
}
else {
//make other months not selected
$selected=””;
}
//output the current month as selected
echo “<option value=\”$value\” $selected>$value</option>\n”;
}
}
echo ‘</select>’;
}
}

Addslashes() with PHP

You should sanitize data before inserting or updating data from forms into a mysql database. Two common methods are to use the functions mysqli_real_escape_string() or addslashes(). Sanitizing with mysqli_real_escape_string() is the best option, but, for demo purposes, I will show another method(which I would personally never use in production).

Note:
If you plan to update the data in the future, using the stripslashes function applied to the selected data will remove the slashes. Otherwise, you could end up with a string like John\’s shoes.

Here is how a query would look when the using addslashes() function is used on a variable:

$command = “INSERT INTO table VALUES (NULL, ‘”.addslashes($_POST[name]).”‘, ‘”.addslashes($_POST[username]).”‘, ‘”.addslashes($_POST[email]).”‘, ‘”.addslashes($_POST[address]).”‘, now())”;

$result = mysqli_query($db, $command);

Here is how a query would look to display data for which slashes had been added:
Note:

$command = “SELECT name, email FROM table where id='”.addslashes($id).”‘;”;
$result = mysqli_query($db, $command);
while ($data = mysqli_fetch_object($result)) {
echo stripslashes($data->name).” “.stripslashes($data->email);

or

$command = “SELECT name, email FROM table where id=1”;
$result = mysqli_query($db, $command);
while ($data = mysqli_fetch_object($result)) {
echo stripslashes($data->name).
” “.stripslashes($data->email);

or

$command = “SELECT name, email FROM table where id=1″;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$name=$row[‘name’];
echo stripslashes($name).” “.stripslashes($row[“email”]);
echo stripslashes($row[’email’]);

 

MYSQL Real Escape String with PHP

You should sanitize data before inserting or updating data from forms into a mysql database. Two common methods are to use the functions mysql_real_escape_string() or addslashes().

Note:
If you plan to update the data in the future, using the stripslashes function applied to the selected data will remove the slashes. Otherwise, you could end up with a string like John\’s shoes.

Here is a method to use the mysqli_real_escape_string() function

A)
//Use the function with a post variable.
$var = mysqli_real_escape_string($db, $_POST[‘name’]);

B)
//Set a variable that is the form post data. Then, make a new variable equal to the post data.
$var = mysqli_real_escape_string($db, $name);

Here is how a query would look with a sanitized variable:

$command= “INSERT INTO table values (NULL, ‘$var’,  now());”;
$result = mysqli_query($db, $command);


Using Load Data to Add File to MYSQL table

With mysql, 4 typical methods to import data into a database are to iport the data, loading text data and dumping a csv file from Excel, or importing data from a xml file. This tutorial discusses loading the data from a text file.

The file below is contents of a text(.txt) file. Note that line 1 just tells us what the two database table columns could be.

Country    City
CAN    Vancouver
CAN    Toronto
CAN    Montreal
CAN    Regina

The text below would add the file(my_file.txt) shown above into a database table called canadian_cities.

To load data,
1) Open the desired database with phpmyadmin or mysql console.
2) Open SQL in phpmyadmin or a) Open mysql console >Type: use databasename;
3) With the above file, we have 2 columns. Therefore, the table should already be setup with 2 columns to insert the data. In this case, the two table columns could be country and can_city.
3) Type the command:
LOAD DATA LOCAL INFILE ‘c:/my_file.txt’ INTO TABLE `canadian_cities`FIELDS TERMINATED BY ‘\t’    LINES TERMINATED BY ‘\r\n’ IGNORE 1 LINES;

Decyphering the command:
The file myfile.txt gets loaded into the table canadian_cities which is in the database called world_cities.

The fields are terminated by ‘\t’ which means there is a tab space between the two columns; in this case between country name CAN and a city like Toronto.

Lines terminated by ‘\r\n’ means that each new line is a new row in the table.

IGNORE 1 LINES means the first line with the junk text ‘Country City’ is not inserted into the database. In order to load the data, we had already set the table and columns up. You could omit this condition if you deleted the first line ‘Country City’.


WAMP Large sql File Export

Often, and especially in the past, PHPMYADMIN in WAMP is not designed to handle the importing of larger sql file.

Here are a couple of quick tips to increase the ability for phpmyadmin to handle large files. 

1) Open the php.ini file:
Click Wamp Server >PHP >php.ini
Find and change the following lines:
upload_max_filesize = 100M
post_max_size = 100M
2) Restart Apache Server.
3) Try importing the file

Note:
You may get the following error uploading a large file:
Set timeout
Fatal error: Maximum execution time of 300 seconds exceeded in C:\wamp\apps\phpmyadmin2.11.6\libraries\import\sql.php on line 118

4) Open C:\wamp\apps\phpmyadmin\config.inc.php
a) Near line 128 you can change the time for which phpmyadmin will execute
b) Change the number.
Before:
$cfg[‘ExecTimeLimit’]           = 300;    // maximum execution time in seconds (0 for no limit)
After:
$cfg[‘ExecTimeLimit’]           = 10000;    // maximum execution time in seconds (0 for no limit)
5) Restart All Services

More Options:
6) a) Open:
my.ini located in C:\wamp\bin\mysql\mysql5.0.51b\my.ini
b) Add the code:
max_allowed_packet = 200M

7) Open:
C:\wamp\apps\phpmyadmin3.4.5\config.inc.php
Look for:
$cfg[‘UploadDir’] = ”;
Change to:
$cfg[‘UploadDir’] = ‘upload’;

8) Create a directory called ‘upload’ in:
C:\wamp\apps\phpmyadmin3.X.X
Copy and Paste sql file to:
C:\wamp\apps\phpmyadmin3.X.X\upload\

9) Restart All Services


CKEditor with PHP

CKEditor can be used to add a editor into a custom cms, or any othered desired application where you want control to edit text, images, video or source code. The editor is similar to what you would see in WordPress, Drupal and Joomla. Personally, I think it is better than default cms editors since it has more bells and whistles.

The procedure to download and use the editor is quick and simple.

To add CKeditor into a php application.
1) Download CKeditor
2) Extract
3) FTP into the directory.
4) Add the Javascript and code into desired page.
5) Add javascript to the files into the head of the file for which you will use the editor
<script type=”text/javascript” src=”http://mysite.com/ckeditor/ckeditor.js”></script>
<script src=”http://mysite.com/ckeditor/_samples/sample.js” type=”text/javascript”></script>
6) Add the code into your desired file. The code samples exist in the sample files located in the _samples directory.
7) Option:
Use custom CRUD script to update desired content from database.

Note: If you want use html, head and body tags within the editor code
a) Open config.js
b) Add the text:
config.fullPage=true;

Simple PHP / MYSQL SESSIONS

//session_start() function is always required
session_start();
require_once(‘mydb.inc’);
$db=my_db_connect();
//error_reporting(0);

$user = $_POST[‘username’];
$password = md5($_POST[‘password’]);

If ($user || $password) {
if (!($user)) {
$error_message = “Please enter your username. “;
}
else if (!($password)) {
$error_message = “Please enter your password. “;
}
else {
#Check the mysql database for username and password
$command = “SELECT id, username, usertype FROM users WHERE username=’$user’ AND password=’$password’ AND usertype=’Administrator’;”;
$result = mysqli_query($db, $command);
if ($data = mysqli_fetch_object($result)) {
#if username, set sessions and redirect.
$_SESSION[‘id’] = $data->id;
$_SESSION[‘username’] = $data->username;
//If desired, you can echo output to see/check values.
}
else {
$error_message = “Sorry, your username was incorrect!”;
echo $data->username;//Note: nothing outputs since no object
echo $data->id; //Note: nothing outputs since no object
}
}
}

PHP / MYSQL Simple User Access Levels

session_start();
//echo $_SESSION[‘username’];
$myuser = $_SESSION[‘username’];

if ($myuser) {
$command=”SELECT * from users WHERE username=’$myuser’;”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {

if ($row[‘access_level’]==’1′) {

echo “Add stuff here!”;

}

else if ($row[‘access_level’]==0){
echo “Add specific stuff here!”;
}
}
}
} else {
echo “Add general stuff here for any non-member!”;
}

PHP / MYSQL Distinct Dynamic Drop Down Menu

The function below creates a dynamic dropdown menu for which it will select all the cities from each user’s address. If there are duplicate values, they will not be duplicated because DISTINCT was added to the SELECT query. Thus, if there are 7 users and 5 distinct cities, only 5 cities will show up on the dynamic drop down menu.

function dynamic_dropdown() {

echo ‘<select name=”myname”>’;
$command= “SELECT DISTINCT mt.city from mytable as mt where mt.user_id>1 “;
$rows = array();
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

//echo $row[‘city’];
$name=$row[‘city’];
echo “<option value=\”$name\” >$name</option>\n”;
}
}
echo ‘</select>’;
}

//call the function
dynamic_dropdown();


MYSQL Query With Numbers

MYSQL Queries with Numbers

When you make a query with mysql you can use quotes or use no quotes. In most cases, making queries without quoting numbers is safer. For example, examine the 2 queries used in php below:

$command= “SELECT name, email from table where years_experience<10 “;
$command= “SELECT name, email from table where years_experience<’10’ “;
//You may get unexpected results if there are the integers with the value 0 in some of the years_experience rows. In this case, the //column years_experience stores integers.

Although the two queries above may look alike, you can output the data to see how it actually worked. Testing output with mysql commands with phpmyadmin(or mysql console) and using the php script will help ensure you get the results you expect. On various servers, you could get various results.

In a nutshell, values inside of quotes will be strings. If you want numbers…use no quotes. With PHP, anything inside quotes is a string wheras any number without quotes is an integer.

$integer=123;
$number_string=’123′;


MYSQL Rows Output Brackets and Quotations

When you output database table rows into a list or table, you have several ways to write the output.

Outputting Rows Without Quotes
echo $row[‘name’];
or
echo $row[name];

Outputting Rows Within Double Quotes.
echo “$row[name]”;


Terminiating a MYSQL Statement

Mysql statements executed within a php script can have 3 different endings.

Option a)
$command= “Select col1, col2 from tablename where id>’0′”;
Option b)
$command= “Select col1, col2 from tablename where id>’0′ “;
Option c)
$command= “Select col1, col2 from tablename where id>’0′;”;

At first glance you may think they all yield the same results, but, technically, they are all different. If you want to use the queries above, they will all give the same results, unless you add another clause to the query.

However, you may want to add more length to the query like adding a limit clause; such as the one below.
$command .= ‘limit ‘ .($page_number – 1) * $number_entries .’,’ .$number_entries;

If you want to add to the initial command, it is safe to use option b since the white space at the end of the query could be the method for which the query behaves as you want it to.

Option a could merge the two statements to something like where id>’0’limit………
You do not want the end of the query to merge next to the limit clause without a space. It could cause an error.
You want where id>’0′ limit…

Option c, which ends ;”; will stop the query at the first semi-colon. Using it is fine, just remember it can lock the statement.


Calling a PHP Function

The php function is called and the function will execute.

//Calling the function
my_function();

function my_function() {
    echo “Hello World!”; //Outputs Hello World
    }


Passing Multiple Variables Into PHP Function

When you pass multiple variables into a PHP function, they can be used within the function. The main point here is the order. You should always input the variables in the same order as you will use them in the function. Naming has nothing to do with it.

The example below shows how to pass multiple variables into a function and how to output those variables.
    
//variables    
$var=”Hello”;
$var2=”World”;
//calling function
my_function($var, $var2);

//function below
//Note that the variable $var is now $my_var and $var2 is now $my_var2
my_function($my_var, $my_var2){
    echo $my_var.” “.$my_var2;//Outputs Hello World
                }
   


Passing Variable Into PHP Functions

When you pass a variable($myvar) into a PHP function, it can be used within the function. The example below shows how to pass a variable into a function and how to output that variable.

$var=”Hello”;
//To call a function, you simply use the function name and put the variable you want to pass in parenthesees
my_function($var);
function my_function($my_new_var) {
    echo $my_new_var; //Outputs Hello
    }

When working with dates in php, it is easy to convert date strings when it outputs like 2010-01-24. You can convert that to almost anything you want, like January 1, 2010 or Jan 1/10.

Here is a simple method to create a date which can be inserted into a mySQL database. Alternatively, you can convert the string for output.

$year=”1983″;
$month=”02″;
$day=”14″;
$mydate = $year.”-“.$month.”-“.$day;
$mydate = date(“Y-m-d”, strtotime($mydate));

echo $mydate; //prints 1983-02-14

Autofill Values To a Text Input Box

Form

<p style=”display:visible;”>
<label for=”myfield”>Name:</label>
<input type=”text” name=”myname” id=”myname”  value=”<?php
$column=”name”;
get_text($column,$id);
?>” />
</p>

Function

function get_text($mycolumn,$myid) {
//This outputs what we want; the variable which is passed in to the function
$command= “SELECT $mycolumn FROM counselling_report where id=’$myid'”;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$var=$row[‘name’];
echo $var;
}
}

Connect To Database with PHP MYSQL

To connect to a mysql database,

1) Create a file such as connect.inc or connect.php.
2) Add the following code.

<?php
function public_db_connect() {
     
    $host = “localhost”;  //usually always localhost
    $user = “root”; //user for wamp
    $pw = “”; //no password for wamp
    $database = “mydb”; //database name

//connect to mysql
    $db = mysql_connect($host,$user,$pw)
       or die(“Cannot connect to mySQL.”);
//connect to mysql database
    mysql_select_db($database,$db)
       or die(“Cannot connect to database.”);
  
    return $db;
 }
 ?>

3) In your file that need to connect to the database you must write the following code at the top of the page:
include(‘connect.inc’);

Alternatively, you could use the same code on any page for which you want tom connect to the database. However, keeping include files in a safe directory is more secure than just leaving the access codes on random pages.

Autofill Input Text Value for Updating Content

Here is a method to populate input text fields from a database using PHP / mySQL.

<p>
<label style=”display:visible;” for=”Name”>Name:</label>
<input type=”text” name=”firstname”  value=”<?php
$command= “SELECT name FROM table where id=’$session_id'”;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$name=$row[‘name’];
echo $name;
}?>” />
</p>

PHP Pagination

Here is some php code which could be used to paginate rss feeds or database queries.

<div class=”myBody”>
<ul>
<?php

if (!(isset($page_number))) {
$page_number = 1;
}

//Need to get the page number
$page_number=$_GET[‘pagenumber’];

$command = “select table1.category_id, table1.seo_fname, table2.post_id, table2.6, table2.post_date, table2.2, table2.5, table2.8, table2.9, table2.15 from cats as table1, p_table as table2 WHERE table1.category_id=table2.6 AND (table2.2 LIKE ‘$keywords%’ OR table2.2 LIKE ‘%$keywords%’ OR table2.5 LIKE ‘%$keywords%’) ORDER by table2.post_date DESC”;
$result = mysqli_query($db, $command);

$rows = mysqli_num_rows($result);
//command below tells us how many entries there actually are
//echo $rows;

//how many entries we want
$number_entries = 3;
//echo $number_entries;
//This tells us the page number of our last page
$last_page = ceil($rows/$number_entries);

//this makes sure the page number isn’t below one, or more than our maximum pages

if ($page_number < 1) {
$page_number = 1;
}
elseif ($page_number > $last_page) {
$page_number = $last_page;
}

//This is the query. It could be any query
$command2 = “select table1.category_id, table1.seo_fname, table2.post_id, table2.6, table2.post_date, table2.2, table2.5, table2.8, table2.9, table2.15 from cats as table1, part_table as table2 WHERE table1.category_id=table2.6 AND (table2.2 LIKE ‘$string%’ OR table2.2 LIKE ‘%$string%’ OR table2.5 LIKE ‘%$string%’)”;

//This sets the range to display in our query
//$command2 .= ” LIMIT “.(($page_number – 1) * 4).”,4″;
$command2 .= ‘limit ‘ .($page_number – 1) * $number_entries .’,’ .$number_entries;

//This is where you display your query results
$result2 = mysqli_query($db, $command2);
while($row = mysqli_fetch_array($result2)) {

$even_odd = ( ‘odd’ != $even_odd ) ? ‘odd’ : ‘even’;
?>
<div style=”display:inline-block;”>
<li style=”min-height:80px; width:99%; height:100%;” class=”myRow <?php echo $even_odd; ?>”>
<h4><?php echo “<a href=/jobs/job/$row[post_id] title=’$row[2]’ >$row[2]</a>”; ?></h4>
<div style=”width:600px; display:inline-block; “><p class=”myDesc” ><?php echo substr($row[5], 0, 120).”…”; ?></p></div>
<div style=”display:inline-block;” class=”mySource” ><span><?php echo “Name”; ?></span></div>
<div style=”display:inline-block;” class=”myDate”><?php echo date(‘l, jS<br/> F Y’, strtotime($row[post_date]));?></div>
</li></div>
<div style=”clear:both;”></div>
<?php

}

//starting with the first page, make a loop for all pages and links to those pages
for($i = 0; $i<$last_page; $i++) {
$page_link = $i + 1;
//create an array of links
$links_pages[] = ” <a style=\”font-size:13px;\” href=’http://localhost/page.php?pagenumber=”.$page_link.”‘ >”.$page_link.”</a>”;
}

// First we check if we are on page one. If we are then we don’t need a link to the previous page or the first page so we do nothing. If we aren’t then we generate links to the first page, and to the previous page.

if ($page_number == 1) {
}
else if ($page_number > 1)
{
echo ” <a style=\”font-size:13px;\” href='{$_SERVER[‘PHP_SELF’]}?pagenumber=1′> <<-First</a> “;
echo ” “;

$previous_page = $page_number-1;

echo ” <a style=\”font-size:13px;\” href='{$_SERVER[‘PHP_SELF’]}?pagenumber=$previous_page’> <-Previous</a> “; ?>

<?php
}

if ($page_number == $last_page) {
}
else {
$next_page = $page_number+1;
echo “<a style=\”font-size:13px;\” href='{$_SERVER[‘PHP_SELF’]}?pagenumber=$next_page’>Next -></a> “;
echo ” “;
echo ” <a style=\”font-size:13px;\” href='{$_SERVER[‘PHP_SELF’]}?pagenumber=$last_page’>Last ->></a>”;
}

// This shows the user what page they are on, and the total number of pages
echo “<span style=\”font-size:13px;\”> Page $page_number of $last_page</span>”;
?>
<div class=”mypageclass”>
Page:
<?php
if (count($links_pages))  {
foreach($links_pages as $links){
echo $links;
}
}
else {
echo “1”;
}
?>
</div>
</ul></div>

Retrieving Radio Values from Database and Updating Form

Here is some code that shows 2 typical html radio buttons.

<p>
<label for=”rel”>Relative in Canada?:</label>
<input type=”radio” name=”member”  value=”yes” /> Yes
<input type=”radio” name=”member”  value=”no” /> No
</p>

Here is some code that shows 2 radio buttons that receive the value from the database. The chosen radio radio selection from the database will be automatically selected. This is a method which could be implemented when updating a database entry. The key is to pull the original values from the databse that were inserted from the original form.  With this update page, the new changes can be updated upon submit.

<p>
<label for=”rel”>Members in United States?:</label>
<?php
$command= “SELECT col1 FROM table where id=’$my_id’ AND member=’yes'”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) ) {
while ($row = mysqli_fetch_assoc($result) >0) {
echo ‘<input type=”radio” name=”member”  value=”yes” checked=”checked” /> Yes’;

}}
else { echo ‘<input type=”radio” name=”member”  value=”yes”  /> Yes’;
}?>

<?php
$command= “SELECT col1 FROM counselling_report where id=’$report_id’ AND member=’no'”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) ) {
while ($row = mysqli_fetch_assoc($result)>0) {
echo ‘<input type=”radio” name=”member”  value=”no” checked=”checked” /> No’;

}}
else { echo ‘<input type=”radio” name=”member”  value=”no”  /> No’;
}?>
</p>

Multiple mySQL Column Updates

To update multiple columns with new values with mysql,
1) $command = “UPDATE table SET col1 = ‘$var1’, col2 = ‘$var2’, col3 = ‘$var3’ WHERE id = ‘$myid'”;
$result = mysqli_query($db, $command);

AJAX and PHP

To make ajax and php output your desired data from a mysql, you will need 3 files;
a) main php file with a form and javascript ajax function
b) functions file which has the dynamic drop down menu
c) second php file which handles the GET variable from the url.

How To

1) Have a php function that has select box with a unique name and onchange javascript function like. The drop down menu is dynamic.

function pulldowns() {

echo ‘<select name=”listings” onchange=”pulldownit(this.value)”>’;
$command= “SELECT col1, col2, col3 from country ORDER BY membername ASC”;
$rows = array();
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

//echo $row[‘col1’];
$name2=$row[‘col2’];
$name =$row[‘col3’];
echo “<option value=\”$name\” >$name2</option>\n”;
}
}
echo ‘</select>’;

2) When an option is selected the ajax call is made. The desired drop down option is the value which gets passed into the javascript function pulldownit(). STR is the value selected. Now ajax goes to work with the string value.

The ajax call opens the desired file with xmlhttp.open(“GET”,”getupdate.php?formname=”+str,true);

<script type=”text/javascript”>
function pulldownit(str)
{
if (str==””)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”getupdate.php?formname=”+str,true);

xmlhttp.send();
}
</script>

The getupdate.php file passes the value into the url. Then, queries run based on the value selected. Change the value and that changes the str value in the url. Voila…fast synchronous output.

3) Set a variable for the get value with the php file which is called
//The getupdate.php file sets avariable to $_GET'[‘formname’]
$formname=$_GET[“formname”];

4) Get any data from the database with that variable.

When using WAMP to make custom php / mysql applications, it would not be uncommon to find it not to behave like your web host. Such issues can occur with if statements that need else conditions, or php short tags not working. If you accidentally have a php short tag, the code may just be treated as if nothing was there. The short tag is <? while the safe notation for starting a block of php code is <?php. Using short tags can be risky if you plan to reuse the code since some servers may not enable the usage, thus, code may not execute as expected. Using <?php always works.

To allow the usage of short tags in wamp,
1) Open WAMP SERVER
2) Select PHP >PHP SETTINGS >Short Open Tags
Note: Make sure ‘Short Open Tags’ has a checkmark.

Alternatively,
1) Open php.ini
2) Look for short_open_tag = On
3) Update the line to:
short_open_tag = On

To move a table from one mysql database to another,
1) Open phpmyadmin >Select table in phpmyadmin
2) Export table
3) Add the table to the other database
a) Select Import >Select File >Go
b) Open table in phpmyadmin >Operations >Rename table if desired

or

To move a table from one mysql database to another,
1) Open phpmyadmin >Select table in phpmyadmin >Export table
2) Open file with editor like Notepad++ >Select ‘SQL’ with phpmyadmin >Paste the entire query that begins with ‘Create Table in NOT Exists’.
Note: You should have 2 queries. One for the new table creation and one for inserting the table data.
2) Select the new database table >Click ‘SQL’ >Paste the query that begins with ‘INSERT INTO’ > Click Go


Quick Start SMF Forum Guide

Quick SMF Template

To remove icon in top right,
1) Login to forum with FTP
2) Edit image in top right corner.
a) Go to Themes >default >images>smflogo.png
b) Edit image and upload.

To edit background,
1) a) Go to Themes >default >images> theme >backdrop.png
b) Edit and upload new background image.
2) a) Go to Themes/default/images/theme/main_block.png
b) Edit and upload new background image.

To edit CSS,
1) Go to Themes >default >css >index.css >change body background to match backdrop.png.

To remove info center at the bottom of the page,
1) Open file Themes/default/BoardIndex.template.php
2) Comment out the function:
template_info_center();
change to
//
template_info_center();
3) Change:
<div id=”posting_icons” class=”flow_hidden”>
Change to:
<div id=”posting_icons” class=”floatleft”>

Creating a Top Menu

To create a custom top menu,
1) Download Custom Top Menu Module (ie. ctm_1.4).
2) Upload Module
3) Install Mod
4) Install new to install in default theme.

To use the top menu module,
1) Go to Admin >Features and Options >Administration Center >Configuration Modification Settings >Top Menu.
2) Add tabs and urls
3) Click Save

New Forum Categories and Boards

To add a category,
1) Go to Admin >Features and Options >Forum >Borads >Create new Category
2) Name category
3) Select Category order.
4) Select Add Category.
5) Add a Board for that category.

To add a board,
1) Go to Forum >Boards >Modify Boards >Select Add Board for the desired category.
2) Add full name and other details such as description.
3) Add Board.

To change category order,
1) Go to Forum >Boards >Modify Boards
3) Click Modify next to the category name.
4) Set the order.
5) Click Modify.

To delete a category,
1) Go to Forum >Boards >Modify Boards
3) Click Modify next to the category name.
4) Click Delete Category.

To change board order,
1) Go to Forum >Boards >Modify Boards
3) Click Modify for the board name.
4) Set the order.
5) Click Modify.

To delete a board,
1) Go to Forum >Boards >Modify Boards
3) Click Modify next to the board name.
4) Click Delete Board.


SEF URLS

To create SEF URLS,
1) Login as admin.
2) Select admin >features and options >Check Search Engine Friendly URLs >Save

To delete a member,
1) Login >Admin >Features and Options >Members >Members >View All Members >Checkbox member(s) you want to delete. >Delete Selected Members

Stop Spam
1) Download Stop Spammer module
2) Install module
3) Enable module

Furthermore, you can adjust built-in features.
1) Go to Admin > Configuration >Security and Moderation > Anti spam >Select Checkboxes >Save

Installing Modules

To install a module,
1) Download module
2) Admin >Package manager >Download Packages >Scroll to bottom >Upload downloaded package >Install Mod >Install Now

To see installed packages,
1) Go to Main >Package Manager >Installed packages

Uninstall  Module

To uninstall a module,
1) Go to Installed Packages > Uninstall >Select ‘Remove all data associated with this modification’>Uninstall Now

Note:
If you uninstall a module, it will be accessible again when you select ‘Browse Packages’.

With PHP, you make not equal to command with !- .

With a mysql query, you use <> in a query to make a condition where not equal to.

Here is an example to make page links with specified urls. Since You want home page on the top, you make 2 queries so that it does this, while making the other pages in alphabetical order.

<ul style=”list-style-type:none; padding: 0px 10px 0px 10px;”>
<?php
$command = “SELECT title, url FROM table where url=’index.php’ ;”;
$result = mysqli_query($db, $command);
while ($data = mysqli_fetch_assoc($result)) {
// echo stripslashes($data->sidebar);
//echo “<ul style=\”list-style-type:none;\”>”;
echo “<li style=\”margin-left:0px;\”><a href=\””.$data[‘url’].”\”>”.$data[‘title’].”</li></a>”;
//echo “</ul>”;
}

$command = “SELECT title, url FROM table WHERE url<>’index.php’ order by title asc;”;
$result = mysqli_query($db, $command);
while ($data = mysqli_fetch_assoc($result)) {
// echo stripslashes($data->sidebar);
//echo “<ul style=\”list-style-type:none;\”>”;
echo “<li style=\”margin-left:0px;\”><a href=\””.$data[‘url’].”\”>”.$data[‘title’].”</li></a>”;
//echo “</ul>”;
}
?>
</ul>


NOTEPAD++ PHP Editor

Notepad++ is quite a versatile html, css, Javascript and PHP editor. It does a fantastic job at separating and hightlighting the various codes such as Javascript, PHP and HTML. In fact, you could put several individuals into a page and the colors alone would determine whom edits what content.

Besides that,it is free and very lightweight. When you right click and edit a page with Notepad++, it opens almost instantly. I cannot think of any other PHP editors who come close to half that time.

Asides from the features above, Notepad++ allows you to click on a tag(ie div), or a curly bracket in php from an if, else or while statement and it will find the closing tag while highlighting it very nicely.

Notepad
Alternatively, you can always use Notepad which comes with all Windows systems. You simply save files as “filename.php”. You must have double quotes before and affter the end of the file.


Add String to all entries in a Column with MYSQL

Add text to a string with MYSQL Concat Function

The code will allow will add .php to each entry in the url column.

1) Open mysql> or phpmyadmin
2) Open sql in phpmyadmin or use mysql> prompt
3) Execute the command:
UPDATE tablename set url=concat(url,’.php’) where id>’0′;

PHP user Access

There could be times when you need to create user access levels for php / mysql scripts. The simplest method is to create a table column that can hold specific access levels such as 1, 2 , 3.  1 could be public, 2 could be registered users and 3 could be administrators.

Here is a block of code which shows 3 different user levels and how to output code blocks based on that output level.

<?php session_start();
//echo $_SESSION[‘session_name’];
//set a variable to the session name
$user = $_SESSION[‘session_name’];

if ($user) {
//select statement to find access level based on unique username

$command=”SELECT table.ID, table.Username, table.access_level from table WHERE table.Username=’$user’;”;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
//echo $row[‘Username’];
//echo $row[‘access_level’];

if ($row[‘access_level’]==’1′) {
//add custom content here for this user access level?>

<?php }

else if ($row[‘access_level’]==0){
//add custom content here for this user access level
?>

<?php
}
}
}
} else {
//add custom content here for public access level
?>
<?php }?>


Hide PHP Error Reporting

PHP error reporting is fine for determining hopw to fix and polish scripts. However, there could be times when you want to hide errors from appearing on a web page.

To hide php errors,
1) Place the following code block in a header or top of php file.
error_reporting(0);

MYSQL Copy Table

Although some versions of phpmyadmin allow you to easily copy mysql tables; you may find it faster to use a query or in a position where phpmyadmin does not have the feature.

To copy and nename a mysql table,
1) open mysql prompy mysql> or the database with phpmyadmin
2) Type the command:
CREATE TABLE table2 SELECT * FROM table1;

This form allows you to take session variables from a login form for which you can alter the Joomla user table.

ALTER JOOMLA PASSWORD WITH CUSTOM PHP MYSQL SCRIPT

//start session and connect to db
session_start();
$id=$_SESSION[‘id’];
$user=$_SESSION[‘username’];
require_once(‘connect.inc’);
$db=db_connect();

//basic form validation
if (empty($old_password ) || empty($new_password) || empty($confirm_password) || ($confirm_password != $new_password) || ($old_password != $old_pass)){
echo “<b>PLEASE FILL IN DATA.</b><br/><br/>”;
}

if (!($id)) {
$error_message = “Please enter the username you used to join. “;
header(‘Location: outer_space.php’);
}

if ($id) {
$name = $_POST[‘name’];
$username = $_POST[‘username’];
$email = $_POST[’email’];
$password = md5($_POST[‘password’]);
$usertype = $_POST[‘usertype’];
$gid = $_POST[‘gid’];

$params = “admin_language=
language=
editor=
helpsite=
timezone=0”;

$command = “INSERT INTO jos_users VALUES (NULL, ‘”.addslashes($_POST[name]).”‘, ‘”.addslashes($_POST[username]).”‘, ‘”.addslashes($_POST[email]).”‘, ‘$password’, ‘”.addslashes($_POST[usertype]).”‘, 0, 0, ‘”.addslashes($_POST[gid]).”‘,   now(), now(), ”, ‘$params’)”;
$result = mysql_query($command, $db);

}

Here is the formto add Registered Users into Joomla Users Table

<form method=POST action=”<?php echo $_SERVER[‘SELF’]; ?>”>
<table>
<tr>
<td align=right>
Name:
</td>
<td align=left>
<input type=text size=25 max=50 name=”name”>
</td>
</tr>
<tr>
<td align=right>
Username:
</td>
<td align=left>
<input type=text size=25 max=50 name=”username”>
</td>
</tr>
<tr>
<td align=right>
Email:
</td>
<td align=left>
<input type=text size=25 max=50 name=”email”>
</td>
</tr>
<tr>
<td align=right>
Password:
</td>
<td align=left>
<input type=password size=12 max=12 name=”password”>
</td>
</tr>
<tr>
<td align=right>

</td>
<td align=left>
<input type=”hidden” size=12 max=12 name=”usertype” value=”Registered”>
</td>
</tr>
<tr>
<td align=right>

</td>
<td align=left>
<input type=”hidden” size=12 max=12 name=”gid” value=”18″>
</td>
</tr>
<tr>
<td colspan=2 align=center>
<input type=submit value=”SUBMIT”>
</td>
</tr>
</TABLE><br>
</form>


Conditional if statements for empty form fields with PHP

if (empty($old_password ) || empty($new_password) || empty($confirm_password) || ($confirm_password != $new_password) || ($old_password != $old_pass)){
echo “<strong>PLEASE FILL IN ALL PROPER DATA.</strong><br/><br/>”;
}

The php strstr() is a great method to retrieve part of a string after a certain point.Here is an example to retrieve a url and get the page title for other purposes.

<?php
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;
}

$var=my_page_URL();
//This shows the url
echo $var;

//strstr gets all string after a certain point
$domain = strstr($var, ‘mysitename’); //will output mysitename.com/mypage.php
echo $domain; // prints mysitename.com/mypage.php whether the url had http:, www., etc

//now get rid of mysitename.com
$cms_page_title= str_replace(‘mysitename.com/’, ”, $domain);

echo $cms_page_title; //now we get mypage.php
?>
 

ORIG FEED
http://api.indeed.com/ads/apisearch?publisher=0000000000000000&q=java&l=austin%2C+tx&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2

Updated Feed to XML
$file = file_get_contents(‘http://api.indeed.com/ads/apisearch?publisher=0000000000000000&q=’.$keywords.’&l=’.$loc.’&sort=&radius=&st=&jt=&start=&limit=30&fromage=&filter=&latlong=1&co=ca&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&.xml’, true);

// write all code here
$dom = new DOMDocument;
//$dom->load($url);
// use the above to load an xml file on server or below to load the api. Both run in less than 1/10 second
@$dom->loadHTML($file);

foreach ($dom->getElementsByTagname(‘result’) as $result) {
$date = $result->getElementsByTagname(‘date’);
$date_text_value = $date->item(0)->firstChild->nodeValue;
       
// indeed url
$myurl = $result->getElementsByTagname(‘url’);
$myurl_value = $myurl->item(0)->firstChild->nodeValue;
$myurl = $result->getElementsByTagname(‘jobkey’);
$myurl_value = $myurl->item(0)->firstChild->nodeValue;
$jobtitle = $result->getElementsByTagname(‘jobtitle’);
$jobtitle_value = $jobtitle->item(0)->firstChild->nodeValue;
$source = $result->getElementsByTagname(‘source’);
$source_value = $source->item(0)->firstChild->nodeValue;
$snippet = $result->getElementsByTagname(‘snippet’);
$snippet_value = $snippet->item(0)->firstChild->nodeValue;

print “$date_value.$source_value \n”;

//create an array from the values which can be combined with other feed sources
$myarray[] = array(“link” => “$myurl_value”, “title” => “$jobtitle_value”, “source” => “$source_value”, “description” => “$snippet_value”, “date” => “$dateString”);
}

ORIG FEED
http://api.indeed.com/ads/apisearch?publisher=0000000000000000&q=java&l=austin%2C+tx&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2

Updated Feed to XML
$file = file_get_contents(‘http://api.indeed.com/ads/apisearch?publisher=0000000000000000&q=’.$keywords.’&l=’.$loc.’&sort=&radius=&st=&jt=&start=&limit=30&fromage=&filter=&latlong=1&co=ca&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&.xml’, true);
$ext=”.xml”;
$feedurl=”myfeed”;
//This makes a name like mysite.com/myurl.php with unique time
$myfeed=$feedurl.time().$ext;
//opens or creates the file here with the desired name    
$fh = fopen($myfeed, ‘w’);
//writes the file to the new file name
fwrite($fh, $file);
fclose($fh);
$url = “http://www.mysite.com/temp-xml/”.$myfeed;

// write all code here
$dom = new DOMDocument;
$dom->load($url);
// use the above to load an xml file on server or below to load the api. Both run in less than 1/10 second
//@$dom->loadHTML($file);

foreach ($dom->getElementsByTagname(‘result’) as $result) {
$date = $result->getElementsByTagname(‘date’);
$date_text_value = $date->item(0)->firstChild->nodeValue;
       
// indeed url
//$myurl = $result->getElementsByTagname(‘url’);
//$myurl_value = $myurl->item(0)->firstChild->nodeValue;
$myurl = $result->getElementsByTagname(‘jobkey’);
$myurl_value = $myurl->item(0)->firstChild->nodeValue;
$jobtitle = $result->getElementsByTagname(‘jobtitle’);
$jobtitle_value = $jobtitle->item(0)->firstChild->nodeValue;
$source = $result->getElementsByTagname(‘source’);
$source_value = $source->item(0)->firstChild->nodeValue;
$snippet = $result->getElementsByTagname(‘snippet’);
$snippet_value = $snippet->item(0)->firstChild->nodeValue;
//print “$date_value.$source_value \n”;

//create an array from the values which can be combined with other feed sources
$myarray[] = array(“link” => “$href”, “title” => “$jobtitle_text_value”, “source” => “$source_text_value”, “description” => “$snippet_text_value”, “date” => “$dateString”);
}

Making Dynamic Page Titles with PHP

You can use the variable $page_title in the head of the header.<title><?php echo $page_title; ?> </title>

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

//get the route
$findme   = ‘mysite.com/category/subcategory’;
//make sure the path is in the url
$pos = strpos($my_url, $findme);
//echo $pos;
if ($pos==true){
//echo $my_url;
//just grab the unique id of the article
$my_url_trimmed = str_replace(“http://www.mysite.com/category/subcategory/”, “”, $my_url);
//echo $my_url_trimmed;
//query the database and find the data you want for the page title
$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)) {
//make the new page title
$space=” “;
$gap=” | “;
$location=$row[“col1”];
$page_title= $row[“col2”].$space.$location.$gap;

}

}
}


Writing and Moving a PHP File with fopen and fwrite

Using php copy() and rename() functions are two such methods to copy and rename php files. However, fopen() and fwrite() functions can alos do the trick. The example below is a method regarding how to copy, move and rename a php file. In this case, the template file and the copied file with a new name exist in the root directory.

 
<?php
// Here we get the source file
$file = file_get_contents(‘page_template.php’, true);
$ext=”.php”;
$url=”urlname”;
//This makes a name like mysite.com/myurl.php
$mytitle=$url.$ext;
//opens or creates the file here with the desired name   
$fh = fopen($mytitle, ‘w’);
//writes the file page_template.php to the new file name
fwrite($fh, $file);
fclose($fh);?>

Image Uploads and Resizing with PHP

You’ve added images everywhere before in sites like facebook and MSN. The procedure is fairly straightforward to open an image, resize the image, rewite the image and save the new image. Below is a siomple tutorial with a form showing how to add a resized image into a form.

<?php
require “connect.php”;
$db=connect();
//only resize images if form is filled in properly
if ($_POST[‘FirstName’] && $_POST[‘LastName’] ) {// file must be jpg, gif, png and maximun 1 MB
if (($_FILES[“img_upload”][“type”] == “image/jpeg” || $_FILES[“img_upload”][“type”] == “image/pjpeg” || $_FILES[“img_upload”][“type”] == “image/gif” || $_FILES[“img_upload”][“type”] == “image/x-png”) && ($_FILES[“img_upload”][“size”] < 1000000))
{
// some settings
$max_image_width = 2592;
$max_image_height = 1944;

// if user chosed properly then scale down the image according to user preferences
if(isset($_REQUEST[‘max_img_width’]) and $_REQUEST[‘max_img_width’]!=” and $_REQUEST[‘max_img_width’]<=$max_image_width){
$max_image_width = $_REQUEST[‘max_img_width’];
}
if(isset($_REQUEST[‘max_img_height’]) and $_REQUEST[‘max_img_height’]!=” and $_REQUEST[‘max_img_height’]<=$max_image_height){
$max_image_height = $_REQUEST[‘max_img_height’];
}

// JPEGs
if($_FILES[“img_upload”][“type”] == “image/jpeg” || $_FILES[“img_upload”][“type”] == “image/pjpeg”){
$image_source = imagecreatefromjpeg($_FILES[“img_upload”][“tmp_name”]);
}
// GIFs
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”]);
}

$remote_file = “my_uploaded_images/”.$_FILES[“img_upload”][“name”];
imagejpeg($image_source,$remote_file,100);
chmod($remote_file,0644);

// get the dimensions in width and height of orig image
list($image_width, $image_height) = getimagesize($remote_file);

if($image_width>$max_image_width || $image_height >$max_image_height){
$proportions = $image_width/$image_height;

if($image_width>$image_height){
$new_width = $max_image_width;
$new_height = round($max_image_width/$proportions);
}
else{
$new_height = $max_image_height;
$new_width = round($max_image_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{

}
?>

HTML CODE HERE

<form name=”form1″ method=”post” action=”<?php echo  $_SERVER[‘SELF’];?>” enctype=”multipart/form-data”>

Maximum 1MB. Accepted Formats: jpg, gif and png:<br />
<input name=”img_upload” type=”file” id=”img_upload” size=”40″ />

<br />
<br />
<br />
<input name=”max_img_width” type=”hidden” id=”max_img_width” value=”130″ size=”4″>

<input name=”max_img_height” type=”hidden” id=”max_img_height” value=”54″ size=”4″>

<tr>
<td >First Name</td>
<td><input name=”FirstName” value=”” type=”text” id=”FirstName”></td>
</tr>
<tr>
<td>Last Name </td>
<td ><input name=”LastName” value=”” type=”text” id=”LastName”></td>
</tr>

<p><input type=”submit” class=”form_submit_button” onclick=”display_alert()” name=”Submit” value=”Submit”>
</p>

</form>

You may want to add the image name to a database table for other purposes; such as a user’s profile picture. Below, shows how this can be done.

You can add this above the form!

$ip=$_SERVER[‘REMOTE_ADDR’];
if (!$remote_file){
//here is a dummy image if they upload no image
$emp_filename=”dummy_image.jpg”;
} else {
$emp_filename=$remote_file;
$emp_filename=str_replace(‘my_uploaded_images/’, ”, $emp_filename);
}
$command = “INSERT INTO table VALUES (NULL, ‘$ip’, now() , ‘0000-00-00 00:00:00’,  ‘$emp_filename’)”;
$result = mysqli_query($db, $command);

If you use php long enough, you will want to concatenate php strings in echo and print statements, or as new strings.Here is a simple example showing how to combine simple strings into a new, larger string.

$my_first_variable=”.php”;
$my_second_variable=”filename”;
$my_new_third_variable= $my_first_variable.$my_second_variable;

echo $my_new_third_variable;

output:
filename.php

 


PHP Print_r();

The function to see the output of an array, print_r($my_array); is a php and mysql database programmers best friend. Normally, examining the array will help in determining how an error was made in programming a query.

For example, duplicate or unsuspected values could result if one of the values in the array is not clearly defined. Imagine an instance for which you select an id, but not a specific id. Therefore, the array could output everything you wanted, but made 3 duplicate rows since the exact user_id was not identified in a WHERE condition or it was not necessary to have in the array.

Such array issues could occure in situations where you make a join by selecting data from 2 or more databse tables. If you select a column which is not used and could contain various auto_incremented IDs, your output could be 3 identical table rows with 3 indexed arrays. Since the one ID from was not clearly defined in one of the tables.

Here is an example:
$username=”Mike”;

“SELECT tb1.id, tb1.username, tb1.email, tb1.date, tb2.username, tb3.adminid from tb1 as tableone, tb2 as tabletwo, tb3 as table3 WHERE (tb1.username=tb2.username AND tb1.username=’username’) order by date DESC”;

With this query above, we would get the results we wanted which was the username and email for Mike. But, if tb3.adminid had 3 entries, there would be 3 indexed arrays with identical arrays.

Since there was no use for tb3.adminid, it would be best to leave it out of the query.

Alternatively, the query could have been written:

“SELECT tb1.id, tb1.username, tb1.email, tb1.date, tb2.username, tb3.adminid from tb1 as tableone, tb2 as tabletwo, tb3 as table3 WHERE (tb1.username=tb2.username AND tb1.username=’$username’ AND tb3.adminid=’$username’) order by date DESC”;

In the second query, the foreign key tb3.admin matched with other keys; thus only record was returned.


Destroy Cookie PHP

To remove a cookie from the browser,
1) Set a date that is expired.
The setCookie() function below creates a cookie with a date in the past; thus it is eliminated.
setcookie(“my_cookie”, $var, time()- 7200, “/”);

The setCookie() function below creates a cookie with a date at that instant; thus it is gone virtually the same time it is created.
setcookie(“firstnm”, $firstname, time() + 0, “/”, ‘.mysite.com’);


PHP Cookies for Entire Domain

A problem that exists when setting cookies is accessing the cookies on various urls such as: mydomain.com, http://mydomain.com and http://www.mydomain.com

Unfortunately, if you want a cookie(s) to be accessible on all directories in the domain regardless of what is inserted into the browser, you need to set the cookie properly.

For example, if a cookie is set on a url like mydomain.com, it can be accessed on any other page in the domain if the address in the browser began with mydomain.com (ie. mydomain.com/directorya). The code for this example is:
setcookie(“my_cookie_name”, $var, time()+ 14400, ‘/’, ‘.mysite.com’);

But, if you want to access the cookie no matter how the url is presented in the browser, you would use:
setcookie(“my_cookie_name”, $var, time()+ 14400, ‘/’, ‘.mysite.com’);

The latter code above sets a cookie called my_cookie_name that remains usable for 2 hours. If you wanted to pull the data from the cookie it would actually be the value $var. 


PHP Cookies

Cookies are stored in the browser. They have many uses since they can timeout at certain intervals and contain identifiable names. Programmers may use them to store variable data for usage elsewhere, or for page access. 

When a cookie is written to the browser, name, content and the path can be set. 

setcookie(“cookie”, “variable_or_text”, time()+ 7200, “/”) can be used in all directories due to the foreward slash “/”
while
setcookie(“cookie”, “data_output”, time()+ 7200) can be used in the residing directory on the website.

The code below takes a variable($email_address) and uses it as the cookie ‘Content’. 

setcookie(“email”, $email_address, time()+ 7200, “/”);

If you echo the cookie in the future like:
value=”<?php echo $_COOKIE[’email’]; ?>” ///the output will be the data_output with a real email address.


PHP Microtime Benchmark

Use microtime() to calculate how long it takes to run code:

$timer_start = microtime(true);

// write all code here
$function1= myfunction();
$class = newClass;

$timer_end = microtime(true);
$elapsed_time = $timer_end – $timer_start;

echo “This ran for $elapsed_time seconds”;
mysql_close();


MYSQL TIMESTAMPDIFF To Compare Dates

Below is a mysql query which joins 3 tables and outputs data that had been inserted into the database within 2 hours(120 minutes) time difference. In the following case, the 2 hour time difference had been checked between 2 tables. The mysql function TIMESTAMPDIFF() was used to compare the dates. The function compares 2 columns and can be used to compare minutes, dates and years. In our case, we used minutes. TIMESTAMPDIFF(minute, columna, columnb)

“select tbnm1.question, tbnm1.answer, tbnm1.firstname, tbnm1.email, tbnm1.lastname, tbnm1.representative, tbnm1.time, tbnm2.score, tbnm2.firstnm, tbnm3.helpText, tbnm2.DateReceived, TIMESTAMPDIFF(MINUTE,tbnm1.time,tbnm2.DateReceived) AS minutes, from prefix_tbnm3quiz_written as tbnm1, prefix_tbnm3quiz_1 as tbnm2, prefix_tbnm3quiz as tbnm3 WHERE tbnm3.question=tbnm1.question AND (TIMESTAMPDIFF(MINUTE,tbnm1.time,tbnm2.DateReceived)>-120 OR TIMESTAMPDIFF(MINUTE,tbnm1.time,tbnm2.DateReceived)<120) AND (tbnm1.email=tbnm2.emailaddress OR (tbnm1.firstname=tbnm2.firstnm AND tbnm1.lastname=tbnm2.lastname)) ORDER BY time DESC”;


Set Cookie PHP

Setting cookies with PHP is a decent method to keep a way to identify a user between pages. For example, if you set a cookie on a Joomla component and checked to see the cookie in another page, you could do an if statement to make sure the cookie was in the browser before the user could view the page.

To set a cookie for the current page,

//This cookie will be stored as written and will last 60 seconds * 60 minutes = 3600 milleseconds
setcookie(“written”, “loaded”, time()+ 3600)

To set a cookie for the entire web site and directories,
//This cookie will be stored as written and will last 60 seconds * 60 minutes = 3600 milleseconds
setcookie(“written”, “loaded”, time()+ 3600, “/”)

IP Address

To add the user’s ip address into the database,

1) Make an ip variable.
$ip=$_SERVER[‘REMOTE_ADDR’];
echo “IP Address= $ip“;

2) Check to see the variable upon clicking submit
if (isset($_POST[‘submit’]){
echo $_POST[‘ip’];
}

3) Make a hidden post variable to post the ip
<input type=”hidden” name=”ip” value=”<? echo $ip;?>/>

4) Insert the $_POST[‘ip’] into the database when the form is submitted.
“INSERT INTO tablename id, ip VALUES (NULL, ‘$_POST[‘ip’])”;

Changing Background Color for Rows from Database

When you select an array from the database, you may want to output each row to list items or table rows. Either way, the data for each list item or table row will look identical unless you specify otherwise.

The examples below shows how to alter the color for each list item from the database.

$background= ‘#CFCFCF’;?>
<ul id=”ul” ><?
while (list($key, $this_entry) = each($entry_array)) {
$background =($background==’#CFCFCF’ ? ‘#ffffff’ : ‘#CFCFCF’);
?><li style=”padding:10px 10px 10px 10px;background:<?php echo $bg;?>”>

or

$background= ‘#CFCFCF’;?>
<ul id=”ul” ><?
$command = “SELECT id,catid,question, question_type FROM table1 WHERE question_type=’3′ and table1.catid=3 ORDER BY RAND() LIMIT 3″;
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$background =($background==’#CFCFCF’ ? ‘#ffffff’ : ‘#CFCFCF’);
?><li style=”padding:10px 10px 10px 10px;background:<?php echo $bg;?>”>


PHP LEFT (Outer) Joins

Inner joins will select data and return all entries which match

To use a left join or outer join,
1) SELECT * FROM table1 LEFT JOIN table2 ON table2.id=table1.id;

With LEFT JOIN, the first table of the statement is critical. If the first table in the statement has 5 entries, 6 entries would have been selected. But, if tbe first table selected had 6 categories it would show all six entries.


PHP inner Joins

When using relational databases and SELECTING data from more than one table, using joins is the answer to make ideal queries.Two options are to use an inner join or LEFT JOIN. The inner join will select data and return results for all rows that match while an OUTER JOIN or LEFT JOIN will show all entries; even those which exist in 1 table, but not in the other. Depending on circumstances, one of the joins is the ideal usage. For example, let`s assume 2 tables share the same category id. One table has 6 categories that match six of seven categories of the second. An inner join will retrieve the 6 matching categories while the LEFT or OUTER JOIN will select 7 categories. However, in the case of the LEFT JOIN, the first table sets the stage. If the table with 6 entries was the first called in the statement only 6 entries would have been selected and matched but if the table with 7 categories was selected first it would show all seven entries.

To use an inner join,
1) SELECT * FROM table1, table2 WHERE table1.id=table2.id;

To use a left join or outer join,

1) SELECT * FROM table1 LEFT JOIN table2 ON table2.id=table1.id;

PHP adding a String To Every Entry in a Specified Column

There may be time when you want to add a number or letter to the beginning or end of every entry in a column. For example, a csv file from excel may have omitted the beginning digit 0.

To add a string to each entry in a specific column or tuple,
UPDATE Tablename SET column = Concat(‘0’, column);

Making an Array from a String and Looping the New Array

//make array function
function explode_to_array($text) {
if ($text) {
$_arr = explode(“,”, $text);
if ($_arr)
$_arr = array_map(“trim”, $_arr);
return $_arr; } return false; }
//string $imgNames = “one,2,3,4”;
$imgCaptions = “caption1,caption2,caption3,caption4”;
$imgLinks = “link1,link2,link3,link4”;
//make an array from the string
$imgs = explode_to_array($imgNames);
// get images ALTs array $caps = explode_to_array($imgCaptions);
//get images links array $links = explode_to_array($imgLinks);
// construct images content
$i = 0;
if ($imgs) {
foreach ($imgs as $item) { 
if ($i >0) $class = ” class = ‘hide_images'”;
$slideshow_content =”<div $class><a href='”.$links[$i].”‘><img src='”.$imgFolder.$item.”‘ alt='”.$caps[$i].”‘ width=’$modwidth’ height=’$modheight’/></a><p >”.$caps[$i].”</p></div>”;
        $i++;
    }
    }

<div id=”bogallery”>
       
             <?php echo $slideshow_content;  ?>           
       
  </div>


PHP !EMPTY FUNCTION

The !empty() function checks to see if a variable is empty or set. The !empty() function is commonly implemented with if and else conditional statements while using $_POST variables in a form. Its usage is very similar to the isset() function. For example, if the name field is !empty within a form a statement is executed, otherwise, an error is prompted.

if (!empty($name)){
do this
}
else {
echo “Please enter your name!”;
}

PHP EMPTY FUNCTION

The empty() function checks to see if a variable is empty or set. The empty() function is often used with if and else conditional statements for $_POST variables in a form. For example, if the name field is empty within a form, an error could be prompted.

if (empty($name)){
echo “Please enter your name!”
}
else {
do this
}

PHP ISSET

The isset() function checks to see if a variable is set. The isset() function is often used with if and else conditional statements for $_POST variables in a form. For example, if the name field is missing in a form, an error could be prompted.

if isset($name){
do this
}
else {
echo “Please enter your name!”
}

PHP Array To A Table

$query = “SELECT * FROM table1, table2 WHERE table1.artist_id = table2.artist_id ORDER BY table1.last_name ASC”;

echo ‘<div style=”text-align:center; margin-left:15%;margin-right:15%;”><table border=”0″ width=”400px” cellspacing=”3″ cellpadding=”3″ align=”center” >
<tr>
<td align=”left” width=”20%”><b>Artist</b></td>
<td align=”left” width=”20%”><b>product Name</b></td>
<td align=”left” width=”20%”><b>Description</b></td>
<td align=”left” width=”30%”><b>Image Name</b></td>
<td align=”right” width=”10%”><b>Price</b></td>
</tr>’;

// Display all the URLs.
$result = mysqli_query ($db, $query);
while ($row = mysqli_fetch_assoc ($result)) {

// Display each record.
echo ”    <tr>
<td align=\”left\”><a href=\”browse_products.php?aid={$row[‘artist_id’]}\”>{$row[‘last_name’]}, {$row[‘first_name’]} </a></td>
<td align=\”left\”><a href=\”view_product.php?pid={$row[‘product_id’]}\”>{$row[‘product_name’]}</td>
<td align=\”left\”>” . stripslashes($row[‘description’]) . “</td>”;?>
<td align=”left”><? echo “<a href=\”view_product.php?pid={$row[‘product_id’]}\”>”; ?> <img src=”admin/myuploads/<? echo stripslashes($row[‘image_name’]); ?> “/></a></td>
<? echo ” <td align=\”right\”>\${$row[‘price’]}</td>
</tr>\n”;

} // End the while loop.

echo ‘</table></div>’; // Closing the table.

MYSQL FETCH ARRAY

$host = “localhost”;
$user = “root”;
$pw = “”;
$database = “test”;
$db = mysqli_connect($host, $user, $pw, $database) or die(“Cannot connect to mySQL.”);

//$sql = “SELECT * FROM table1”;
//$result = mysqli_query($db, $sql);
$command = “SELECT * FROM table1”;
$result = mysqli_query($db, $command);
//see the array of what is there
//print_r(mysqli_fetch_assoc($result));
if($row = mysqli_fetch_array($result)/*mysqli_fetch_assoc($result)*/) {
//SET UP VARIABLES
$id = $row[‘id’];
$column2 = $row[‘column2’];
$column3 = $row[‘column3’];
$column4 = $row[‘column4’];
$column5 = $row[‘column5’];
$column6 = $row[‘column6′];
echo “Column 2 is: “.$column2;
#check to see if entered
if($column6 == “”){
//column titles
if($column4 == “This Text”){
$column6 = “New Text”;
}
if($column4 == “This Different Text”){
$column6 = “Different New Text”;
}
//update table
$sql = “UPDATE table SET column6=’$column6’ WHERE id=’$id'”;
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
}
}


How To Make a CMS

With so many content management systems available, you may wonder why spending many hours to build a custom cms is a worthy option. Firstly, the reusability of a CUSTOM CMS can speed up web development in many cases.

A custom CMS is built with server side languages such as php/mySQL. The backbone behind a CMS is CRUD, which stands for create, read update and delete. For a very small cms with limited pages, deleting may not be necessary. On a very simple level, administrators can login and make any changes to the website while web surfers will see selected data from the database. For all web usage, there will be a connection to the database for which the administrator has create, read, update and delete privileges while web surfers  can only select data.

When making a custom cms, you can have a login file which rediirects or links the administrator to the file(s) which creates, updates or deletes data for one or various pages. All in all, making a cms can be a handful of files which should be lightning fast. The job is really for an individual with adequate php/mySQL knowledge since database design and creating the cms can take many hours of decent coding and testing. But, the result is the ability to make a website with your own editor. Furthermore, it is a starting point to add many pre-xisiting php scripts or more custom scripts like shopping carts, etc. Using a lightweight cms will significantly cut down on server resources.

Using a Custom CMS vs a Open Source CMS

When would I use an open source cms like Joomla or WordPress vs my own?
If the development time is faster, using an open source cms could be the solution. However, if you do not find an appropriate solution like an updatable cms for all mobile devices and want to include a fast, simple Paypal shopping cart for all devices, creating a custom cms with a lightning fast shopping cart could be the best option. Although many open source cms may have an answer to browsing the web on a pc, mobilizing the site is another issue; especially when it comes to using extensions.

A custom cms could also be diversified and used with PHP Frameworks too. The Framework could be dumped into the website and use the same template and / or database. The options to building and using a  custom cms are endless.

Using PHP for MYSQL Queries

There may come a when you want to write a custom PHP script to access one or more database tables. Even with content management systems like WordPress or Joomla, you can write custom search scripts.

If you add an .htaccess file within a folder that contains the PHP script,  you can limit access to a single Internet IP addess. Alternatively, you can password protect the directory with the .htaccess file.

PHPMYADMIN allows you to use, alter, add, modify, create, delete and dump databases just as though you could with the mysql command prompt.

If you use phpmyadmin, you may often use it to access data. You may access data for content management systems such as Joomla, or stand-alone PHP scripts. Using phpmyadmin is fast. When accessing data with phpmyadmin, you can sort queries by order descending (most recent first) or order ascending (oldest first). Otherwise, you can always run a search query with SQL; such SELECT * from posts where username=username;

To add a column to a database table with mySQL,

1) Open phpmyadmin or mysql prompt.
2) Open desired database.
3) Type: ALTER TABLE contacts ADD email VARCHAR(60) AFTER name;
Note: This will add a column after the column named name.
or
Type: ALTER TABLE contacts ADD email VARCHAR(60) FIRST;
Note:This will add the column email to the beginning of the table. This is not recommended if the table has an auto_incremented id column.
or
Type: ALTER TABLE contacts ADD email VARCHAR(60);
Note: This will add the column email to the end of the table. All new columns will automatically be inserted to the end of the table unless specified otherwise.

While creating or upgrading a php script, there is often a time when you want to find the last inserted id with mysql. The purpose is to get that id from the database and make it a variable for another database query.

The code to acquire the last inserted id of an auto_incremented id in a database table is to call the function:

$get_my_last_id = mysql_insert_id($dbc);

Finding out what version your browser is with php is required if you want to make custom conditions for a specific browser or various browser versions.

To find the version,
1) //Make a variable for the browser which is being used.
$browser = $_SERVER[“HTTP_USER_AGENT”];
2) // Print the browser to the page to display the required information.
echo $browser;
3) //Set a condition for the browser.
i.e. if ($browser == ‘Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1’ || $browser == ‘Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.0’ ) {
        $qty = 1;
    }

Searching for specific strings of text with PHPMYADMIN or the MYSQL command prompt is a very fast way to find rows in tables for which you want to find specific pieces of data. For example, let’s assume you have a very long database table and you want to find all users that share one particular IP address or all names in a table for which a user is called John.

To search PHPMYADMIN for strings of text,

1) Open up the specific database with php myadmin.

2) Select Search
3) Add the word to search from the desired column.

4) Select Browse

At this point, you can open up Firefox and find the exact location.

To find the desired text with a query,
1) Use mysql command prompt or select sql with PHPMYADMIN.
2) Add the following code.

SELECT * FROM `myname_accomodationbc`.`abccontent`
WHERE `database_column` LIKE ‘%name%’;

When you use a content management system like Joomla and WordPress you can use components, modules, extensions, php frameworks and pure php/mysql.

Adding Pure PHP / MYSQL
The content management systems have many available templates and extensions, but, there may be times when you have a stand-alone php/mysql application that you want to add, but not recode into an extension. You just want to add it quick.

To add a pure php / mysql application you simply copy and paste the application inside the root directory. The index.php file could be accessed like mysite.com/socialbookmarks/index.php. The url could be added to the main menu of the content management system. The urls for each file of the new application could use absolute or relative urls; like join.php or http://mysite.com/bookmarks/join.php.

To finalize the application, you can dump the database schema into the existing database for the CMS, or use a different database. The application can use the same stylesheet too if an absolute url is used to link the stylesheet.

To keep it simple and use a php / mysql cms you can try Sitemakin CMS.


Single or Multiple Databases

For any database driven website, the database is a backbone that must remain secure. That now leaves the question whether or not to use one database or multiple databases? The school that invented the first Apache server, first website and is still amongst the top computer programming schools in the United States had me convinced that more databases is a better option since it made for better overall security of data; especially if backed up elsewhere. Personally, I like one website to have at least one database. One is often more than enough. But, if you decided to use 2 frameworks for 1 website, 2 could be the better option. Multiple databases is one area where Drupal excels. Some people like using 1 database for their various installations. One downside to this could be that someone with access to the database could alter it in such a way that it ruins things for everyone. Imagine every client not being able to login. If a clever hacker had you make his website with Drupal and he requested a backup upon payment, you might want to think about him having his own database since the connection username, password and database name may be the same, especially with shared hosting.

Anyways, like a good boy, I believed that all files, 1 database with specific passwords per site and backed up sql files and a good log file is quite good to ensure the sites can stay up and running. Keeping all the files in the public_html folder for each website with the databases can allow for quick recovery. And, always expect the worst so that you can fix the mess if you must.

For most languages that do not use special characters, the default mysql settings will work fine creating and using mysql database tables. However, they can be created and modified to accept other characters like

Using PHP to redirect pages based on browser can make life simpler in some circumstances. The following samples below show various redirects for various browers.

if(preg_match(“/opera/i”,$_SERVER[‘HTTP_USER_AGENT’]))
die(header(“Location: http://getfirefox.com”));
?>
 
<?php
if(preg_match(“/chrome/i”,$_SERVER[‘HTTP_USER_AGENT’]))
die(header(“Location: http://getfirefox.com”));
?>
 
<?php
if(preg_match(“/safari/i”,$_SERVER[‘HTTP_USER_AGENT’]))
die(header(“Location: http://getfirefox.com”));
?>
 
<?php
if(preg_match(“/MSIE/i”,$_SERVER[‘HTTP_USER_AGENT’]))
die(header(“Location: http://getfirefox.com”));
?>
 
<?
$redirect=”http://www.redirecturlputhere.net”;
if(preg_match(‘/Firefox/’,$_SERVER[‘HTTP_USER_AGENT’]))!
=1) header(“Location: “.$redirect);
?>

Using the mysql query cache can enable the website to grab the queries from a cache rather than having to query the database over and over again. Grabbing the data can work for ‘SELECT’ statements. To enable the query cache, the administrator needs root access. Root access can be aquired with Putty or some other SSH tool.

To see what variables are present in the mysql query cache;
mysql> show variables like ‘query%’;
Look next to query_cache_size and see its value. The value 0 means it is not enabled. A value like 2,000,000 is 2 mb.

To set the query cache to 2 mb;
mysql> set global query_cache_size=20000000;

To see info about the query cache like the amount of free memory and number of queries
mysql> show status like ‘qc%’;

To dump the cache is as easy as setting the global query_cache_size to 0 then setting it to a new value.

Depending upon the default settings, the query cache may be enabled or disabled. To see if query_cache_type is enabled,
mysql> show variables like ‘query%’;

The 0 value is enabled. To enable it,
mysql> set global query_cache_type=1;
or
mysql> set global query_cache_type=2;

If the number does not change, it could be that you logged in with an updated administrator password, rather than the mysql password. To fix this, login to the server with SSH, then, type
$ mysql -u root

Whether you need to get through school or you need to modify a commerce application, adding columns into mySQL is something that must be done to custom tweak databases.

The following 3 commands can be used in at the mysql prompt or made with an sql query with phpmyadmin.

ALTER TABLE mytable add column newcolumn varchar (20);
ALTER TABLE mytable ADD newcolumn VARCHAR(25) AFTER secondcolumn;
ALTER TABLE mytable ADD newcolumn VARCHAR(25) FIRST;

Alternately, the column can be added with php my admin. Just add the custom field(s) and attributes and click Go.