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

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

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

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

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

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

 

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

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

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

 

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

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

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

 

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

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

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

GRUNT

Install Grunt and usage

1. Install the command-line interface

npm install -g grunt-cli

 

2. With the command line, navigate to the folder where you want to run grunt; such as a web application or website folder.

cd myfoldername

 

3. Install Grunt locally

npm install grunt –save-dev

 

4. Make a simple grunt file called gruntfile.js

module.exports = function(grunt) {
    grunt.initConfig({
    jshint: {
      files: ['test.js'],
      options: {
        globals: {
          jQuery: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['jshint']);
  console.log('File Changed');

};

 

5. Make a simple package.json file or run the command ‘npm init’ to make it from the command line. Below is an example of a package.json file with all desired and required dependencies.

{
  "name": "Test-Project",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-concat": "~0.1.3",
    "grunt-contrib-jshint": "^1.0.0",
    "grunt-contrib-uglify": "^2.0.0",
    "grunt-contrib-watch": "^1.0.0",
    "grunt-livereload": "^0.1.3"
  }
}

 

Here is how dependencies can be installed.

npm install grunt-contrib-jshint –save-dev
npm install grunt-contrib-watch –save-dev
npm install grunt-livereload –save-dev

 

GULP
Here is how to get up in running with Gulp.

Install globally just as you would Grunt.

npm install -g gulp

 

Go to desired folder.

cd myfoldername

 

Create a simple package.json file or run the command ‘rpm init’ to create it in the command line. See sample package.json file below.

{
  "name": "test",
  "version": "0.1.0",
  "devDependencies": {
  }
}

 

Install Gulp locally

npm install gulp –save-dev

 

Create a file called gulpfile.js and add your desired task(s). Sample gulpfile shown below.

var gulp = require('gulp');

livereload = require('gulp-livereload');

gulp.task('watch', function () {
    livereload.listen();
    
    gulp.watch('test/*.html').on('change', function(file) {
        livereload.changed(file.path);
        console.log('File Changed');
        gutil.log(gutil.colors.yellow('HTML file changed' + ' (' + file.path + ')'));
    });
});

 

Add required dependencies. Doing this will automatically modify package.json too.

npm install gulp-concat –save-dev
npm install –save-dev gulp-livereload
npm install gulp-uglify gulp-rename –save-dev

 

Here is how package.json will look after dependencies are installed.

{
  "name": "my-project",
  "version": "0.1.0",
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.0",
    "gulp-livereload": "^3.8.1",
    "gulp-watch": "^4.3.9"
  }
}

 

Le’t run the watch task and see the console change when any html file in the test folder is modified.

gulp watch

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

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

 

Method A

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

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

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

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

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

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

 

Method B

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

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

        width = $(window).width();

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

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


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

});

 </script>

 

Method C

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

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

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

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

 

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

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

        width = $(window).width();

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

        }


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

    });

</script>

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

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

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

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

Service Methods

Factory and Service Method

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

Naming Conventions

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

Controller

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

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

Ending Statements

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

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

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

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

Call the Function In HTML

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

 

The Actual Function in the Javascript

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

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

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

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

 

CONTROLLERS

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

 

Global Controller

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

 

Using Angular Namespace, module function and controller function

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

 

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

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

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

 

HTML

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

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

</body>

 

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

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

 

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

<body ng-app=”myAppName” >

<div ng-controller=”myController”>

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

</div>

<div ng-controller=”secondController”>

Add custom stuff here

</div>

</body>

 

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

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

How It Works

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

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

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

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

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

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

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

 

CSRF Class

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

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

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

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

}

 

Top of File

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

 

Form

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

</div>

 

Angular Code

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

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

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

        $scope.check_credentials = function () {

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

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

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

            var request = $http({

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

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

            });

        }

    });

</script>

 

PHP Code

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

$session_array = $_SESSION['csrfs'];

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

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

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

$_SESSION = array();

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

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

Step # 1 Installation

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

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

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

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

Step #2 Using the Framework

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

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

Open this file and add the following code.

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

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

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

<?php
namespace App\Http\Controllers;

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

class TestController extends Controller
{
    public $restful = true;

    public function get_index()
    {

        $title = "My Test Title";

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

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

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

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

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

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

        }
    }

}

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

View Files

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

<html>

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


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

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

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

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


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

@endsection

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

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

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

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

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

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

Method #1: WordPress backend

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

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

Method #2: Files From Directory

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

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

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

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

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

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

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

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

    <script type="text/javascript">

        $(document).ready(function () {

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

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

                $.ajax({

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

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

                    }

                });

            });

        });

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

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

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

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

</body>
</html>

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

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

$PDO = PDO_Connect();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Changing Posts

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

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

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

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


PHP, Jquery and Ajax Tutorial

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

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

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


How is a typical Ajax Request Performed?

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

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

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

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

Example #1

Overview

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

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

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

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

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

Main File

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


<script type="text/javascript">

$(document).ready(function () {

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

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

$.ajax({

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

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

}

});

});

});

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

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

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

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

</body>
</html>

Ajax File

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

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

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

Example #2

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

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

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

Main File

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


<script type="text/javascript">


$(document).ready(function () {

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

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

$.ajax({

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

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

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

});

});

});

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

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

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

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

</body>
</html>

Ajax File

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

Example#3

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

Main File 

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


<script type="text/javascript">


$(document).ready(function () {

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

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

$.ajax({

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

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

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

});

});

});

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

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

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

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

</body>
</html>

Ajax File

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

Ajax Security

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

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