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

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