How to Install Composer on Windows with XAMPP

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

Now-a-days, many modern php frameworks like laravel, symfony, codeigniter and other libraries use the composer to manage their dependencies. So you need composer to install them on your machine. In case you don't know, Composer is the tool for dependency management in php. It allows you to declare the dependency libraries and packages required for a project and it will install, update and manage them for you. Composer will never maintain anything globally by default but rather on per-project basis.

You need PHP 5.3.2 and above to use Composer. So make sure the system requirements are met before installing it on your machine. In addition, you must also make some changes to the php settings to make it work.

install composer on windows xampp

Change Settings on php.ini:

I hope you have XAMPP installed already on your machine. So before composer installation, do the following changes on your php.ini file.

Go to [path-to-xampp]/php folder and open php.ini file.

Locate the below lines one by one and remove the semicolon (;) from the start.

extension=php_openssl.dll
extension=php_curl.dll
extension=php_sockets.dll

Save the file.

Install Composer on Windows:

STEP-1) First download composer for windows and click on the exe file. This will launch the setup for installing composer on your system. Click 'Next'.

install composer step-1

STEP-2) Next you need to select the path to the php executable file. Just click on the 'Browse' button and select 'php.exe' file. It can be found inside [path-to-xampp]/php folder. Click 'Next'.

install composer step-2

STEP-3) Now a window appears for proxy settings. Just leave it blank for now and click on 'Next' button.

install composer step-3

STEP-4) Finally the ready to install window pops up. Click on 'Install' to start installing the tool.

install composer step-4

Done! Once you finished installing composer, you can check it via command line.

Click on 'Start' > 'Run' dialogue, type cmd and click 'OK'.

On the command prompt, simply type composer and hit enter. If composer is successfully installed on your windows machine, you will see the below screen.

composer command screen

Restart your machine and launch 'XAMPP' control panel and start using composer. The same procedure can be used to install composer for 'WAMP' stack or even if you have installed php separately.

Read Also:

How to Change Apache and MySQL Port Number in XAMPP Localhost

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

Hi! I'm going to show you how to change the apache and mysql port number in xampp localhost. In case you wonder why you should change the port number of a web server, here is the answer. It's not unlikely for you to run multiple PHP versions on a same machine or to run IIS or JBoss simultaneously with Apache.

When you start a web server, it occupies the default HTTP port '80'. If you try to run the second one, it will fail since the port is already occupied. So unless you change the port for the latter, you can't run more than one web server at once. Below we will see the ways to change the port no. for apache and mysql.

xampp change apache port number localhost

To Change Apache Port Number:

Stop Apache server and exit XAMPP control panel if it is already running.

First you must change the HTTP port.

Go to [path-to-xampp-folder]/apache/conf folder and open http.conf file.

The default port for Apache is '80'. Unless you have changed it, this is the port number you must replace.

Now look for the line,

Listen 80

And then change the port no. to some unused port like this,

Listen 8012

Then search for the line,

ServerName localhost:80

And replace '80' with the new port no like this,

ServerName localhost:8012

Save the file.

Next you must change the SSL port.

Open [path-to-xampp-folder]/apache/conf/extra/httpd-ssl.conf file and search for the lines,

Listen 443
<VirtualHost _default_:443>
ServerName localhost:433

Replace '443' port with something else,

Listen 444
<VirtualHost _default_:444>
ServerName localhost:444

Save the file.

Done! Now restart Apache and access the url http://localhost:8012 on browser. If everything goes fine, you will see the xampp home page.

Please remember to use the port number along with local host to access it. This is not required when you leave apache to run on the default port itself.

To Change MySQL Port:

Just like Apache, you can also change the default port used by MySQL Server which is '3306'.

To do this, go to [path-to-xampp-folder]/mysql/bin/ and open the file my.ini.

Locate the line containing '3306' no. and change it to '3310' or something else and save. Please make sure the new port number is not used by any other service.

You can use 'Netstat' to check all used ports on your system.

That's it. You have successfully changed the default port numbers of apache and mysql server on xampp server. The same procedure can be applied for 'WAMP' and 'LAMP' stacks. For LAMP, you can locate the files on 'usr/bin/apache' directory.

Read Also:

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.

How to Create Custom Library in CodeIgniter

