Saturday, August 26, 2017

PHP Form Validation Part 2

In Part One,  we explored some securing form logic. In That Article, we extend form validation class by writing validation method like doesn't allow to send empty input value, restrict (minimum or maximum) characters before sending a form or check input value is an email address or not.
Lists of method and properties going to declare in class.
  • Declare class properties.
  • Rework in previous declared methods.
  • Include a method for getting the form field value.
  • Include method check form post request.
  • Include validations method.

Declaring three class properties

    public $isform;
    public $errors = [];
    private $formData = [];
The $isform property, later on, will use in the validation method. $errors property will use for validation messages and last $formData will hold the form field values.

Rework in previous declared methods

public function __construct(){
        switch($_SERVER['REQUEST_METHOD']):
            case 'GET':
                $this->get();
                break;
            case 'POST':
                $this->post();
                break;
        endswitch;
    }
    private function post($arg = ''){
        $post = $_POST;
        $this->userInput($post);
        $this->formData = (!empty($arg) && !empty($post)) ? $post[$arg] : $post;
    }
    private function get($arg = ''){
        $get = $_GET;
        $this->userInput($get);
        $this->formData =  (!empty($arg) && !empty($get)) ? $get[$arg] : $get;
    }
    private function userInput($data){
        $arg = [];
        // clean user input logic here
        foreach($data as $k => $val):
            $val = trim($val);
            $val = stripslashes($val);
            $val = htmlspecialchars($val);
            $arg[$k] = $val;
        endforeach;
        return $arg;
    }
Main Reason for rework in the declared method is pushing form data in the $formData class property.

Getting the Form field value

 public function input($fieldname = ''){
        if(empty($fieldname)):
            return $this->formData;
        else:
            if(array_key_exists($fieldname,$this->formData)):
                return $this->formData[$fieldname];
            else:
                return '';
            endif;
        endif;
    }
Method input() takes one parameter. it will return all the form field value if not send any form field name in the first argument.

Required input field Validation

private function required($fieldName){
        $field = $this->input($fieldName);
        if(empty($field)):
            $this->errors[$fieldName][] = "The $fieldName is required";
            $this->isform = true;
        endif;
    }
The method required() is a private not accessible outside the class. It takes form field name in the first parameter. If the posted form field is empty that method set $isform to true and set validation message in $errors property.

Email input field Validation

 private function validEmail($fieldName){
        $field = $this->input($fieldName);
        if(!filter_var($field, FILTER_VALIDATE_EMAIL)):
            $this->errors[$fieldName][] = 'Email is invalid';
            $this->isform = true;
        endif;
    }
The method validEmail() also have similar required() method logic. It takes one argument, if not valid email then set $isform to true and push validation error message in $errors property.

Set validation rules method

public function addRule($fieldNm,$ruleNm){
        if($_SERVER['REQUEST_METHOD'] = 'post' && empty($this->formData) ){
            $this->isform = true;
            return $this;
        }
        if(!empty($ruleNm)):
            $validationRules = explode('|',$ruleNm);
            foreach ($validationRules as $validationRule):
                switch ($validationRule):
                    case 'required':
                        $this->required($fieldNm);
                        break;
                    case 'validEmail':
                        $this->validEmail($fieldNm);
                        break;
                endswitch;
            endforeach;
        endif;
    }
These validations method is not accessible outside the class because it's private. So we make an addRule() method which is allowed to set validation rules.

//set single validtion rule
$formValidation->addRule('fieldname','required');
//set multiple validation rule
$formValidation->addRule('fieldname','required|validEmail');
The method addRule() takes two arguments. The first form field name and second rules name '|' pipe sign separated.

public function isFailed(){
        $isFail = $this->isform;
        return $isFail;
    }
The method isFailed() is checked form validation Failed or successful. Hopefully that article helpful.
Everyone gets a form validation class from Github with an example.

Thursday, August 24, 2017

PHP Form Validation Part 1

Form Validation is used to validate form data, Protect against hackers and Spammers. We can Validate User's input on the Client Side and on the server side. In this article, we'll discuss why validation is important and how to secure the web form in PHP.

Why validation is important?

Submit form without validating data means you are inviting to the someone destruct your website by using hacking techniques.

How to Secure Web form in PHP

We need to make one Validation layer (function or class) before the user's form data is used in the script or stores the database. This layer validates each form input and pushes into $_POST or $_GET.  if you are not using any PHP framework so definitely you need to write some custom validation code. It could be a bunch of function or a class. Make one Validation class is good to approach rather than an individual method.

Never assign form input directly to class property or local variable it could be harmful.

$val = $_POST['val'];

For securing let's make a validation class.

