Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

How to Install Laravel 5.6 on Windows using Composer

On 6/19/2018 1 Comment so far

Here let's see how to install laravel on windows using composer. Ever since its launch, laravel has become the most popular php framework and not without a good reason. It's a great alternative to CodeIgniter which is another popular MVC for php. Laravel ships with so many goodies out of the box than other frameworks do.

Mastering laravel will definitely take some time, but the time spent is well worth it in the long run. And it will save loads of time in application development. Anyhow, here you are, planned to move on to laravel and want to install it for the first time. Without wasting the time, let's dive into the process of installing laravel on windows machine.

step by step install laravel on windows composer

System Requirements for Laravel:

As of now, the latest laravel version is 5.6. And you have to make sure the below system requirements is met to install and use it on your machine.

  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • JSON PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

Reference: Laravel website

Prerequisite: Composer

Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it's a dependency management tool for php similar to node's npm.

To install Composer on your machine, check this post:

Installing Laravel on Windows:

Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on 'www' folder and on XAMPP, obviously the 'htdocs'.

STEP-1) Open 'htdocs' folder on XAMPP, hold SHIFT key and right click on the folder, and choose 'open command window here'. Alternatively, you can open command window and change directory to 'xampp/htdocs'.

STEP-2) Enter the following command.

composer create-project laravel/laravel my_laravel_site --prefer-dist

Here 'my_laravel_site' is the folder name where laravel files will be installed. Change this to your liking.

STEP-3) Now it's time to be patient as laravel installation is going to take some time.

STEP-4) Once installed, change directory to 'my_laravel_site' (cd 'my_laravel_site') on the command prompt and enter the below command.

php artisan serve

STEP-5) This will show a message something like, 'Laravel development server started:' along with an url.

STEP-6) Copy and paste the url on the browser. If things go right, you'd see the laravel welcome screen.

laravel welcome screen

STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

Setting Application Key:

Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

In case it's not set, you have to do it manually. First make sure to rename the '.env.example' file to '.env' on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

php artisan key:generate

Copy this generated key to the APP_KEY variable on '.env' file. Save and you are done.

Installing Specific Laravel Version:

The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

composer create-project laravel/laravel=5.4 your-project-name --prefer-dist
Read Also:

Likewise you can easily install laravel using composer on windows. I hope you find this tutorial useful. Please share it on your social circle if you like it.

How to Create and Download CSV File in PHP

On 6/08/2018 Be the first to comment!

Hi! Here we will see how to create a csv file and download it using php. CSV is one of the popular data storage methods used on the Web. Being a modern language, PHP has no problems handling various data formats including csv. It offers native functions to read and write csv files. With fputcsv() method, you can write data as a csv file and force it to download.

Clicking on a file url (link) will just open it in the browser window without downloading. The exe and zip formats are an exception here. But in case you need to download it directly to client's hard disk, then you have to make use of the readfile() function.

Let's see how to do it.

php create download csv file

PHP - Create CSV File:

The following snippet creates a csv file named 'myfile.csv' on your current working directory.

<?php
// data array
$user = array(1, 'Johnson', 'johnson@mydomain.com', 'Miami');
// filename
$filename = 'myfile.csv';

// write to csv file
$fp = fopen($filename, 'w');
fputcsv($fp, $user);
fclose($fp);
?>

Okay! We have created the csv file. Next we'll move on to the download part.

Download CSV File:

As I said before, you must use readfile() along with the proper header to force download of the file. Here's the code to do it,

<?php
// download file
header('Content-type: text/csv');
header('Content-disposition:attachment; filename="'.$filename.'"');
readfile($filename);
?>

Sending the header along with the download option will force open the 'Save File' dialog in the user's browser window.

We have used two header() functions in the above script.

The first one sets the MIME type of the content sent. Since it is 'text/csv' for csv data, we need to set it as the 'Content-type'.

The second line provides the filename to be used for storing and force the browser to display the save dialog.

Read Also:

That explains how to create csv file and automatically download it in php. I hope you find this post useful. Please share it on social media if you like it.

How to use PHP PREG MATCH function to validate Form Input

On 6/03/2018 3 Comments so far

In this post we'll see how to do some basic PHP validations of form input using preg_match() function. One of the vulnerable spot in a website which attracts malicious hackers are the user input forms like registration form, contact form etc. Validating the user input before processing is the first and foremost step in securing the site. The validation includes checking if the data we received is in the right format and length. Generally it's a practice among web developers to do validation check at the client side (like java script). Still it’s easy for someone to break thru it and harm your site. So it's strictly advisable to do these validations on the server side (like PHP).

Generally we receive the form input as string and we can use preg_match with appropriate regular expression to check a required pattern in the input string.

Preg Match Syntax

Before dwelling into the validation process, here take a sneak peak at the syntax of preg match function.

PHP Preg Match Syntax

1. Form Input should contain only alphabets

Say we have a "Name" field in which we want the user to enter only alphabets. Then we can do the checking by this PHP code,

<?php 
     $name = $_POST["Name"];
     if(!preg_match("/^[a-zA-Z]+$/",$name)) { die ("Invalid Name");}
?>

Where in the regular expression, ^ matches the start of the string and $ matches the end of the string. Also "a-zA-Z" is used in the expression to include both upper and lower case alphabets.

The above code checks each character of the string against the regular expression and throws error incase if there is any other character other than alphabet present in the string.

2. Form Input should contain only alphanumeric characters

In case we want a field (eg., "username") to contain only alphanumeric characters then we can alter the above preg_match expression to include 0-9 numbers too.

 
<?php
     $username = $_POST["Username"];
     if(!preg_match("/^[a-zA-Z0-9]+$/",$username)) { die ("Invalid Username");}
?>

3. First character should be alphabet

We can also force a field's first character to be an alphabet. Let’s take the same "username" example. It can contain alphanumeric characters but we want the first character to be an alphabet. The below code will check if the first character is an alphabet.

<?php
     $username = $_POST["Username"];
     if(!preg_match("/^[a-zA-Z]/",$Username)) { die ("Username should start with an alphabet");}
?>

Instead of using the expression "/^[a-zA-Z]/", we can use "/^[a-z]/i" also. Here ‘i’ represents case independent ie., includes both uppercase and lowercase alphabets.

4. Form Input should contain alphanumeric with special characters

What if you want the input field to contain special characters also? Here is an expression that let the string to have alphanumeric characters along with hyphen (-) and space.

<?php
     if(!preg_match("/^[a-zA-Z\-\ ]+$/",$name)) { die ("Invalid Name");}
?>

5. Check for valid Email-ID

The below code will check if the given email id is a valid one.

 
<?php
     $emailid = $_POST["Emailid"];
     if(!preg_match("/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/",$emailid)) { die ("Invalid Email-ID");}
?>

We have discussed so far some of the common validations we should employ while validating a form. Though it will take a while to warm up with regular expressions, they are quite powerful and using the right expression will do the trick.

