# PHP, Javascript & HTML

All about PHP, JS and HTML including its frameworks

# Useful PHP Codes

### Increment a Date by Month, Day or Year

**Increment by month**

- 1. ```
        <span class="pln">$time = strtotime("2014-12-11");<br></br>$d = date("Y-m-d", strtotime("+1 month", $time));</span>
        ```

**Increment by day**

1. ```
    <span class="pln">$time = strtotime("2014-12-11");<br></br>$d = date("Y-m-d", strtotime("+1 day", $time));</span>
    ```

**Increment by year**

1. ```
    <span class="pln">$time = strtotime("2014-12-11");<br></br>$d = date("Y-m-d", strtotime("+1 year", $time));</span>
    ```

### Verify Email Accounts

```
<?php<br></br>function verifyEmail($toemail, $fromemail, $getdetails = false)<br></br>{<br></br>    $email_arr = explode("@", $toemail);<br></br>    $domain    = array_slice($email_arr, -1);<br></br>    $domain    = $domain[0];<br></br>    // Trim [ and ] from beginning and end of domain string, respectively<br></br>    $domain    = ltrim($domain, "[");<br></br>    $domain    = rtrim($domain, "]");<br></br>    if ("IPv6:" == substr($domain, 0, strlen("IPv6:"))) {<br></br>        $domain = substr($domain, strlen("IPv6") + 1);<br></br>    }<br></br>    $mxhosts = array();<br></br>    if (filter_var($domain, FILTER_VALIDATE_IP))<br></br>        $mx_ip = $domain;<br></br>    else<br></br>        getmxrr($domain, $mxhosts, $mxweight);<br></br>    $details = '';<br></br>    if (!empty($mxhosts))<br></br>        $mx_ip = $mxhosts[array_search(min($mxweight), $mxhosts)];<br></br>    else {<br></br>        if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {<br></br>            $record_a = dns_get_record($domain, DNS_A);<br></br>        } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {<br></br>            $record_a = dns_get_record($domain, DNS_AAAA);<br></br>        }<br></br>        if (!empty($record_a))<br></br>            $mx_ip = $record_a[0]['ip'];<br></br>        else {<br></br>            $result = "invalid";<br></br>            $details .= "No suitable MX records found.";<br></br>            return ((true == $getdetails) ? array(<br></br>                $result,<br></br>                $details<br></br>            ) : $result);<br></br>        }<br></br>    }<br></br>    <br></br>    $connect = @fsockopen($mx_ip, 25);<br></br>    if ($connect) {<br></br>        if (preg_match("/^220/i", $out = fgets($connect, 1024))) {<br></br>            fputs($connect, "HELO $mx_ip\r\n");<br></br>            $out = fgets($connect, 1024);<br></br>            $details .= $out . "\n";<br></br>            <br></br>            fputs($connect, "MAIL FROM: <$fromemail>\r\n");<br></br>            $from = fgets($connect, 1024);<br></br>            $details .= $from . "\n";<br></br>            fputs($connect, "RCPT TO: <$toemail>\r\n");<br></br>            $to = fgets($connect, 1024);<br></br>            $details .= $to . "\n";<br></br>            fputs($connect, "QUIT");<br></br>            fclose($connect);<br></br>            if (!preg_match("/^250/i", $from) || !preg_match("/^250/i", $to)) {<br></br>                $result = "invalid";<br></br>            } else {<br></br>                $result = "valid";<br></br>            }<br></br>        }<br></br>    } else {<br></br>        $result = "invalid";<br></br>        $details .= "Could not connect to server";<br></br>    }<br></br>    if ($getdetails) {<br></br>        return array(<br></br>            $result,<br></br>            $details<br></br>        );<br></br>    } else {<br></br>        return $result;<br></br>    }<br></br>}<br></br><br></br>//Sample usage:<br></br>print_r(verifyEmail('<to email>', '<from email>'));
```

### Calculate Coordinate Distances