class formValidation{

     public function __construct(){        
      //secure Post request
      $this->post();
      //secure Get request
      $this->get();
     }

     public function post(){
      $post = $_POST;
         $this->userInput($post,'post');
     }
     
     public function get(){
       $get = $_Get;
        $this->userInput($get,'get');
    }

    private function userInput($data,$type){
    $arg = [];
     // clean user input logic here 
     foreach($data as $k => $val): 
      $val = trim($val);
      $val = stripslashes($val);
      $val = htmlspecialchars($val);
      $arg[$k] = $val;   
     endforeach;
    
  if($type = 'post'):
       $_POST = $arg;
     endif;

  if($ype = 'get'):
      $_GET = $arg;
    endif;
   }
    
}

That's a very simple class having three method's two of the public and one is private. let's initialize form validation class.

$formValidation = new formValidation();

Whenever you initialize form validation class into other classes or inherit with it. it will automatically remove whitespaces at the start and at the end, remove backslashes and convert each form field data into HTML entities. So in the end, you have learned about how to secure web form. In the next Article, you will learn about how to restrict the user to don't send empty input, less than or greater characters stuff.

Monday, May 8, 2017

Change Wordpress Default email and name

By Default Wordpress, all outgoing notification mails are sent from WordPress <wordpress@yourdomain.com>. Does Wordpress have a built-in option to change the default name and email address for outgoing mails? There is no built-in option for it. We have to change manually by using WordPress hooks. In this article, I will show you how to change the default sender name and email address in WordPress notification emails.


The functionality

Copy the code and paste into current theme functions.php
 
// change sender email function
function yr_sender_email( $var_email) {
    return 'info@yoursite.com';
}
// change sender name function
function yr_sender_name( $var_name) {
 return 'Yourname';
}

// Hooking up our functions to WordPress filters 
add_filter( 'wp_mail_from', 'yr_sender_email' );
add_filter( 'wp_mail_from_name', 'yr_sender_name' );

Wednesday, June 17, 2015

PHP basename() Function

The basename() function return file name from the path. This Function Mostly used when we want the only filename from web URL.

Syntax of Basename() function

The basename() function takes two Parameters. In first $path parameter Pass file URL or directory where the file is located and second $suffix parameter pass file format like (.jpg,.png.pdf), etc. Whenever the file format match this will be cut off.
<?php basename ($path ,$suffix ); ?>

Example of Basename() Function

Below code will upload an image from any path or directory to your define folder.
<?php
$path = "http://www.bestphptuts.blogspot.com/logo.png";
$name = basename($path);
$folder = "your_folder_name";
file_put_contents("$folder/$name", file_get_contents($path));
?>

Tuesday, June 16, 2015

Window Live Writer tool for Blogger Posting

Window Live Writer is a Desktop blog publishing tool, developed by Microsoft. I use that tool for blogger posting here some other Blogger tools. Download the latest window writer tool for blogs posting to Here.

Follow Those Steps for installing and setting up this Blogger Tool.


Install Window live Writer in your System

blogger-tools-for-posting

Click on downloaded wlsetup-web.exe File, and follow the Wizard instruction.


blogger-tools-for-posting-01
   
Choose  Your Desire Apps and Then Click to Install.





Then wait for few seconds and your Window live Writer application will be install.

blogger-tools-for-posting-02

Now Lunch Window live writer tools.
blogger-tools-for-posting-03

Link Your Blogger Account with Window Live Writer Field the form to blogger URL, username, and password.

blogger-tools-for-posting-04 blogger-tools-for-posting-05

After setting up blogger account You can Use the following Features of this blogger tools.
  1. Add new Article, edit and preview your article using this Microsoft word Interface APPS.
  2. Add Photos, videos, and offline edit your article.
  3. Add and Select Labels.
  4. Publish Your Article.
  5. schedule your post publishing.

Monday, June 15, 2015

Submit form without a page refresh in PHP/Jquery

In this post, we will explain about submit the form without a page refresh using jquery and PHP.

STEP 1:
I'm using bootstrap front-end framework. the first thing we need to do building proper HTML form using bootstrap classes.

Make jquery-post folder inside create a file index.php and use this below HTML markup.
 

Submit A form Without page Refresh




Using this code, Page should be looks like this.
step 2 create the code.js file and I'm using jquery library for post form include jquery library and code.js file in index.php at the bottom.
e.preventDefault we use e.preventDefault() method for default action of the event will not be triggered.
$.ajax is a jquery method that method post a form we need to define type is a post or get, URL where we want to submit a form after success callback function is executed.
$(document).ready(function(){
 $('#form1').submit(function(e){
  e.preventDefault();
  var formdata = $(this).serialize();
  $.ajax({
   type:'POST',
   url:$(this).attr('action'),
   data:formdata,
   success:function(data){
    console.log(data);
   }
  
  })
 
 });
});