On 4/25/2018 Be the first to comment!

Hi, today let's see how to create custom library in codeigniter. CodeIgniter offers a rich set of libraries and helpers for robust application development. In general, a library is a class file used to group similar functionalities into a single file. Now we can do the same with helper but the libraries have their own object to store relevant data.

Below I'll show you how to create your own class libraries in CI. You must store these library files inside the 'application/libraries' folder. This will keep them separate from the native libraries of the framework.

create custom library in codeigniter

CodeIgniter - Create Custom Library:

CodeIgniter is a flexible MVC framework and allows you to,

  1. Create new custom libraries.
  2. Extend existing libraries to include additional functionalities to them.
  3. Replace native libraries completely with your own version.

I'm going to show you an example where I create a custom library to export the database table as a json string.

STEP-1) Create a library named 'Mylib.php' inside the 'application/libraries' folder. Make sure the file name matches the class name.

Mylib.php

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

class Mylib
{
    public function to_json($tblname)
    {
        $CI =& get_instance();
        $CI->load->database();
        $query = $CI->db->get($tblname);
        return json_encode($query->result(), JSON_PRETTY_PRINT);
    }
}
?>

In the 'Mylib' class, I have added a member function to_json() which takes up a database table name as a parameter, fetch and return the data as json.

STEP-2) Next we need a controller file to test the library. So create a controller 'TestController.php' within 'application/controllers' folder.

TestController.php

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

class TestController extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }
    
    function index()
    {
        // code
    }
}
?>

STEP-3) Now load the library within the controller's index() function.

$this->load->library('mylib');

You can also auto load the library inside 'application/config/autoload.php' file. Just look for the line, $autoload['libraries'] and add the library name. Auto loading will make it available for the entire application.

STEP-4) Then call the to_json() function to export the database table as json.

$json = $this->mylib->to_json('customers');
print '<pre>' . $json . '</pre>';

Now running the 'TestController' will output the data from the given table as a json string on the browser.

This is just a simple example of what a custom library can do.

Extending a Native Library:

Sometimes you may want to include some additional functions to a native library. In such case you can just extend the library like this,

class MY_Email extends CI_Email
{

    public function __construct()
    {
        parent::__construct();
    }
    
    public function my_function()
    {
        // code goes here
    }
}

Please note that while extending a library you must set the prefix 'MY_' before the class name.

And you can change this prefix inside 'application/config/config.php' file. Just search for the below line and replace it with your choice of prefix.

$config['subclass_prefix'] = 'MY_';

To use my_function() in your application, load the 'email' library like you always do and access the function like this,

$this->load->library('email');
$this->email->my_function();

Replacing the Native Library:

In case you want to rewrite an entire native library, you can simply replace it with your own version. For example, to replace the 'Email' library, create a file 'Email.php' inside 'application/libraries' folder and declare the class like this,

class CI_Email
{
    // code
}

And to use the class, you can simply load it on your controller or view like this,

$this->load->library('email');
Also Read:

That explains about creating custom libraries in codeigniter. I have also discussed about other ways of working with libraries. Just make sure to place all your library files inside 'application' > 'libraries' path and you are good to go. I hope you find this tutorial useful. Please share it on social media if you like it.

How to Import CSV File into MySQL with LOAD DATA INFILE

On 4/18/2018 Be the first to comment!

I tried to import a csv file into mysql with php script. It is a simple solution if you have a small set of data to import. But if you have hundreds of thousands of records, don't even think about it. You need something different to read through a large dataset quickly. MySQL's LOAD DATA INFILE command works like a charm and can be executed from the command line.

Using LOAD DATA INFILE allows you to load csv or any other delimited data file to the mysql table with a single command. It comes with several options and we will see below what they are and how to use them to import the csv data set into the mysql table.

Using LOAD DATA INFILE Command:

The LOAD DATA INFILE command in mysql loads data from a file into the table at high speed. The file path specified must be absolute or relative.

1. Importing CSV File into MySQL:

Let's say we have a mysql table 'customers' with the following structure.

MySQL Table: Customers
CREATE TABLE `customers`(
    `id` INT(8) NOT NULL ,
    `name` VARCHAR(30) NOT NULL ,
    `email` VARCHAR(40) NOT NULL ,
    `location` VARCHAR(25) NOT NULL ,
    PRIMARY KEY (`id`)
);