Hope you would have enjoyed this article. If you find this one useful, please share it in your circle.

How to Secure Passwords in PHP and Store in Database

On 6/01/2018 1 Comment so far

Hi! Here let's see how to secure passwords in php. Developers have a huge responsibility when handling sensitive user data, such as password. They must take necessary precautions to store the password and other sensitive information in a secure manner. Old-school methods use the md5 algorithm to hash passwords and store them in the database. This really is not safe and vulnerable to attack.

But thanks to the community, PHP 5.5 and higher comes with the password_hash function that generates one-way hash that is extremely secure to store passwords in the database. Below, we will see how to securely hash passwords, store them in the database and verify them against the user given password in php.

php secure password and store in database

PHP - Secure Way to Store Passwords:

If you are a budding developer, these are some things to keep in mind when handling the password.

  • Never store passwords as plain text. It's as good as not having a password at all.
  • Never use MD5 or SHA1 for hashing. They are extremely fast and vulnerable to brute force attack. A powerful GPU could easily break the md5 hash.
  • Never try to make your own password hashing. Someone could easily outrun your smartness putting the system vulnerable.
  • Don't even associate password with encryption, as there is this chance to decrypt which is a big NO. Instead, you must use salted one-way hashing for the password.

So, what to use to protect passwords?

Use password_hash:

With PHP v5.5+, you are lucky to have the built-in password_hash() function, that uses BCRYPT algorithm to hash the password.

The good thing about BCRYPT is that it is very slow compared to md5 and sha1. This makes it computationally expensive to brute force. Plus, you can also change the algorithmic cost factor to make it tougher to break.

How to Hash Password?

To hash the password, pass the password string and the algorithm you want to use for the password_hash.

<?php
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$hash = password_hash($password, PASSWORD_BCRYPT);
$sql = "insert into users (email, password_hash) values ($email, $hash)";
mysqli_query($con, $sql);
?>
The password_hash function will automatically generate a random salt that is cryptographically secure. Therefore, it is strongly recommended that you do not provide your own salt (though you can) for the function.

What should be the length of the Password field?

Be sure to use at least varchar(60) column to store the password hash, since BCRYPT returns 60 characters length string. But you can keep it to up to 255 characters long if you are considerate about future upgrade to accommodate a much stronger algorithm.

How to Verify User Password?

To verify the password, you must use the function password_verify() which will check the password given by the user against the hash created by password_hash. It returns true if the password and the hash match and false otherwise.

Here's the rough usage of the function,

<?php
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$sql = "select * from users where email=$email";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
    $user = mysqli_fetch_assoc($result);
    if(password_verify($password, $user['password']))
        echo 'Valid password!';
    else
        echo 'Invalid password!';
}
?>

If you are using PHP 5.3.7+, use this https://github.com/ircmaxell/password_compat library that helps you to use password_* functions on older php servers.

Read Also:

Guess now you have a clear idea of storing passwords securely in the database with php. No matter how awesome your application, it would be nothing without the proper security measures. I hope you find this post useful. Please, share it on your social circle if you like it.

How to Convert PDF to JPEG Image in PHP

On 5/04/2018 Be the first to comment!

Hi! Today let's see how to convert pdf to jpeg in php using imagick. PHP offers some good native extensions for image processing. Imagick is one of those extensions with which we can easily create JPEG images from pdf without the need for third-party tools.

The library does not need installation since it comes built-in with PHP. You just have to instantiate the class and use it. Plus it provides several customization options to create images. I suggest you to refer the official documentation for the complete list of functions.

php convert pdf to jpeg

PHP - Convert PDF File to JPEG:

Imagick is the native php extension to create and process images using the ImageMagick API. To covert the pdf into jpeg with imagick, you must first read the image from the pdf file and then write it into an image. The following example converts all the pages in a pdf file into jpeg images.

<?php
$imagick = new Imagick();
$imagick->readImage('mypdf.pdf');
$imagick->writeImages('myimage.jpg', false);
?>

In the above snippet, we used two functions,

  • Function readImage(), to read the image from the given file.
  • Function writeImages(), to write an image or image sequence to the file. We have set the second parameter as 'false', which makes the pages to be split into a separate image file. For example, if there are 3 pages in the pdf, they will be saved as myimage-0.jpg, myimage-1.jpg and myimage-2.jpg.

For Better Quality:

To obtain better image quality, use the setResolution() method before reading the image.

$imagick->setResolution(150, 150);

Converting Specific Page to JPEG:

In case you want to convert only a particular page in the pdf file, use the page number after the file name like this, mypdf.pdf[0]. Please remember, the pages start from zero. It will just convert the first page of the pdf into image. Here's the example.

<?php
$imagick = new Imagick();
$imagick->readImage('mypdf.pdf[0]');
$imagick->writeImages('page_one.jpg');
?>
Read Also:

It is really easy to convert pdf to jpeg using the imagick extension. It offers a wide range of functions to create, edit and process images and support formats such as jpg, png, etc. I hope this tutorial is useful to you. Please share it on social media if you like it.

Send HTML Email in PHP via SMTP

On 4/06/2018 4 Comments so far

Hi! Welcome to Koding Made Simple. Today we'll see how to send html email in php. PHP's mail() function is simple and effective and let you send emails with text/html contents and with attachments. Though it has some shortcomings compared to other mailer libraries like PHPMailer, it does the job and comes in-built with PHP package. Plain text emails are good enough, but the ability to send html emails is more powerful in email marketing and other promotions.

HTML emails include html tags and let you add images, format texts and other eye-catching call-to-action buttons etc. But you have to add additional headers for mailing them.

php-send-html-email-via-smtp

Using SMTP for Sending Email

You can send mails via third party Mail Servers but you need authentication first. That is if you want to send email via Gmail in php, then you must have a working gmail account and provide the accounts email-id and password for authentication. We'll see how to set up the php configuration for sending email via gmail smtp server.

How to Send HTML Email in PHP Using Gmail SMTP

You need to change the settings in two places i.e., php.ini and sendmail.ini files. You must remove the ; at the starting of the line to enable the settings in these files. Please note the configuration is given for the xampp package. Open 'php.ini' file located at C:\xampp\php\php.ini and edit the settings like below.

php.ini

[mail function]
SMTP = smtp.gmail.com
smtp_port = 587
sendmail_from = christmascontest@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Next open the 'sendmail.ini' file located at C:\xampp\sendmail\sendmail.ini and make the below changes.

sendmail.ini

smtp_server = smtp.gmail.com
smtp_port = 587
auth_username = christmascontest@gmail.com
auth_password = christmascontest
force_sender = christmascontest@gmail.com

Save the files and restart apache server for the changes to reflect. Now you are ready to send send html email using php mail() function.

Create a php file and write down the below php mailer code to it and save.

PHP Code for Sending HTML Email

<?php
// from email
$from = 'christmascontest@gmail.com'; // change this
// to email
$to = 'sally@somedomain.com, justin@somedomain.com, parker@somedomain.com'; // change this
// subject
$subject = 'Christmas Contest Announcement';