Step 3 When we submit a form, Success callback is executed. The data arguments returned from the server, formatted according to the Type Parameter.first we check what data parameter return using console.log() method.I'm using google chrome, view inspect element click console tab.

Now in the final step, we will insert data MYSQL, Using database library, Create database 'jquery-post', create table 'records' with 4 fields.
1 - id int(11),
2 - name varchar(50),
3 - email varchar(100),
4 - msg varchar(255)
In records.php file paste this below code.
<?php 

if(isset($_POST)){
 //database connection variables
 $username = "root"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "jquery-post"; 
  
 //create new instance DB Mysqlidb
 $db = new Mysqlidb ($host, $username, $password, $dbname);
 $data = array(
  'name' => $_POST['name'],
  'email' => $_POST['email'],
  'msg' => $_POST['msg'],  
 );
 //using insert method 
 $db->insert('records',$data);

}

?>

Thursday, March 26, 2015

Pagination with jQuery, PHP and MySQL.


Pagination is an important part of any website especially if you have hundreds of records. We can build pagination in PHP with the help of  Jquery library.

This tutorial contains four PHP and two JS files.
 First Create demo_pagination folder inside create those files.

database.php (Using DB Class)
config.php (Database configuration)
pagination.php
records.php

Open config.php in your IDE.
// These variables define the connection information for your MySQL database.Define Your Own setting 
    $username = "root"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "DemoPagination"; 

Close config.php then We are creating Database in MYSQL.
CREATE DATABASE DemoPagination;

Inside "DemoPagination" Database Creating Table.
CREATE TABLE records
(
id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT
);

Inserting Few Rows in "records" table
INSERT into records 
 (msg)
values
('This is Testing record row 01. Just for Check'),
('This is Testing record row 02. Just for Check'),
('This is Testing record row 03. Just for Check'),
('This is Testing record row 04. Just for Check'),
('This is Testing record row 05. Just for Check'),
('This is Testing record row 06. Just for Check'),
('This is Testing record row 07. Just for Check'),
('This is Testing record row 08. Just for Check'),
('This is Testing record row 09. Just for Check'),
('This is Testing record row 10. Just for Check'),
('This is Testing record row 11. Just for Check'),
('This is Testing record row 12. Just for Check'),
('This is Testing record row 13. Just for Check'),
('This is Testing record row 14. Just for Check'),
('This is Testing record row 15. Just for Check'),
('This is Testing record row 16. Just for Check'),
('This is Testing record row 17. Just for Check');
Create a pagination.js file inside the folder and Paste this below code.
$(document).ready(function()
{
//Display Loading Image
function DisplayLoader()
{
$("#loader-div").fadeIn(800,0);
$("#loader-div").html("");
}
//Hide Loading Image
function HideLoader()
{
$("#loader-div").fadeOut('slow');
};

DisplayLoader();
$("#results").load("records.php?page=1", HideLoader());

//Pagination Click
$("#pagination li a").click(function(e){
 e.preventDefault(); 
 DisplayLoader();

//Loading Data
var page = this.id;
$("#results").load("records.php?page=" + page, HideLoader());
});

});

I'm using Database Class. You can also download from here. Then open the database.php file and copy whole code from download File.open config.php and include database.php.In records.php file first check $_GET['page'] is not empty then load records from Database.
 
<?php
require_once('config.php');

if($_GET['page']) {
 $record_per_page = 5;
 
 $page = $_GET['page'];
 $start = ($page - 1) * $record_per_page;
 
 $per_page = $start + $record_per_page;
 
 $db = new Mysqlidb ($host, $username, $password, $dbname);
 
 $results = $db->query("select * from records order by id limit $start,$record_per_page");
 
 foreach($results as $record) {
  $html = '';
  $html .= ''.$record['id'].'

';        
        $html .= ''.$record['msg'].'

';
  $html .= '';
  echo $html;
 }
}
?>
Open user interface file (pagination.php) and copy the code from below and paste it.
<?php
require_once('config.php');
//no of records shows  in page
$record_per_page = 5;
//create new instance DB Class
$db = new Mysqlidb ($host, $username, $password, $dbname);
//Runing Query
$db->query("select * from records");
//and count Total records
$count = $db->count;

$pages = ceil($count/$record_per_page);
?>




id Message
    <?php for ($i = 1; $i <= $pages; $i++) { echo '
  • '.$i.'
  • '; } ?>
Download Pagination Code from Here and Live Preview