```
function getDistance( $latitude1, $longitude1, $latitude2, $longitude2 ) {  <br></br>    $earth_radius = 6371;<br></br><br></br>    $dLat = deg2rad( $latitude2 - $latitude1 );  <br></br>    $dLon = deg2rad( $longitude2 - $longitude1 );  <br></br><br></br>    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);  <br></br>    $c = 2 * asin(sqrt($a));  <br></br>    $d = $earth_radius * $c;  <br></br><br></br>    return $d;  <br></br>    }<br></br><br></br>    $distance = getDistance( 56.130366, -106.34677099999, 57.223366, -106.34675644699 );<br></br>    if( $distance < 100 ) {<br></br>        echo "Within 100 kilometer radius";<br></br>    } else {<br></br>        echo "Outside 100 kilometer radius";<br></br>    }<br></br>}
```

# Standard PHP/JS/HTML Procedures

### Updating PHPUnit to Version 3.7

```
sudo mv /opt/lampp/lib/php/PHPUnit /opt/lampp/lib/php/PHPUnit.bak<br></br>curl -sS https://getcomposer.org/installer | php<br></br>sudo mv composer.phar /opt/lampp/bin/composer<br></br>sudo rm -rf /opt/lampp/share/openssl/certs/<br></br>sudo ln -s /etc/ssl/cert.pem /opt/lampp/share/openssl/cert.pem<br></br>sudo ln -s /etc/ssl/certs /opt/lampp/share/openssl/certs<br></br>composer global require "phpunit/phpunit=4.7.*"
```

# How to do Everything in CakePHP 2.x

### Writing Test Case for AuthComponent's login() Function with CakePHP's Mocking

```
$this->controller = $this->generate('Users', array(<br></br>    'components' => array('Auth' => array('login')) //Mock all Auth methods <br></br>));<br></br><br></br>//This will make sure that Auth->login() function returns true <br></br>$this->controller->Auth->expects($this->once())<br></br>    ->method('login') //The method login()<br></br>    ->will($this->returnValue(true)); //And will return something for me 
```

---

### Loading other models from AppModel

Use `ClassRegistry::init(''anothermodel);`

---

### Irregular Naming Convention

```
Edit app/Config/bootstrap.php and add the following line:<br></br>Inflector::rules('plural', array('irregular' => array('staff' => 'staves')));
```

---

### Expecting exception in CakePHP 2.x Test Case

```
$this->expectException();<br></br>$this->testAction('/controller/action');
```

---

### Cakephp - Saving to Multiple Models from a Single Form

Controller: `$this->Model->saveAll($this->request->data);`

View:

```
echo $this->Form->input('<CURRENT MODEL>.<CURRENT MODEL FIELD>');<br></br>echo $this->Form->input('<MODEL A>.0.<MODEL A FIELD>');<br></br>echo $this->Form->input('<MODEL B>.0.<MODEL B FIELD>');
```

---

### Problem Cakephp blank for certain controller actions only

Cause:

- Extra characters after the php tag "`?>`"
- Retrieved text is not in `UTF-8`

Solutions:

- Do not close php tag for php only files
- Remove the extra characters
- use `utf8_encode([text])` function to convert it before returning the data.

# How to do Everything in AngularJS

### Prevent Route Change

1. Add `target="_self"` to all elements
2. Create new directive to prevent the defaults:
3. ```
    app.directive('a', function() {<br></br>  return {<br></br>    restrict: 'E',<br></br>    link: function(scope, elem, attrs) {<br></br>      if (attrs.ngClick || attrs.href === '' || attrs.href === '#') {<br></br>        elem.on('click', function(e) {<br></br>          e.preventDefault();<br></br>        });<br></br>      }<br></br>    }<br></br>  };<br></br>});
    ```

### Updating Model Within Directives

```
App.directive('myDirective', function ($parse) {<br></br>  return {<br></br>    require: 'ngModel',<br></br>    link: function (scope, elm, attrs, ctrl) {<br></br>      ctrl.$setViewValue(newValue);<br></br>      ctrl.$render();<br></br>      e.preventDefault();<br></br>      scope.$apply();<br></br>    });<br></br>  };<br></br>});
```

### Making AngularJS Work with Bootstrap Vertical Button Group

```
<div class="btn-group-vertical" ng-class="{'active':selected}"><br></br>    <input type="checkbox" autocomplete="off" ng-checked="selected" /><br></br></div>
```

### &lt;Enter&gt; Key Event Directive

JS:

```
app.directive('ngEnter', function () {<br></br>  return function (scope, element, attrs) {<br></br>    element.bind("keydown keypress", function (event) {<br></br>      if(event.which === 13) {<br></br>        scope.$apply(function (){<br></br>          scope.$eval(attrs.ngEnter);<br></br>        });<br></br>        event.preventDefault();<br></br>      }<br></br>    });<br></br>  };<br></br>});
```

HTML Usage:

```
<div ng-app="" ng-controller="MainCtrl"><br></br>    <input type="text" ng-enter="doSomething()"> <br></br></div> 
```

### Passing Functions to Directives

HTML:

```
<test color1="color1" update-fn="updateFn(msg)"></test> 
```

JS:

```
var app = angular.module('dr', []);<br></br><br></br>app.controller("testCtrl", function($scope) {<br></br>  $scope.color1 = "color";<br></br>    $scope.updateFn = function(msg) { <br></br>    alert(msg);<br></br>  }<br></br>});<br></br><br></br>app.directive('test', function() {<br></br>  return {<br></br>    restrict: 'E',<br></br>    scope: {<br></br>      color1: '=',<br></br>      updateFn: '&'<br></br>    },<br></br>    // object is passed while making the call<br></br>    template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>Click</button>",<br></br>    replace: true, <br></br>    link: function(scope, elm, attrs) { <br></br>    }<br></br>  }<br></br>});
```

### Angular JS Best Practices

***1. Do not put the main controller into the main module, instead the main controller should be declared in a new module, this will make the application more modular e.g.***

```
angular.module('app', ['Controller'])<br></br>angular.module('Controller', []).controller('Controller', function($scope) {<br></br>  $scope.something = 100<br></br>})
```

***2. Do not call functions for ng-show and ng-hide directives, as it may degrade performance***

***3. Using too much $scope.$watch is going to degrade performance, try only watch what you really need to and remove the watchers when it's not needed anymore***

# How to do Everything in Javascript (Pure JS)

### Mobile user-agent detection

```
var isMobile = {<br></br>  Android: function() {<br></br>    return navigator.userAgent.match(/Android/i);<br></br>  },<br></br>  BlackBerry: function() {<br></br>    return navigator.userAgent.match(/BlackBerry/i);<br></br>  },<br></br>  iOS: function() {<br></br>    return navigator.userAgent.match(/iPhone|iPad|iPod/i);<br></br>  },<br></br>  Opera: function() {<br></br>    return navigator.userAgent.match(/Opera Mini/i);<br></br>  },<br></br>  Windows: function() {<br></br>    return navigator.userAgent.match(/IEMobile/i);<br></br>  },<br></br>  any: function() {<br></br>  return (isMobile.Android() <br></br>    || isMobile.BlackBerry() <br></br>    || isMobile.iOS() <br></br>    || isMobile.Opera() <br></br>    || isMobile.Windows());<br></br>  }<br></br>};<br></br><br></br>if (isMobile.Android()) {<br></br>  document.location.href = "y";<br></br>} else if(isMobile.iOS()) {<br></br>  document.location.href = "x";<br></br>} 
```

---

### jQuery UI Datepicker Reset Date

```
$(document).ready(<br></br>  function () {<br></br>    $(.datepicker).datepicker({<br></br>    showOn: 'focus', showButtonPanel: true,<br></br>    closeText: 'Clear', // Text to show for close button<br></br>    onClose: function () {<br></br>      var event = arguments.callee.caller.caller.arguments[0]; // If Clear gets clicked, then really clear it<br></br>      if ($(event.delegateTarget).hasClass('ui-datepicker-close')) {<br></br>        $(this).val('');<br></br>      }<br></br>    }<br></br>  });<br></br>});
```

---

### Convert object to string

Use JSON.stringify() function:

```
var obj = new Date();<br></br>console.log(JSON.stringify(obj)); 
```

---

### DataTables Editor jQuery UI Datepicker Issue

- When 2 datepickers are used, it will jump to first datepicker when the second datepicker's date is selected. Make sure that datepickers aren't used as the first field.

---

### Problem: DataTable - Cannot read property 'style' of undefined jquery.dataTables.js

Make sure that HTML number table columns matches the number of 'mData' definition during data table initialization

# How to do Everything in Metro UI CSS