// html message
$htmlmsg = '<html>
    <head>
        <title>Christmas Contest Winners</title>
    </head>
    <body>
        <h1>Hi! We are glad to announce the Christmas contest winners...</h1>
        <table>
            <tr style="background-color: #EEE;">
                <th width="25%">#</th>
                <th width="35%">Ticket No.</th>
                <th>Name</th>
            </tr>
            <tr>
                <td>#1</td>
                <td>P646MLDO808K</td>
                <td>Sally</td>
            </tr>
            <tr style="background-color: #EEE;">
                <td>#2</td>
                <td>DFJ859LV9D5U</td>
                <td>Parker</td>
            </tr>
            <tr>
                <td>#3</td>
                <td>AU30HI8IHL96</td>
                <td>Justin</td>
            </tr>
        </table>
    </body>
</html>';

// set content type header for html email
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

// set additional headers
$headers .= 'From: Christmas Contest <christmascontest@gmail.com>' . "\r\n";
$headers .= 'Cc: contestadmin@gmail.com' . "\r\n";

// send email
if (mail($to, $subject, $htmlmsg, $headers))
    echo "Email sent successfully!";
else
    echo "Error sending email! Please try again later...";
?>

Change $from to your gmail-id and $to variable to the recipients email-id.

Plus the code includes content type header which is a must for sending html emails and additional headers should be appended with CRLF.

Note: If you have enabled two-way authentication for Google account then please disable it for this code to work.

That's all about sending html email in php via smtp server.

Read Also:

Dynamic Treeview Menu using PHP, MySQL and AJAX Example

On 3/26/2018 Be the first to comment!

How to Create Dynamic Treeview Menu using PHP, MySQL and AJAX? Most modern websites use tree view to display the dynamic sidebar menu for easy navigation. In case you don't know, a Treeview is a hierarchical representation of elements in a tree-like structure. You can go for jquery solution in this context, but I would recommend 'Bootstrap Treeview' plug-in if you use the bootstrap framework to build your websites.

The plug-in uses JSON dataset to create a hierarchical tree structure. I have already discussed the creation of static treeview menu using bootstrap treeview. But you can also generate a dynamic tree where you pull off the data elements stored in the database. In this tutorial I'm going to show you about creating dynamic treeview using php, mysql, ajax and bootstrap.

bootstrap dynamic treeview example

How to Create Dymanic Treeview in PHP & MySQL?

For the demo, I'm going to load all the required libraries via CDN. So there's no need to download them to your web server.

Here are the simple steps to build a dynamic tree view structure.

STEP-1) First create the mysql database required for the example. I would suggest you follow the same schema given below to maintain the hierarchy structure.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE `tbl_categories` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(50) NOT NULL,
  `parent_id` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18;

INSERT INTO `tbl_categories` (`id`, `item_name`, `parent_id`) VALUES
(1, 'Electronics', 0),
(2, 'Televisions', 1),
(3, 'Tube', 2),
(4, 'LCD', 2),
(5, 'Plasma', 2),
(6, 'Computers and Laptops', 1),
(7, 'Desktops', 6),
(8, 'Laptops', 6),
(9, 'Netbooks', 6),
(10, 'Tablets', 6),
(11, 'Android', 10),
(12, 'iPad', 10),
(13, 'Mobile Phones', 1),
(14, 'Basic Cell Phones', 13),
(15, 'Smartphones', 13),
(16, 'Android Phones', 15),
(17, 'iPhone', 15);

STEP-2) Next create a php script to be executed by ajax call. This will fetch the menu data from the 'tbl_categories' table, create hierarchical tree structure and return it as JSON data.

fetch_categories.php

<?php
$db = mysqli_connect('localhost', 'mysql_username', 'mysql_password', 'my_demo');
$sql = 'select id, item_name as name, item_name as text, parent_id from tbl_categories';
$result = mysqli_query($db, $sql);

$tree_data = mysqli_fetch_all($result, MYSQLI_ASSOC);

foreach($tree_data as $k => &$v){
    $tmp_data[$v['id']] = &$v;
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        $tmp_data[$v['parent_id']]['nodes'][] = &$v;
    }
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        unset($tree_data[$k]);
    }
}

echo json_encode($tree_data);
?>

STEP-3) Finally, create an HTML file and add placeholder to show the tree view. Here you have to load all the required libraries such as bootstrap, jquery and bootstrap treeview libraries.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>PHP and MySQl Dynamic Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-4">
            <h3 class="text-center bg-primary">Dynamic Treeview Example</h3>
                <div id="myTree"></div>
            </div>

            <div class="col-sm-8">
                <!-- here goes other page contents -->
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: 'fetch_categories.php',
            method: 'GET',
            dataType: 'json',
            success: function(data){
                $('#myTree').treeview({data: data});
            }
        });
    });
    </script>
</body>
</html>

In the success function of the ajax() call, we have invoked the treeview() method of the 'bootstrap-treeview' library to display the tree structure on the corresponding placeholder.

When you run 'index.html' a tree menu similar to this one will appear,

ajax dynamic treeview php mysql example
Read Also:

Similarly, you can create treeview dynamically using php, mysql and ajax. You can also add icons, check boxes and filters to the nodes of the tree menu. Check the documentation to learn more about it. I hope this tutorial is useful for you. Please share it on social media if you like it.

Convert HTML to PDF in PHP using DomPDF Library

On 3/12/2018 Be the first to comment!

Hi! In today's post we will see how to convert html to pdf in php using dompdf library. DomPDF is basically a php library that offers a simple way to convert html content to pdf so that you can generate pdf files on fly with php. Frameworks like Laravel offers separate packages to create pdf files, but there is not so much luck when you work on core php. Hence we need external tools for the task and DomPDF is a good fit for it.

The library creates downloadable pdf file from the html webpage. It supports CSS2.1 and CSS3 and renders the html layout including the styles. It also handles @import, @media and @screen queries and can load external stylesheets while generating the pdf.

php convert html to pdf dompdf

1. Convert HTML to PDF - Basic Usage:

Download the dompdf archive from here and extract the contents to your root folder. After that, create a sample php file, 'index.php' and include the autoloader file to load the required dompdf libraries and helper functions into your PHP project.

The following php script describes the basic usage of the dompdf class. It converts simple html content into pdf and output to the browser.

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// import dompdf class into global namespace
use Dompdf\Dompdf;

// instantiate dompdf class
$dompdf = new Dompdf();

// pdf content
$html = '<h1 style="color:blue;">Hello World!</h1><p>A PDF generated by DomPDF library.</p>';

// load html
$dompdf->loadHtml($html);

// set paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// render html as pdf
$dompdf->render();

// output the pdf to browser
$dompdf->stream();
?>

The function setPaper() is optional. If not provided, the default page settings will be used for rendering the pdf.

2. Generate PDF and Show File Preview:

The dompdf library offers an option to preview the pdf file before downloading. After generating the pdf, display it on the browser to get a preview using the stream() method.

This method takes two parameters of which the first is the filename and the second is the optional parameter called Attachment. The default value for this param is '1' forcing the browser to open the download pop-up window. Instead, you must set it as '0' for the browser preview.

<?php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$html = '<h1 style="color:blue;">Hello World!</h1><p>A PDF generated by DomPDF library.</p>';
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

// preview pdf
$dompdf->stream('newfile',array('Attachment'=>0));
?>
generate pdf from html php dompdf

3. Save PDF to File:

To save the created pdf as a file on your local disk, you must output the rendered pdf to a variable and write it to a file using the file_put_contents() method.

<?php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$html = '<h1 style="color:blue;">Hello World!</h1><p>A PDF generated by DomPDF library.</p>';
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
// write pdf to a file
$pdf = $dompdf->output();
file_put_contents("newfile.pdf", $pdf);
?>

4. Generate PDF from HTML File:

You can also generate pdf from an html file. First you have to read the contents of the file into a variable using file_get_contents() method and then load it with the loadHtml() function of the library.

<?php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$html = file_get_contents('data.html');
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream('newfile', array('Attachment'=>0));
?>

5. DomPDF Options:

The library offers a range of options for customization. You can set the options at run time like this,

<?php
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->set_option('defaultFont', 'Courier');
?>

For the complete list of available options, see the page Dompdf Options on github.

Read Also:

To generate pdf files in your php project, you can use the DomPDF library. The support for CSS gives you good control over the looks of the generated pdf. But keep in mind rendering large tables and files will take time. I hope this post is useful to you. Please share it on social media if you like it.

PHP - Send Email via SMTP Server using PHPMailer

On 3/05/2018 Be the first to comment!

Hi! In this post, let's see how to use PHPMailer to send email from PHP. PHPMailer is an amazing php library to send emails quickly. We all know the generic PHP's mail() function helps you send emails. But on the downside, it requires local mail server to send them. And also the setup and configuration is not that easy. But that's not the case with PHPMailer. The library supports SMTP protocol and allows easy authentication over SSL and TSL. It allows you to display error messages in more than 40 languages in case there is an error when sending emails.

PHPMailer uses the real valid email address to send mails. Hence you have to setup one if you don't have it. Here, let's see how to use Gmail SMTP to send email via PHPMailer.

php send email through smtp using phpmailer

Sending Email via Gmail SMTP using PHPMailer:

SMTP is basically a mail protocol that sends a request to the mail server and after verification sends it to the mail server of the recipient.

To send an email via smtp, you need the authentication from the other host. So if you want to use gmail, you must provide the following details for authentication.

  • Host - gmail smtp server
  • Port - smtp port number
  • Username - gmail address
  • Password - gmail a/c password

First you need to download and extract the 'PHPMailer' folder to your application root. If you use composer (which is recommended), simply including the 'vendor/autoload.php' file in your php script will do. Otherwise, you must load all the required class files manually as I do in the following example.

PHPMailer Script to Send Mail:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

$mail = new PHPMailer;

// smtp settings
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tsl';
$mail->Username = 'myemailaddress@gmail.com'; // change this to yours
$mail->Password = '********'; // change this to yours

// set from & to email address
$mail->setFrom('myemailaddress@gmail.com', 'KMS'); // change this to yours
$mail->addReplyTo('myemailaddress@gmail.com', 'KMS'); // change this to yours
$mail->addAddress('john.doe@gmail.com');

// mail content
$mail->isHTML(true);
$mail->Subject = 'This is the subject';
$mail->Body = '<h1>Test Mail!</h1><p>This is the body of the message.</p>';

// send email
if($mail->send()){
    echo 'Message has been sent successfully!';
} else {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>

This php script send a simple html email to the recipient's email address. Note that we have used isHTML(true) to set the mail format to html.

The first two lines of the script are used to import PHPMailer classes into the global namespace. Make sure they remain at the very top of your script and not within a function.

Sending Mail to Mulitiple Email-IDs:

To send an email to multiple email addresses, add the recipients one by one with the addAddress() function.

$mail->addAddress('user1@example.com', 'user 1');
$mail->addAddress('user2@example.com', 'user 2');
$mail->addAddress('user3@example.com', 'user 3');

Including CC and BCC:

To send 'CC' and 'BCC', use addCC() and addBCC() functions.

$mail->addCC('cc_address@example.com');
$mail->addBCC('bcc_address@example.com');

Sending Mail with Attachments:

Use the addAttachment() function to add attachments to the mails.

// attachment
$mail->addAttachment('files/file1.tar.gz');

// add optional name to the attachment file
$mail->addAttachment('images/image1.png', 'newimage.png');

Some may face problems while sending emails with gmail smtp. This is due to Google blocking the authentication from apps.

Just log in to your Google account, go to 'Sign-in & security' > 'Connected apps & sites' and turn on 'Allow less secure apps' option.

You may also face problem if you have enabled two-step verification on your account. Either disable the feature or create a unique password for signing in through apps.

Read Also:

Following the above procedure, you can easily send emails through smtp with the phpmailer class. The same applies to any other third-party mail servers. You have to change the smtp host, username and password accordingly. I hope you find this post useful. Please share it on social media if you like it.

How to Display Random Image from Folder in PHP

On 2/26/2018 Be the first to comment!

Hi! This is a quick tutorial about displaying random image from folder in php. It will be useful if you want to include featured section area on websites. Usually site owners will showcase their products or services in the prominent section with attractive pictures. And all these images will come from a folder and rotated through at regular time interval. A random image will be picked up from the lot one at a time and displayed here.

Let's see how to implement this random image selection process. PHP offers a rich set of native functions to handle directory and files. And they are more than enough for the task we are going to do.

php display random image from folder

PHP - Displaying Random Image from Folder:

As for the process goes, we have to use scandir() function to read all the files from a given folder and make a random pick in the lot. Just follow the below steps to choose a random image file in a directory and display it on the browser.

Step-1) First define the path to the image folder.

$dir_path = "images";

Step-2) Next read all the filenames into an array. For this we have to use scandir() method.

$files = scandir($dir_path);

Step-3) Now select a random image file from the array. For this, you have to create a random index using rand() function and get the file name.

$count = count($files);
$index = rand(2, ($count-1));
$filename = $files[$index];

Step-4) Finally display the chosen image in the browser. You must use <img> tag to display the image.

echo '<img src="'.$dir_path."/".$filename.'" alt="'.$filename.'">';

That's it! You have successfully displayed a random image in a directory.

PHP Function:

Here I have created getRandomImage() function to display random picture. It takes up the directory path as a parameter and returns an image from the same directory.