And a csv file customers.csv with data that we want to insert into the 'customers' table.

CSV File: Customers.csv
csv file to import into mysql

Now to import the csv data into the table, use the following sql statement.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABL    E customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Executing the above sql will import records to the given 'customers' table.

customers mysql table after running load data infile command

Our csv file has a column header as the first row, so we used the option IGNORE 1 LINES which will skip the first row. If you don't have the column header, don't use it.

Also make sure the file path is correct. You can use the format 'c:/tmp/customers.csv' or 'c:\\tmp\\customers.csv'.

This method will only work when your mysql table has the same sequence of columns as of the csv file.

2. Importing File with Different Column Sequence from Table:

Consider the scenario where your table and csv file column sequence are different. In this case, you must explicitly specify the order of the column name to ensure that the data is imported correctly.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

3. Importing Data to Remote MySQL Database Server:

If you have your file on the local machine and not on the server, use the word LOCAL. This will import file from the client (local system) to a remote mysql database server.

LOAD DATA LOCAL INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

When you include the LOCAL option, the file is expected to be located on the client and not on the server.

You can also use the mysqlimport utility to load csv data into the database. It's very similar to LOAD DATA INFILE, except that mysqlimport supports multiple file loading and the latter does not.

Read Also:

If you have a large dataset to import, go for the LOAD DATA INFILE command, as it is extremely faster than doing it with any other script. I hope this tutorial is useful to you. Please share it on social media if you like it.

How to Add Select All Options to jQuery Select2 Plug-in

On 4/09/2018 Be the first to comment!

Hi, in this post let's see how to add select all options to jQuery Select2 plugin. Select2 is an excellent alternative to the standard HTML selection box that supports all its functions and provides greater flexibility. The plug-in is easy to setup and use. It supports multiple selection options where the selected elements will be added as pills to the top text box. You can also tag, search and load remote data-sets to select2 control.

Below we will see how to use select2 in your web projects, and select all options at once by ticking a check box using jquery.

jquery select2 select all options on click

How to Use Select2 jQuery Plug-in?

To implement Select2 plug-in in your projects, create a regular drop-down box with html markup as usual.

HTML:

<select id="states" style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

This would produce a select box like this,

standard html select box example

Now load the library files for jquery and select2 on the html page. Do it only once on a page.

CSS:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

JS:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

Finally bind the select2() method to the dropdown in this way,

$(document).ready(function() {
    $('#states').select2();
});

It will initialize the select2 control and convert the plain dropdown to this,

select2 single select example

Please note that you must wrap your code within the $(document).ready() block. This will ensure that the DOM is ready before initializing the select2 control.

Select2 Multiple Select Box:

Select2 also supports multiple selection option. All you have to do is to declare the multiple attribute to the input. This will add the selected options as pills to the text box at the top of the control.

Example:

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
});
</script>

The above example will produce a dropdown box like this,

select2 multi select example

Add Select All Option to jQuery Select2:

Select2 also supports selecting all options at once from the list. Here we'll see how to select all the options when the user ticks the 'Select All' checkbox.

First create the markup for the multi-value select box and a check box for selecting all option.

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<input id="chkall" type="checkbox" >Select All

Now add this java script to the page.

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
    
    $("#chkall").click(function(){
        if($("#chkall").is(':checked')){
            $("#states > option").prop("selected", "selected");
            $("#states").trigger("change");
        } else {
            $("#states > option").removeAttr("selected");
            $("#states").trigger("change");
        }
    });
});
</script>

The above script will be executed by onclick() event of the check box. If checked, the script will set all the options of the select control as selected.

If you think this will alone do the job, you're wrong. This will simply keep all items in the dropdown selected, but will not add the selected items to the top of the control. For that we have to explicitly trigger the 'change' event.

select2 select all options example

Read other tutorials of select2,

That explains about jquery select2 and selecting all the options at once on click of the checkbox. The plugin offers so many customizations and adds flexibility to the standard html select box. I hope you like this tutorial. Meet you in another interesting post. Good day!

Send HTML Email in PHP via SMTP

On 4/06/2018 5 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:

Contact Form

Name

Email *

Message *