### Metro UI CSS with isLoading jQuery plugin

IsLoading jQuery plugin:

```
/* jQuery Plugin */<br></br>$.isLoading({<br></br>  class: 'spin', <br></br>  text: 'Loading', <br></br>  position: 'overlay', <br></br>  tpl: '<span class="bg-darker isloading-wrapper %wrapper%">%text%<i class="%class% icon-spin"></i></span>' <br></br>});<br></br><br></br>/* CSS */<br></br>/* Chrome, Safari, Opera */ <br></br>@-webkit-keyframes rotate { <br></br>  from {-webkit-transform: rotate(0deg);} <br></br>  to {-webkit-transform: rotate(360deg);} <br></br>} <br></br><br></br>/* Mozilla */ <br></br>@-moz-keyframes rotate { <br></br>  from {-moz-transform: rotate(0deg);} <br></br>  to {-moz-transform: rotate(360deg);} <br></br>} <br></br><br></br>/* Opera */ <br></br>@-moz-keyframes rotate { <br></br>  from {-o-transform: rotate(0deg);} <br></br>  to {-o-transform: rotate(360deg);} <br></br>} <br></br><br></br>/* Spin animation */ <br></br>i.spin, span.spin { <br></br>  -webkit-animation: rotate 1s ease-in-out infinite; <br></br>  animation: rotate 1s ease-in-out infinite; <br></br>  -moz-animation: rotate 1s ease-in-out infinite; <br></br>} <br></br><br></br>/* jQuery isLoading styles */ <br></br>span.isloading-wrapper.isloading-overlay { <br></br>  position: absolute; <br></br>  top: 50%; <br></br>  left: 50%; <br></br>  padding: 10px; <br></br>} 
```

### Metro UI CSS Datepicker Change Event

```
$("#datepicker").datepicker({<br></br>  selected: function(dateString, dateObject) {<br></br>    alert('date-selected');<br></br>  } <br></br>});
```

# ReactJS REDUX Summary

### Using stores and reducers

#### A simple example

```
import {createStore} from 'redux'<br></br><br></br>var reducer_1 = (state, action) => {<br></br>  console.log('reducer_0 was called with state', state, 'and action', action);<br></br>};<br></br>var store_1 = createStore(reducer_1); 
```

#### Real world example

```
import {createStore} from 'redux'<br></br><br></br>var reducer_1 = (state = {}, action) => {<br></br>  switch(action.type) {<br></br>  case '':<br></br>  return {<br></br>    ...state,<br></br>    message: action.value<br></br>  };<br></br>  default:<br></br>    return state;<br></br>  }<br></br>};<br></br>var store_1 = createStore(reducer_1); 
```

#### Combining reducers

```
import {combineReducers, createStore} from 'react';<br></br><br></br>var userReducer = (state = {}, action) => {<br></br>  switch(action) {<br></br>    case 'ADD_USER':<br></br>    return {<br></br>      //Return modified state<br></br>  };<br></br>  default:<br></br>    return state;<br></br>  }<br></br>};<br></br><br></br>var itemReducer = (state = [], action) => {<br></br>  switch(action) {<br></br>    case 'ADD_ITEM':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br><br></br>var reducers = combineReducers(user: userReducer, item: itemReducer);<br></br>var store = createStore(reducers);<br></br>console.log(store.getState());<br></br>// {<br></br>// user: {}, // {} is the slice returned by our userReducer<br></br>// items: [] // [] is the slice returned by our itemsReducer<br></br>// } 
```

### Dispatching an action

Flow of application: ActionCreator -&gt; Action -&gt; dispatcher -&gt; reducer

#### Without action creator

```
import {combineReducers, createStore} from 'react';<br></br><br></br>var userReducer = (state = {}, action) => {<br></br>  switch(action) {<br></br>  case 'ADD_USER':<br></br>    return {<br></br>      //Return modified state<br></br>    };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br><br></br>var itemReducer = (state = [], action) => {<br></br>  switch(action) {<br></br>    case 'ADD_ITEM':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>      default:<br></br>        return state;<br></br>    }<br></br>};<br></br><br></br>var reducers = combineReducers(user: userReducer, item: itemReducer);<br></br>var store = createStore(reducers);<br></br>store.dispatch({type: 'ACTION'}); 
```