<?php
function getRandomImage($dir_path = NULL){
    if(!empty($dir_path)){
        $files = scandir($dir_path);
        $count = count($files);
        if($count > 2){
            $index = rand(2, ($count-1));
            $filename = $files[$index];
            return '<img src="'.$dir_path."/".$filename.'" alt="'.$filename.'">';
        } else {
            return "The directory is empty!";
        }
    } else {
        return "Please enter valid path to image directory!";
    }
}
?>

Usage:

You have to call the above function like this,

<?php
echo getRandomImage("images");
?>

Every time you run the code, it will select and display some random picture from the folder.

Read Also:

Likewise, you can display random image from the folder in php. To read the filenames, you also can use glob() function which return the filenames from a folder that matches a specific pattern. Hope this post is useful to you. Please share it on social media if you like it.

How to Download File from URL using PHP cURL

On 2/15/2018 Be the first to comment!

Hi! In this post, we will see how to download file from url using php curl. CURL is a great tool when it comes to remote communication. Using it, you can easily connect to a remote server and download files to your local machine. It allows to send http post request and get request in php as well.

Executing a basic curl request will simply return the data to the output stream. But we don't want that. Instead, we must assign it to a php variable, which we can write it to the disk. Using CURLOPT_RETURNTRANSFER is the easiest way to copy remote files to our own. But there is a problem with this method. Below we will see the right way to download remote files with curl.

php download file from url curl

PHP - Download File from URL using cURL:

To download files from the remote url with curl, you have to follow the below steps:

  1. Create a writable file stream
  2. Pass the file handle to curl
  3. This will make cURL write the content downloaded directly into the file.
  4. Close the file handle.

As I said earlier, using CURLOPT_RETURNTRANSFER will pose a problem when we download huge files. You'll easily exceed memory limits, given the entire data has to be read into the memory before writing it to disk. Even if you increase the limit, it's an unnecessary load on the server.

Simply passing the writable file stream to the curl will make it copy the contents of the file directly. For this we have to use the CURLOPT_FILE option.

Here is the code snippet to download files from the remote url.

<?php
$file_url = 'http://www.test.com/images/avatar.png';
$destination_path = "downloads/avatar.png";

$fp = fopen($destination_path, "w+");

$ch = curl_init($file_url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
$st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);

if($st_code == 200)
 echo 'File downloaded successfully!';
else
 echo 'Error downloading file!';
?>

This code will download the file contents from the given $file_url and copy it to the $destination_path. Make sure the destination folder has write permission so that the file is downloaded correctly.

Brief explanation of the functions we have used above,

  • fopen() - The function opens a file or url and returns the file pointer.
  • curl_init() - Initialize the curl session.
  • curl_exec() - It executes the given curl session.
  • curl_close() - Destroy an existing curl session.
  • CURLOPT_FILE - The option instructs curl to save the data returned to the given file.
  • curl_getinfo() - Returns the status details of the latest transfer.

For HTTPS Transfer:

If your file url contains 'https' instead of 'http', it is better to configure the SSL option in curl with this line,

curl_setopt($ch, CURLOPT_SSLVERSION, 3);
Read Also:

That explains about downloading file from url using php curl. With this method, you can download even large files from remote servers without running out of memory usage. Also make sure to include proper error handling in the production environment. I hope this tutorial is useful. Please share it on social media if you like it.

How to Post JSON Data with PHP cURL & Receive It?

On 2/05/2018 1 Comment so far

Hi! Here let's see how to post json data with php curl and receive the raw json sent. You can simply use PHP file_get_contents() to send HTTP GET request. But it's not the same case with HTTP POST. Fortunately PHP cURL makes the process very simple. With curl you can easily send HTTP requests. In case you don't know, 'cURL' is a library that let you communicate with web servers using different protocols such as http, https, ftp, telnet, file etc.

To use curl, you must install libcurl package on your server according to the version of PHP you use.

send http post json in php

In case you are not sure if curl is enabled on your machine or not, use this code to check it.

<?php echo (is_callable('curl_init') ? 'cURL is enabled' : 'cURL is disabled'); ?>

How to Post JSON with PHP cURL?

In order to send HTTP POST request with JSON data, you have to follow some steps and they are,

  1. Format JSON data correctly
  2. Attach JSON to the body of the POST request
  3. Set the right content type with HTTP headers
  4. Send the request.

The following is the PHP code to send json through POST request.

<?php
// url
$url = 'http://mydomain.com/api/users/create';

// json data
$data = array(
    'site' => 'mydomain.com',
    'account' => 'admin',
    'status' => 'true'
);
$json = json_encode($data);

// send post request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

Here is the explanation for the functions & curl options we have used in the above script:

  • curl_init() - Initialize a curl session, takes up a parameter URL to send post request.
  • curl_setopt() - Set the curl options.
  • CURLOPT_POSTFIELDS - This option will set the data to the body of the http request.
  • CURLOPT_HTTPHEADER - Option to set http headers. It is important to define the right content type here, so that the remote server understands what we sent. To send json, the content type should be set to 'application/json'.
  • CURLOPT_RETURNTRANSFER - Setting this to TRUE will place the response from the remote server on $result variable instead of outputting it.
  • curl_exec() - Send the HTTP request.
  • curl_close() - Close the curl session.

Retrieve the Posted JSON:

Okay! We have sent json data via http post request. But what will happen at the receiving end? How should we retrieve the incoming json?

Well! In our example we have sent raw json data. This can be accessed through php's input stream. Below is the code to receive the json posted,

<?php
$output = file_get_contents("php://input");
echo $output;
?>

You can decode the json and process it as you want. Pretty simple!

Read Also:

That explains about posting json data and receiving it using PHP cURL. This is not very different from sending a regular POST request. However, we are doing it over HTTP here. Hopefully, this tutorial is useful for you. Please don't forget to share it with your friends.

Paytm Payment Gateway Integration in PHP - Example

On 1/22/2018 Be the first to comment!

Hi! In this tutorial, we will see how to integrate paytm payment gateway in php. Mobile wallets have become immensely popular in recent years and paytm is highly trusted among online customers. Many people use it every day for doing online recharges, DTH & other bill payments. It reduces the risk of exposing customer's banking credentials and credit card details to hackers. Therefore, Paytm is a good solution for online payments on your Website and Mobile Apps.

Integrating the paytm gateway in your application is quite easy and below I'll show how to do it with php.

paytm payment gateway integration php

Paytm Payment Gateway PHP Integration:

If your application is based on php, then you don't have to go from scratch. You can quickly integrate paytm into the application using the paytm kit for php. It covers all the basics, you just have to download and use it in the following way.

Step-1) Download Paytm Kit

Download Paytm Payment Kit for PHP and extract its contents. Then move the 'PaytmKit' folder to your working directory.

Step-2) Register for Paytm Sandbox Account

Next, you must register for merchant sandbox account with paytm and collect the necessary details to use with the API. Visit this link and provide your mobile number, email id and password and register an account. You will be provided with merchant id, key etc. Store them in a text file to use it later.

Step-3) Configure the Settings

Now you must configure the payment gateway settings with the data you received in Step-2. Open 'PaytmKit' > 'lib' > 'config_paytm.php' file and update the following details.

define('PAYTM_ENVIRONMENT', 'TEST'); //change this to 'PROD' to use it in production environment
define('PAYTM_MERCHANT_KEY', 'YOUR_MERCHANT_KEY'); //Change this to the merchant key downloaded from the portal
define('PAYTM_MERCHANT_MID', 'YOUR_MERCHANT_ID'); //change this to merchant id received from paytm
define('PAYTM_MERCHANT_WEBSITE', 'WEBSITE_NAME'); //change this to website name received from paytm

Step-4) Create Payment Form

Finally create a payment form to make transactions. Here we need to pass the form action to file 'pgRedirect.php' located inside the 'PaytmKit' folder. This will take care of verifying the checksum and other details and process the payment via the paytm wallet.

<!doctype html>
<html>
<head>
<title>PHP Patym Gateway Integration Demo</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="text-center">Paytm Payment Gateway Demo</h3>
            </div>
            <div class="panel-body">
            <form action="pgRedirect.php" method="post">
                <div class="form-group">
                    <input type="text" class="form-control" id="ORDER_ID" name="ORDER_ID" size="20" maxlength="20" autocomplete="off" tabindex="1" value="<?php echo  "ORDS" . rand(10000,99999999)?>">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="CUST_ID" name="CUST_ID" maxlength="12" size="12" autocomplete="off" tabindex="2" value="CUST001">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="INDUSTRY_TYPE_ID" name="INDUSTRY_TYPE_ID" maxlength="12" size="12"  autocomplete="off" tabindex="3" value="Retail">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="CHANNEL_ID" name="CHANNEL_ID" maxlength="12" size="12" autocomplete="off" tabindex="4" value="WEB">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="TXN_AMOUNT" name="TXN_AMOUNT" autocomplete="off" tabindex="5" value="1">
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="CheckOut" class="btn btn-success btn-lg">
                </div>
            </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

This is just a usual php form, but remember to pass all the required parameters as I did. And for designing UI, I have used bootstrap css here, but you can happily skip it if you don't want.

php paytm payment demo

You can refer the official documentation for more details about Paytm gateway API.

Read Also:

That explains about paytm payment gateway integration in php. Using the kit really simplifies the task and allows you quickly add the paytm payment option to your web/mobile applications. I hope you like this tutorial. Please share it on social media if you find it useful.

CodeIgniter | Remove index.php from URL using htaccess

On 1/21/2018 28 Comments so far

Hi, we’ll see how to remove index.php from url in codeigniter. Even though codeigniter uses search engine friendly urls, nobody would have missed the awkward presence of 'index.php' in between those codeigniter's urls. Have you ever wondered how to get rid of it to get more clean urls in your codeigniter application? Say your app has an url something like http://www.example.com/index.php/contact and you want it to look like http://www.example.com/contact. Yes, you can do it. In codeigniter removing index.php from url should be done by rewriting urls in htaccess file.

How to Remove index.php from URL in CodeIgniter using .htaccess?

Recommended Read: How to Create Login Form in CodeIgniter, MySQL and Twitter Bootstrap

Recommended Read: CodeIgniter/MySQL Tutorial - Read and Display data with Twitter Bootstrap

Step 1: Enable Mod Rewrite Option in your APACHE Server

To rewrite urls in the htaccess file, the mod_rewrite option should be enabled in the apache server. Goto apache's "httpd.conf" file and search for the line,

LoadModule rewrite_module modules/mod_rewrite.so

If the above line is preceded with # (in which case, the module is disabled), then remove the # (hash) symbol to enable url rewriting.

Step 2: Create '.htaccess' File

Next create the .htaccess file at the root directory. To create the htaccess file, open your favourite text editor and create a new text file. Save it as ".htaccess" (make sure you type the filename within quotes to avoid the file to be saved as text file) in the root directory.

htaccess file codeigniter

Now copy paste this code to the htaccess file and save it.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteCond %{REQUEST_URI} !/system/.* [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

If you run your codeigniter app as a subdirectory instead of root domain like, http://example.com/cisite/ instead of http://example.com/ then the above code won't work. You have to tweak it little to tell that your site runs as a subdirectory. Add this code to the htaccess file instead of the above one.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteCond %{REQUEST_URI} !/system/.* [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Step 3: Modify CodeIgniter Config Settings

Open config.php file under application >> config folder and search for the line,

$config['index_page'] = 'index.php';

Remove index.php from it to look like this,

$config['index_page'] = '';

Now restart apache and check the url. eg., http://www.example.com/contact instead of http://www.example.com/index.php/contact

Recommended Read: How to Upload Files in PHP Securely

Recommended Read: How to Insert JSON into MySQL using PHP

If it doesn't work, you may be having problem with uri protocol. In that case find $config['uri_protocol'] ='AUTO' setting in config file and replace with $config['uri_protocol'] = 'REQUEST_URI'.

Restart apache server again and you can check the codeigniter site to see that index.php has been removed from codeigniter url.

How to Merge Two JSON Strings into One with PHP

On 1/19/2018 Be the first to comment!

Hi! In this tutorial we will see how to merge two json strings into one in php. People often mistakes JSON for object or array but it's the string representation of a JavaScript object. In a recent project, I wanted to combine two jsons. That is, I have to make two API calls and combine their results into one. It is a rest api and returns the response as json. The task is simpler than I thought. It employs a similar technique I used here earlier when dealing with json. Let me show you how to do it.

php merge two json strings

PHP - Merging Two JSON into One:

If you are new to working with JSON, don't worry. PHP offers native functions to handle it easily. The idea is to decode the json data, write it to an array and encode it back to json.

Below are the steps involved in the process.

STEP-1) Let's take two different jsons containing couple of employee details.

<?php
$json1 = '{"id": "GD01", "name": "Garrett Davidson", "position": "System Administrator", "location": "New York"}';
$json2 = '{"id": "DW02", "name": "Donna Winters", "position": "Senior Programmer", "location": "Seattle"}';
?>

STEP-2) Next we should convert the json strings into an array and join them into a single array.

<?php
$array[] = json_decode($json1, true);
$array[] = json_decode($json2, true);
?>

Keep in mind the function json_decode() will return stdObject by default. To make it return associative array, we have to set the second parameter as 'true'.

STEP-3) Then convert the merged array to json. For this we have to use the function json_encode(). While encoding, I have included the token 'JSON_PRETTY_PRINT' to add proper indentation so that it's easy on the eyes.

<?php
$result = json_encode($array, JSON_PRETTY_PRINT);
?>

STEP-4) Finally print the merged json. You can simply echo it, but the output will look messy and difficult to read. So be sure to set the headers with right content type to display indents and blank spaces between the texts.

<?php
header('Content-type: text/javascript');
echo $result;
?>

This will produce the below output,