#### With Action Creator (Adopted from Flux)

```
import {combineReducers, createStore} from 'react';<br></br><br></br>var userReducer = (state = {}, action) => {<br></br>  switch(action) {<br></br>    case 'ADD_USER':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br><br></br>var itemReducer = (state = [], action) => {<br></br>  switch(action) {<br></br>    case 'ADD_ITEM':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br><br></br>var reducers = combineReducers(user: userReducer, item: itemReducer);<br></br>var store = createStore(reducers);<br></br>var addItemActionCreator = (name) => {<br></br>  return {<br></br>    item: name,<br></br>    type: 'ADD_ITEM'<br></br>  };<br></br>};<br></br>store.dispatch(addItemActionCreator); 
```

#### Async Action with Middleware

```
import {combineReducers, createStore, applyMiddleware} from 'react';<br></br><br></br>var userReducer = (state = {}, action) => {<br></br>  switch(action) {<br></br>    case 'ADD_USER':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br><br></br>var itemReducer = (state = [], action) => {<br></br>  switch(action) {<br></br>    case 'ADD_ITEM':<br></br>      return {<br></br>        //Return modified state<br></br>      };<br></br>    default:<br></br>      return state;<br></br>    }<br></br>};<br></br><br></br>//Set the state after 2s<br></br>var addItemActionCreator = (name) => {<br></br>  return (dispatch) => {<br></br>    setTimeout(() => {<br></br>      dispatch({<br></br>        item: name,<br></br>        type: 'ADD_ITEM'<br></br>      });<br></br>    }, 2000);<br></br>  };<br></br>};<br></br><br></br>// 1) The first level provide the dispatch function and a getState function (if your<br></br>// middleware or your action creator needs to read data from state) to the 2 other levels<br></br>// 2) The second level provide the next function that will allow you to explicitly hand over<br></br>// your transformed input to the next middleware or to Redux (so that Redux can finally call all reducers).<br></br>// 3) the third level provides the action received from the previous middleware or from your dispatch<br></br>// and can either trigger the next middleware (to let the action continue to flow) or process<br></br>// the action in any appropriate way.<br></br>var thunkMiddleware = ({dispatch, getState}) => {<br></br>  return (next) => {<br></br>    return (action) => {<br></br>      return typeof action === 'function' ? action(dispatch, getState) : next(action);<br></br>    }<br></br>  };<br></br>};<br></br><br></br>var reducers = combineReducers(user: userReducer, item: itemReducer);<br></br>var finalCreateStore = applyMiddleware(thunkMiddleware)(createStore);<br></br>var store = finalCreateStore(reducers);<br></br>store.dispatch(addItemActionCreator); 
```

### Subscribing to a Store

```
import {createStore} from 'redux'<br></br><br></br>var reducer_1 = (state = {}, action) => {<br></br>  switch(action.type) {<br></br>    case '':<br></br>      return {<br></br>        ...state,<br></br>        message: action.value<br></br>      };<br></br>    default:<br></br>      return state;<br></br>  }<br></br>};<br></br>var store_1 = createStore(reducer_1);<br></br>store_1.subscribe(() => {<br></br>  //Update react views<br></br>});
```

# Standard ReactJS Procedures

### Initialize ReactJS Project

1. Enter npm init
2. Enter npm install --save-dev babel-core babel-loader babel-preset-react babel-preset-es2015 webpack webpack-dev-server
3. Enter npm install --save react react-dom jquery
4. Append "scripts": {"start": "node\_modules/.bin/webpack-dev-server --progress"},
5. Create and edit webpack.config.js: 
    1. ```
        module.exports = {<br></br>  entry: [<br></br>    './src/app.js'<br></br>  ],<br></br>  output: {<br></br>    path: __dirname,<br></br>    filename: "bundle.js"<br></br>  },<br></br>  module: {<br></br>    loaders: [{<br></br>      test: /\.jsx?$/,<br></br>      loader: 'babel',<br></br>      exclude: 'node_modules',<br></br>      query: {<br></br>        presets:['react', 'es2015']<br></br>      }<br></br>    }]<br></br>  }<br></br>};
        ```
6. Enter `npm start`