// output
[
    {
        "id": "GD01",
        "name": "Garrett Davidson",
        "position": "System Administrator",
        "location": "New York"
    },
    {
        "id": "DW02",
        "name": "Donna Winters",
        "position": "Senior Programmer",
        "location": "Seattle"
    }
]

As you can see, the output consists of a nested json combining the data from $json1 and $json2.

Here is the complete php script for json merging process.

index.php

<?php
$json1 = '{"id": "GD01", "name": "Garrett Davidson", "position": "System Administrator", "location": "New York"}';
$json2 = '{"id": "DW02", "name": "Donna Winters", "position": "Senior Programmer", "location": "Seattle"}';

// decode json to array
$array[] = json_decode($json1, true);
$array[] = json_decode($json2, true);

// encode array to json
$result = json_encode($array, JSON_PRETTY_PRINT);

// print merged json
header('Content-type: text/javascript');
echo $result;
?>

You can also store the json output in a file instead of displaying it in the browser window.

Read Also:

That explains about combining two or more json strings in php. The process can be easily done with core php alone and doesn't require any external tool. I hope you like this tutorial. Please share it on social media if you find it useful.

How to Get Country Name from IP Address with PHP

On 1/15/2018 Be the first to comment!

Hi! In this post, let's see how to get country name from ip address using php. When working on multilingual web applications, it is mandatory to find the geographic location of the visitors, so that you can provide the contents that match the specific location. Some websites even change country flags and themes accordingly.

With PHP, you can get the visitor's IP easily, but unfortunately there's no way to get the country details from it. Hence, you have to rely on external web services to provide the location details. Here I'm going to show you how to find the country of visitors with the help of GeoPlugin API and PHP.

php get country name from ip address

Getting Country Name from IP Address with GeoPlugin:

GeoPlugin is a free web service that provides geographical location of site visitors from IP. It offers various types of services like PHP, JSON etc., and in this tutorial, I'm going to use the JSON API to find the country name.

You have to access the service with this url,

http://www.geoplugin.net/json.gp?ip=IP_ADDRESS

The API will return the name of the country along with other details related to the location, such as city, currency, latitude, longitude, etc.

Below I have created a PHP function getIP(). It accepts the IP Address as a parameter, communicates with the geoPlugin api and returns the country name for that IP.

PHP Function:

<?php
function getIP($ipadr) {
    if(isset($ipadr)) {
        $details = file_get_contents('http://www.geoplugin.net/json.gp?ip=' . $ipadr);
        $json = json_decode($details);
        if($json->geoplugin_status == '200')
            return $json->geoplugin_countryName;
        else
            return 'Error getting country name.';
    } else {
        return 'IP is empty.';
    }
}
?>

Usage:

You must call the function like this,

<?php
echo getIP('17.142.180.78');

// output
// United States 
?>

What the function does is, take the ip address and send the http request to the api using file_get_contents() method. The api returns the json response, which it decodes with json_decode(), parses for the country name and returns it.

Finding Visitor Country Location:

In case you want to find the visitor's location, you must pass the client ip address to the function in this way,

<?php echo getIP($_SERVER['REMOTE_ADDR']); ?>

Keep in mind to use this on live server, because REMOTE_ADDR will return the default ip '127.0.0.1' when you run it from localhost.

Read Also:

That explains about getting country name from IP address using geoplugin api and php. The good thing about this API is you do not need to register or obtain an API key to use the web service. It's totally free and simple to use. I hope you like this. Please share this on social networks if you find it useful.

Get JSON from URL in PHP

On 1/09/2018 8 Comments so far

In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

Let's see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.

php-get-json-from-url

How to Calculate Age from Date of Birth using PHP

On 1/08/2018 Be the first to comment!

Hi! Here we will see how to calculate age from date of birth using php. Working with dates is essential in web development and what we are going to see is a small but very useful utility. Applications such as membership driven websites, social platforms, etc., show the age of the users on their profile page, which they calculate from the date-of-birth of the users. Finding age with the birth date is very easy in php.

If you use PHP 5.3+, consider yourself fortunate as it offers a built-in function called date_diff() that simplifies the task.

php calculate age from date of birth

Using Date_diff() Function:

The function date_diff() in php takes two DateTime objects and returns the difference between them.

You can't pass a date string as it is to the function. First you must convert it into a DateTime object using date_create() and then pass them as arguments.

Consider the following example,

<?php
$date1 = date_create('2017-7-10');
$date2 = date_create('2017-7-17');
$interval = date_diff($date1, $date2);
echo $interval->format('%a days');
?>

The above code will output '7 days'. It takes two dates as arguments and returns the difference in the number of days.

PHP - Calculate Age from Date of Birth:

We can use similar logic to find age. To calculate the age, all you have to do is to get the difference between the current date (today) and the birth date.

The following PHP function accepts date of birth as parameter and returns the person's age based on that.

PHP Function to Calculate Age (Procedural Way):

<?php
function calculateAge($dob)
{
    $interval = @date_diff(date_create($dob), date_create('today'));
    return $interval->format('You are %y years, %m months, %d days old.');
}

echo calculateAge('20-5-1993');
// output
// You are 24 years, 7 months, 16 days old.
?>

The function creates 'DateTime' object from 'date of birth' and 'current date' (today) and passes them to the date_diff() function. Then using format() returns the difference in years, months and days.

The snippet employs a procedural approach. The same can be done with object oriented programming (OOP).

Calculating Age (Object Oriented Sytle):

In the OOP approach, you have to use the function diff(). Here is the PHP function to calculate the age using diff() and oop.

<?php
function calculateAge($dob)
{
    $interval = @(date_create($dob)->diff(date_create('today')));
    return $interval->format('%y years, %m months, %d days');
}

echo 'Age: ' . calculateAge('20-5-1993');
// output
// Age: 24 years, 7 months, 16 days 
?>

As you can see, both methods are simple and have couple lines of code. Use whichever you want.

Read Also:

That explains about calculating age from date of birth in php. It's a handy feature for social networks and other apps. I hope it's useful to you. Please share the post in your social circle if you like it.

Get Zipcode From Address using PHP and Google Maps API

On 1/05/2018 Be the first to comment!

Hi! We were seeing about Google Maps API for a while, and today's post is also one on the line. In this tutorial, we are going to see how to get zipcode from address using php and google maps api. Sometimes you might have a large set of customers addresses without postal codes. In such cases you can rely on Google maps to provide the pin code you need. It serves queries related to addresses with less effort. So with the help of Google Maps Geocoding API you can easily extract the zip code from the address and I'm going to show you how to do it in php.

get zipcode from address php and google maps api

PHP - Get Zipcode from Address using Google Maps API:

Retrieving zipcode/pincode from the address is a two step process. First we have to get the latitude and longitude for the given address and then use them to get the zip code details.

The API offers two different types of services, geocoding and reverse geocoding of addresses and we have to use both to achieve the desired result.

This is the web service url we have to use,

http://maps.google.com/maps/api/geocode/json

With this, you have to attach the appropriate query parameters to the api url. The result will be returned as JSON.

Let's get started!

Step-1) Getting Latitude & Longitude from Address

<?php
$geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address");
$json = json_decode($geocode);
$latitude = $json->results[0]->geometry->location->lat;
$longitude = $json->results[0]->geometry->location->lng;
?>

Step-2) Getting Zipcode using Latitude, Longitude

<?php
$geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude");
$json = json_decode($geocode);

foreach($json->results[0]->address_components as $adr_node) {
    if($adr_node->types[0] == 'postal_code') {
        return $adr_node->long_name;
    }
}
?>

The following is the complete php function to retrieve zip code details from the provided address.

PHP Function:

<?php
function getZipcode($address)
{
    // get geocode
    $geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address");
    $json = json_decode($geocode);
    $latitude = $json->results[0]->geometry->location->lat;
    $longitude = $json->results[0]->geometry->location->lng;
    
    // get zipcode
    $geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude");
    $json = json_decode($geocode);
    
    foreach($json->results[0]->address_components as $adr_node) {
        if($adr_node->types[0] == 'postal_code') {
            return $adr_node->long_name;
        }
    }
    return false;
}
?>

The function getZipcode() takes up a single parameter $address and extracts postal_code from the provided address using geocode api.

Usage:

You have to call the above function like this in php.

<?php
// set address
$address = 'Brooklyn, NY, USA';
$address = str_replace(' ', '+', $address);
$zipcode = getZipcode($address);

if($zipcode)
    echo 'Zipcode: ' . $zipcode;
else
    echo 'Zipcode not found! Please try different address!!!';

// output
// Zipcode: 11216
?>

What the above function does is, it takes the address info and request Google API for its geocoding details. Receive the response, decodes the json string and extract the latitude and longitude values from it.

Next, request the API once again by passing the extracted geocoding values, but this time for address details with postal code. This step is called reverse geocoding. It again decodes the json response, iterate over to fetch and return the zipcode.

API Key:

Google imposes request limits per day for using the api. Therefore getting the api_key is the best way for uninterrupted work. Login to your Google account, get the api key and use it in the url like this,

https://maps.googleapis.com/maps/api/geocode/json?address=ADDRESS&key=YOUR_API_KEY

http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude&key=API_KEY;
Read Also:

That was all about fetching zipcode from address in php and google maps api. Although the process seems handful at first, it is really simple once you get to know it. I recommend you to use the api_key parameter with the url, since you can easily exceed the daily limit. I hope you like this post. Appreciate if you share it in your social circle.

How to Filter Multidimensional Array by Key Value in PHP

On 1/01/2018 Be the first to comment!

Hi! In today's post, let's see how to filter multidimensional array by key value in php. PHP offers extensive functions to manipulate arrays of which array_filter makes the unimaginable possible. The function allows you to filter elements of an array with custom callbacks.

Multi-dimensional arrays are complicated enough but filtering them by key value is a headache because you have to iterate over each element and look for the specific key values to filter it. But PHP's array_filter() function provides a short and simple way to filter multidimensional array by key and value. You have to use the appropriate callback filter and the rest is cake walk.

php filter multidimensional array by key value

PHP - Filtering Multidimensional Array by Key Value:

Before we start the process, a little intro about the function array_filter().

It let you to filter array by value using custom callback. It takes up three parameters, 1. the source, 2. callback function that acts as the conditional filter and 3. flag to define whether a key, value or both should be used for filtering.

Consider the following multi-dimensional array,

Array
(
    [0] => Array
        (
            [name] => John
            [email] => john@mydomain.com
            [dept] => Finance
        )

    [1] => Array
        (
            [name] => Lilly
            [email] => lilly@mydomain.com
            [dept] => Sales
        )

    [2] => Array
        (
            [name] => Austin
            [email] => austin@mydomain.com
            [dept] => HR
        )

    [3] => Array
        (
            [name] => Whites
            [email] => whites@mydomain.com
            [dept] => Finance
        )

    [4] => Array
        (
            [name] => Milan
            [email] => milan@mydomain.com
            [dept] => Sales
        )

)

Now let's see how to filter this array so that the result only contains the elements that have their 'dept => Sales'. Here 'dept' is the key and 'Sales' is the value.

<?php
$myarray = array(
    array("name"=>"John", "email"=>"john@mydomain.com", "dept"=>"Finance"),
    array("name"=>"Lilly", "email"=>"lilly@mydomain.com", "dept"=>"Sales"),
    array("name"=>"Austin", "email"=>"austin@mydomain.com", "dept"=>"HR"),
    array("name"=>"Whites", "email"=>"whites@mydomain.com", "dept"=>"Finance"),
    array("name"=>"Milan", "email"=>"milan@mydomain.com", "dept"=>"Sales")
);

$filter = "Sales";

$new_array = array_filter($myarray, function($var) use ($filter){
    return ($var['dept'] == $filter);
});

echo "<pre>";
print_r($new_array);
?>

Above code will produce the following output,

Output:

Array
(
    [1] => Array
        (
            [name] => Lilly
            [email] => lilly@mydomain.com
            [dept] => Sales
        )

    [4] => Array
        (
            [name] => Milan
            [email] => milan@mydomain.com
            [dept] => Sales
        )

)

Please note that we are filtering multi-dimensional array which is an array or arrays. So, here each element is itself another array. What the function did is, check each array against the given condition, and keep it in the result if it passes through the condition else remove it.

Filtering Array by Mutiple Key Values:

In the previous example, we have used a single conditional filter, but you can also filter it by multiple values.

Consider the following example,

<?php
$myarray = array(
    array("name"=>"John", "email"=>"john@mydomain.com", "dept"=>"Finance"),
    array("name"=>"Lilly", "email"=>"lilly@mydomain.com", "dept"=>"Sales"),
    array("name"=>"Austin", "email"=>"austin@mydomain.com", "dept"=>"HR"),
    array("name"=>"Whites", "email"=>"whites@mydomain.com", "dept"=>"Finance"),
    array("name"=>"Milan", "email"=>"milan@mydomain.com", "dept"=>"Sales")
);

$filter = array("Lilly", "Whites");

$new_array = array_filter($myarray, function($var) use ($filter){
    return in_array($var['name'], $filter);
});
echo "<pre>";
print_r($new_array);
?>

Output:

Array
(
    [1] => Array
        (
            [name] => Lilly
            [email] => lilly@mydomain.com
            [dept] => Sales
        )

    [3] => Array
        (
            [name] => Whites
            [email] => whites@mydomain.com
            [dept] => Finance
        )

)

In the above code, we have filtered the sourcearray only to contain those elements (arrays) which have their name in the list we provided. When you provide a separate filtering condition in the callback, you must include 'use' before it.

Read Also:

Likewise you can filter the multi dimensional array by key value with php. Filtering one dimensional or simply the array is much simpler that doing it with two or more dimensional. I hope this helps. Please share the post if you find it useful :)

Contact Form

Name

Email *

Message *