Free programming stuff https://freeprogrammingstuff.com Best and free portal for programming stuff Fri, 26 Jun 2020 04:38:17 +0000 en-CA hourly 1 Tutorial install myIgniter using built in PHP Web server https://freeprogrammingstuff.com/2016/10/19/tutorial-install-myigniter-using-built-php-web-server/ Wed, 19 Oct 2016 04:08:05 +0000 http://freeprogrammingstuff.com/?p=95 Continue reading "Tutorial install myIgniter using built in PHP Web server"]]> In this tutorial we try step by step installing myIgniter using built in PHP Web server start with installing PHP in command line until running myIgniter.

First things first we need :

Step 1 : Extract the files

Extract archive PHP.zip into “C:\” and extract myIgniter.zip into “C:\web\”

Step 2 : Configure php.ini

Copy “C:\php\php.ini-recommended” to “C:\php\php.ini”. There are several lines we need to change in the text editor (use search to find the current setting).

extension_dir = "C:/php/ext"

Enable extensions. This will depend on the libraries you want to use, but the following extensions should be suitable for the majority of applications (remove the semi-colon comment):

extension=php_curl.dll
extension=php_gd2.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo.dll
extension=php_pdo_mysql.dll
extension=php_xmlrpc.dll

Step 3 : Add C:\php to the path enviroment variable

To ensure Windows can find PHP, you need to change the path environment variable. From the Control Panel, choose System, (then “Advanced system settings”), select the “Advanced” tab, and click the “Environment Variables” button.

Scroll down the System variables list and click on “Path” followed by the “New” button. Enter “C:\php”.

path

Now OK your way out. You might need to reboot at this stage.

Step 4 : Run in command line

Try run “php -v” in command line.

command-line

make sure the result like screenshot.

Step 5 : Configure myIgniter

Configure file “application/config/database.php” we need to changes “hostname, username, password, database, dbdriver” with our current database. Then configure file “application/config/migration.php” set $config['migration_enabled'] = TRUE;

Step 6 : Running myIgniter in command line

In command line go to myIgniter directory “C:\web\myIgniter\” then run command “php -S localhost:8080”

running-command

Step 7 : Running migration data myIgniter

Open browser go to url “http://localhost:8080/migrate/index/3” number 3 is the current latest migration we can check in the directory “application/migrations” then use the latest number. If success it will appear “Success”. Now we success migrate data to our database next step we need to change $config['migration_enabled'] = TRUE; into FALSE again.

Step 8 : Start build perfect webapp with myIgniter

]]>
Making the most of the Google Maps API – Marking a path to a location https://freeprogrammingstuff.com/2016/10/12/making-google-maps-api-marking-path-location/ Wed, 12 Oct 2016 06:43:35 +0000 http://freeprogrammingstuff.com/?p=56 Continue reading "Making the most of the Google Maps API – Marking a path to a location"]]> Our app takes advantage of a JSON file containing the different bus lines and arrays of geographic points, the combination of which forms the route of the busses. A part of the array with coordinate points looks like this:

"coordinates": [
 [26.00671399999988,43.8541],
[26.006582999999882,43.85418],
[26.00640999999988,43.85422],
[26.006300999999883,43.85422]
]

Now, if we take all those points and fill the distance between them we would get a visual representation of the vehicles’ route on the map. Thankfully, Google Maps allows us to do just that.

The fetchRoutes method that we have seen in the initialization function just stores the routes in a variable for us to use later on.

Transporter.fetchRoutes = function () {
$.get("js/routes.json", function (data) {
routes = data.features;
})
}

When a user clicks on a bus number, we want to show him/her the route of the bus from its initial departure to its endpoint on the map.  We set up an event listener that would be set for all elements with the class of bus-num no matter if they existed when we were setting up the event listener thanks to jQuery’s event delegation (http://stackoverflow.com/questions/8459204/adding-event-listeners-to-current-and-future-elements-with-a-particular-class). Thereafter, we remove from the map any previous routes that could have been shown to the user due to his/her previous clicks.

$("body").on("click", ".bus-num", function () {
for (var x = 0; x < Transporter.globals.linePaths.length; x++) {
Transporter.globals.linePaths[x].setMap(null);
}

Following that, in the same event listener, we set up a variable cointaining only the lines/geographic points of the clicked bus number.

var self = $(this);
routeLines = routes.filter(function (route) {
return route.properties.line_name === self.attr("data-line")
})[0];

Following that, we format the coordinates that we have in the routeLines variable and create a new array with objects that have only thelat and lng properties that we would need to pass to the Google Maps API.

var lineCoords = [];
 
for (var j = 0; j < routeLines.geometry.coordinates.length; j++) {
 
lineCoords.push({
 
lat: routeLines.geometry.coordinates[j][1],
 
lng: routeLines.geometry.coordinates[j][0]
 
})
 
}

Now, for the cool stuff. We add and connect all those single points using the google.maps.Polyline method , passing it the array of lat/lng objects in a path property and we define a few properties which set the route to have green-ish color, to be fully opaque and give it an easily visible stroke weight.

var linePath = new google.maps.Polyline({
 
    path: lineCoords,
 
    geodesic: true,
 
    strokeColor: '#99ff00',
 
    strokeOpacity: 1.0,
 
    strokeWeight: 4
 
  });

And, voila. We have shown the user the full path from point A to point B.

Or have we? It seems like we have to add the path/route to the map before we can see it, so we type linePath.setMap(map); and we add the path/route to our array so that we can remove the path from the map later when the user wants to see the route for another bus.

You can try to make your Google Maps API-reliant app into a mobile app with Phonegap/Cordova. If you do this, you would not have to worry about users in some browsers having to give permission every few seconds as they will be asked only once and the users will have your app in their pocket!

]]>
Creating your first middleware in Laravel 5 https://freeprogrammingstuff.com/2016/10/04/creating-first-middleware-laravel-5/ Tue, 04 Oct 2016 03:23:08 +0000 http://freeprogrammingstuff.com/?p=35 Continue reading "Creating your first middleware in Laravel 5"]]> Middlewares can help us execute different application logic in numerous routes so that we do not repeat ourselves.

They are good for filtering HTTP requests. For example, you can create a middleware which redirects user that are not authorized to view a page to another page or you can create a middleware which disallows guests from accessing pages (in fact, Laravel has such a middleware built-in). You can create a middleware which sets some HTTP headers. For example, you can enable CORS so that AJAX requests can be made from everywhere to some particular routes.

To show you how to build a middleware we are going to build a middleware which gets some Geolocation information from the user’s IP address and makes it accessible to the controller. Then, any controller that uses that middleware in its route settings will be able to use the Geolocation information about the user. The Geolocation would be saved in the user’s session so that we do not make a request to the API every time a user requests a new page.

Creating a new middleware with Artisan

To make a new middleware we start our Command Line/Terminal, go to the directory where our Laravel project is and type: php artisan make:middleware getClientInformation. getClientInformation could be anything and it represents the name of our middleware (the appropriate file would be named getClientInformation in our case).

After you execute the command, you will see a file with the name getClientInformation.php in the directory path: app/http/middleware. We would have to insert our middleware functionality there.

Registering the middleware

Before that, we navigate to app/Http/Kernel.php and introduce our middleware to Laravel. Inside the  $routeMiddleware array we add the following index:

'getClientInfo' => \App\Http\Middleware\getClientInformation::class,

This would set a middleware available for use in our routes located in the routes.php file with the alias of getClientInfo. The value is just the namespace of our middleware (which is automatically set up by the Terminal command that we typed in the beginning).

In the created file, you can see the namespace:

namespace App\Http\Middleware;

The class is automatically created:

class getClientInformation

{

Therefore, in Kernel.php’s $routeMiddleware property our middleware’s namespace would look like the following:

\App\Http\Middleware\getClientInformation::class,

Using the middleware

Now, to use the our middleware, we can go to our routes.php file and provide an array of options in which we declare a middleware key with value corresponding to the key we have put in the Kernel.php file (the $routeMiddleware array). Our middleware would now be used for that route. We would not create a controller here but you can (we will just provide an anonymous function). In our controller, we will get the clientInfo attribute that is set on the request by our middleware and display the properties in the user’s browser.

Route::get("/", ['middleware' => "getClientInfo", function() {

$clientInfo = Request()->attributes->get("clientInfo");

echo "It seems like you are based in " . $clientInfo->city . ", " . $clientInfo->country . ".<br>";

echo "Is your region (" . $clientInfo->regionName . ") nice to live in?";

}]);

Creating the actual Laravel 5 middleware

What is inside the middleware file (app/Http/Middleware/getClientInformation.php) is mostly boilerplate created by our initial Artisan command. We just type inside the handle method. There, we check if there is a session property called clientInfo – if there is none we make a request to the API, provide it the client IP address, set the session property to the API’s response and bind the API’s response to the request. If there is already a session property with the Geolocation data – we just bind it to the request attributes (we can retrieve it from the controllers which use the middleware)

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
use Illuminate\Support\Facades\Request;
 
use Illuminate\Support\Facades\Session;
 
 
class getClientInformation
{
 
    /**
 
     * Handle an incoming request.
 
     *
 
     * @param  \Illuminate\Http\Request  $request
 
     * @param  \Closure  $next
 
     * @return mixed
 
     */
 
    public function handle($request, Closure $next)
 
    {
 
        if (!Session::get("clientInfo")) {
 
            $ip =  Request::ip() && Request::ip() !== "127.0.0.1" ? Request::ip() : "126.15.33.125";
 
            $data = json_decode(file_get_contents("http://ip-api.com/json/" . $ip));
 
            Session::set("clientInfo", $data);
 
            $request->attributes->add(["clientInfo" => $data]);
 
        }
 
        $request->attributes->add(["clientInfo" => Session::get("clientInfo")]);
 
        return $next($request);
 
    }
 
}

Conclusion

Now, our index route will return a response similar to the one in the picture below:

sample

]]>
Web Designer Vs. Web Developer: What’s the Difference? https://freeprogrammingstuff.com/2016/09/23/web-designer-vs-web-developer-whats-difference/ Fri, 23 Sep 2016 17:58:14 +0000 http://freeprogrammingstuff.com/?p=91 Continue reading "Web Designer Vs. Web Developer: What’s the Difference?"]]> Web Designers create the visual aesthetic of a website with a layout program or Photoshop. This includes the “UI” or nav bar, background image, graphics, menus etc. they then export these images as 72dpi web files. a designer is responsible for the look and feel of a website, and keeping it consistent with current brand standards.

A Web Devloper, takes the designers plan and combines the designers images into an html framework. The developer is responsible for the function and operation of the website.

These are two very different skill sets one is creative, the other is scientific. Some peoplecan do both, but very few do either well.

A web designer:

  • Focuses on look and feel of a website
  • Uses HTML, CSS, and JavaScript
  • Is competent in color scheming, graphic design, and information flow
  • Creates a great user experience
  • Is right-brained: Strong intuition, creativity, & imagination
  • Portfolio is worth more than a degree
  • Median salary: $47,820

A web developer:

  • Creates the inner workings of a website
  • Is competent in programming languages (PHP, .NET, Python, C, Ruby)
  • Develops the user interface
  • Is left-brained: logic, linear thinking, technical
  • Hands-on coding experience is required (either your own products or github)
  • Median salary: $85,430

So which profession do you choose?

Everyone I spoke to recommended not to.

Haney thinks it is important to not think of web design and development as two entirely different entities.

“Without them both, there is no usable web. Whether you’re in charge of both or working within a team doing one or the other, make sure your process flows in both directions,” he says.

If you don’t know what you want to do and are still deciding between the two, then try working with Photoshop one day, and Sublime the next. Like Steve Jobs said, “As with all matters of the heart, you’ll know when you find it. And like any great relationship, it just gets better and better as the years roll on.” So start looking. Go find it.

Do either of these careers sound interesting to you? Let us know in the comment section or read some of our related articles below.

]]>
Creating an Init Script in Ubuntu 14.04 https://freeprogrammingstuff.com/2016/09/14/creating-init-script-ubuntu-14-04/ Wed, 14 Sep 2016 05:19:23 +0000 http://freeprogrammingstuff.com/?p=87 Continue reading "Creating an Init Script in Ubuntu 14.04"]]> In Ubuntu, you create init scripts using the SysV init system. Details are here. In this article, I will create a very simple script to start and stop Tomcat.

In this tutorial, our goal is to start and stop Tomcat as the user “joe”. First, we will create a script called tomcat in /etc/init.d folder.

#! /bin/sh
### BEGIN INIT INFO
# Provides: tomcat
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Tomcat
# Description: This file starts and stops Tomcat server
# 
### END INIT INFO

TOMCAT_DIR=/home/joe/programs/apache-tomcat-8.0.5/
export JAVA_HOME=/home/joe/programs/jdk1.8.0_05

case "$1" in
 start)
   su joe -c $TOMCAT_DIR/bin/startup.sh
   ;;
 stop)
   su joe -c $TOMCAT_DIR/bin/shutdown.sh
   sleep 10
   ;;
 restart)
   su joe -c $TOMCAT_DIR/bin/shutdown.sh
   sleep 20
   su joe -c $TOMCAT_DIR/bin/startup.sh
   ;;
 *)
   echo "Usage: tomcat {start|stop|restart}" >&2
   exit 3
   ;;
esac

The “Default-Start” field specifies the run levels in which the script will be run with the “start” argument. “Default-Stop” does the reverse. For example, when the machines shuts down and enters run level 1, the script will be run with the “stop” argument.

Make the script executable:

sudo chmod a+x tomcat

Always unit test the script by running it from the command line. For example:

sudo ./tomcat start
sudo ./tomcat stop

If all goes well then register the script as an init script:

sudo update-rc.d tomcat defaults

Reboot the machine and make sure that Tomcat has started.

]]>
Session Timeout And Keep-alive Plugin With jQuery – sessionTimeout https://freeprogrammingstuff.com/2016/09/11/session-timeout-keep-alive-plugin-jquery-sessiontimeout/ Sun, 11 Sep 2016 09:15:19 +0000 http://freeprogrammingstuff.com/?p=84 Continue reading "Session Timeout And Keep-alive Plugin With jQuery – sessionTimeout"]]> sessionTimeout is an useful jQuery plugin that popups a timeout dialog with ‘Log out’ and ‘keep Alive’ options after a certain idle time. If ‘Log Out’ is clicked, the page is redirected to a specified URL. If ‘Keep Alive’ is clicked, a keep-alive URL is requested through AJAX. If no options is selected after another set amount of time, the page is automatically redirected to a timeout URL.

Basic usage:

1. Include the jQuery sessionTimeout.js script after you’ve loaded jQuery JavaScript library.

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="jquery.sessionTimeout.js"></script>

2. Include jQuery UI’s JavaScript and CSS for the session timeout dialog.

<link rel="stylesheet" href="jquery-ui.min.css">
<script src="jquery-ui.min.js"></script>

3. Initialize the plugin on document ready. In this case, the plugin will display a warning dialog after 3 seconds and automatically redirect the page after 30 seconds.

$.sessionTimeout({
  warnAfter: 3000,
  redirAfter: 30000
});

4. More configuration options.

$.sessionTimeout({

  // custom warning message
  message: 'Your session is about to expire.',

  // keep alive url
  keepAliveUrl: '/keep-alive',

  // request type
  keepAliveAjaxRequestType: 'POST',

  // redirect url
  redirUrl: '/timed-out',

  // logout url
  logoutUrl: '/log-out',

  // 15 minutes
  warnAfter: 900000, 

  // 20 minutes
  redirAfter: 1200000, 

  // appends time stamp to keep alive url to prevent caching
  appendTime: true 
  
});

 

]]>
AngularJS vs. jQuery: What are the key differences https://freeprogrammingstuff.com/2016/09/05/angularjs-vs-jquery-comparing-two-popular-javascript-tools/ Mon, 05 Sep 2016 03:53:18 +0000 http://freeprogrammingstuff.com/?p=76 Continue reading "AngularJS vs. jQuery: What are the key differences"]]> jQuery is a library and Angular is a MVVM framework. jQuery is included in Angular.js file so you can use the jQuery functions and features within Angular.

WHAT IS JQUERY?

jQuery is a DOM manipulation library that makes it easier to use JavaScript on your website. JavaScript is the language of choice for making webpages dynamic and interactive. jQuery takes the complex code that would be required to make AJAX calls or manipulate the DOM and wraps them into simple methods you can call with a single line of JavaScript.

Here are some of the key technical features that are available in the jQuery library:

  • DOM manipulations are a lot easier with the help of jQuery
  • CSS manipulation
  • It simplifies many complicated things attached to JavaScript – e.g. Ajax calls.
  • Event handling
  • Effects and animations
  • Cross-browser compatibility
  • Lightweight (minified and gzipped)

jQuery makes no assumptions about your web technology stack, and may be used in conjunction with other frameworks, including AngularJS. In fact, AngularJS is built off of an implementation of jQuery called jqLite.

WHAT IS ANGULARJS?

AngularJS is a JavaScript framework that was specifically designed to help developers build SPAs in accordance with best practices for web development. By providing a structured environment for building SPAs, the risk of producing “spaghetti code” is greatly reduced. AngularJS also provides a suite of features that help the developer do more with less code than would be required with “vanilla JavaScript” (developer speak for plain, simple JavaScript without the use of any libraries) and jQuery.

Some of the key features AngularJS adds on top of jQuery are:

  • Angular directives (extension to HTML)
  • Templating
  • Dependency injection
  • Two-way data binding
  • Support for MVC
  • RESTful API
  • Form validation

It goes without saying that AngularJS also abstracts the DOM, has a system for managing event handlers, and supports AJAX/JSONP.

As far as choosing between Angular JS and jQuery, it always depends on the nature of the application. If we are talking about a complex application, then Angular JS is the best otherwise go with jQuery.

]]>
How Traits in PHP, Explanated with Example https://freeprogrammingstuff.com/2016/09/02/traits-php-explanated-example/ Fri, 02 Sep 2016 04:13:41 +0000 http://freeprogrammingstuff.com/?p=73 Continue reading "How Traits in PHP, Explanated with Example"]]> PHP 5.4 introduces the concept of traits. In PHP 5.4 version several new features was introduced, one such feature is PHP traits.

PHP traits help you to minimize code duplication in your codebase. Until the concept of traits, PHP uses classical inheritance model in which one class can inherit only one class. But sometimes, it is beneficial to inherit from multiple classes to avoid code duplication. To solve this problem, PHP community introduces the concept of traits.

PHP Traits

Trait allows us to reuse sets of methods freely in several independent classes living in different class hierarchies. In simple words, it gives you the flexibility to “copy and paste” code between classes.

trait Create {
 
    public function initiate($item){
              return  "item created";      
    }  
}
 
class some
{
   use Create;  // Calling trait
 
   public function status()
   {
        return "Job completed";
   }
 
}
 
   $demo = new Some;
   echo $demo->initiate("");
   echo $demo->status();

How PHP Traits Work

In the above example, I have created one trait create and used in a class some. When I created an object of some class, it can use the method initiate despite it is not being defined in some class.

Multiple Traits

We can use multiple traits in our class by listing them in use statement separated with a comma.

trait Create {
 
    public function initiate($item){
              return  "item created";      
    }  
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete;  // Calling multiple traits
 
}
NOTE – If two Traits insert a method with the same name, a fatal error is produced. If the conflict is not explicitly resolved.
trait Create {
 
    public function message(){
              return  "item created";
    }
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete;  // Calling multiple traits
 
}

Both traits (Create and Complete) has same method message. It will throw a fatal error if the conflict is not explicitly resolved.

PHP Fatal error:  Trait method message has not been applied, because there are collisions with other trait methods

To resolve this fatal error, we need to choose one of the conflicting methods using the insteadof operator.

trait Create {
 
    public function message(){
              return  "item created";
    }
}
 
trait Complete {
 
   public function message() {
          return "Completed";
   }
}
 
 
class some
{
   use Create, Complete {
           Create::message insteadof Complete;
          }
 
}

Traits Vs Interface – Difference between Traits and Interfaces

An Interface is a contract that says “this object is able to do this thing”, whereas a Trait is giving the object the ability to do the thing.

i) Using traits we can implement a method body while in an interface we can not provide a default implementation of a method body.

ii) We can implement multiple interfaces as well use traits in a class.

iii) An interface is used for Polymorphism(It means classes have different functionality while sharing a common interface), while we cannot use trait for Polymorphism.

 

]]>
Multiple File Upload in PHP using DropzoneJS – Drag and Drop https://freeprogrammingstuff.com/2016/08/29/multiple-file-upload-php-using-dropzonejs-drag-drop/ Mon, 29 Aug 2016 06:08:50 +0000 http://freeprogrammingstuff.com/?p=69 Continue reading "Multiple File Upload in PHP using DropzoneJS – Drag and Drop"]]> How to create drag and drop multiple file upload in PHP using DropzoneJS. In this tutorial you’ll learn about how to build multiple file upload feature using DropzoneJs.

 

DropzoneJS is highly customizable, an open source library that provides drag’n’drop file uploads with image previews.

In this tutorial, i’ll show you how to use DropzoneJs to create nice drag and drop file upload feature.

Create Drag and Drop Multiple File Upload using DropzoneJS

To use DropzoneJS first download and include it’s CSS and Js.

Download Dropzone js

Download CSS file

Now let’s create a form and you are done. For using this library you just need to write minimal code and rest everything is included by DropzoneJS.

<form action="example.php" method="post" class="dropzone" id="my-awesome-dropzone" enctype="multipart/form-data">
 
    <div class="dropzone-previews"></div>
 
    <div class="fallback">
       <input name="file" type="file" multiple/>
    </div>
</form>
 
<button type="submit" id="submit-all" class="btn btn-primary btn-xs">Upload the file</button>

We have written the html code. Let’s write PHP code to handle multiple upload as this library doesn’t handle server-side implementation. This short PHP snippet upload the file in images folder. You can upload this file in any folder you want.

 // Multiple file upload
          
          foreach($_FILES['file']['name'] as $index=>$name){
            
             $filename = $name;
            
             if(!file_exists("images/".$filename)){
                
                    move_uploaded_file($_FILES["file"]["tmp_name"][$index],"images/" . $filename);
            
              }
            
          }

DropzoneJS is highly customizable so you can easily customize it’s behaviour.

<script type="text/javascript">
// The camelized version of the ID of the form element
 
Dropzone.options.myAwesomeDropzone = {
 
// set following configuration
 
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 10,
    maxFiles: 10,
    addRemoveLinks: true,
    previewsContainer: ".dropzone-previews",
    dictRemoveFile: "Remove",
    dictCancelUpload: "Cancel",
    dictDefaultMessage: "Drop the images you want to upload here",
    dictFileTooBig: "Image size is too big. Max size: 10mb.",
    dictMaxFilesExceeded: "Only 10 images allowed per upload.",
    acceptedFiles: ".jpeg,.jpg,.png,.gif,.JPEG,.JPG,.PNG,.GIF",
 
   // The setting up of the dropzone
   init: function() {
     var myDropzone = this;
   // Upload images when submit button is clicked.
 
   $("#submit-all").click(function (e) {
       e.preventDefault();
       e.stopPropagation();
       myDropzone.processQueue();
    });
   // Refresh page when all images are uploaded
 
    myDropzone.on("complete", function (file) {
         if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
        window.location.reload();
        }
      });
 
    }
 
}
</script>

Check complete DropzoneJS configuration and customize them as per your need.

]]>
How to create RESTful API / Web Service with Slim, PHP & MySQL https://freeprogrammingstuff.com/2016/08/28/create-restful-api-web-service-slim-php-mysql/ Sun, 28 Aug 2016 11:05:47 +0000 http://freeprogrammingstuff.com/?p=65 Continue reading "How to create RESTful API / Web Service with Slim, PHP & MySQL"]]> For this article we will be using the slim PHP micro framework to implement the RESTful API. Slim was chosen because it is very light weight, clean, supports all the HTTP methods, and also provides support for middleware layers. Along with slim you will need a web server (apache or nginx), PHP, and MySQL installed before proceeding. Once you’ve gotten all the necessary files you can begin.

This tutorial gives you complete examples of creating full Restful API using multiple HTTP methods like GET,POSTPUT and DELETE. You would get the output in JSON and create a user data for all options, download code available.

HTTP methods:

GET: Used to retrieve and search data.

POST: Used to insert data.

PUT: Used to update data.

DELETE: Used to delete data.

Add below .htaccess file in your api folder http://localhost/api

RewriteEngine On
 
RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

Database design and table:
database name => rest
table name => restAPI
column names => id, name, email, ip, date
db.sql
Database file run in your MySQL to create database and add data in table.

CREATE TABLE `rest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

Database configuration

Edit database name, user and password as per your configuration

function getConnection() {
    try {
        $db_username = "DATABASE_NAME";
        $db_password = "********";
        $conn = new PDO('mysql:host=localhost;dbname=root', $db_username, $db_password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    return $conn;
}

Used PDO connection you can use as per your ease and I have added this function in same methods file you can also manage them as per your projects.

Implement API

We have created 6 API methods

  1. getUsers
  2. getUser
  3. findByName
  4. addUser
  5. updateUser
  6. deleteUser

Define HTTP routes:

$app->get('/users', 'getUsers'); // Using Get HTTP Method and process getUsers function
$app->get('/users/:id',    'getUser'); // Using Get HTTP Method and process getUser function
$app->get('/users/search/:query', 'findByName'); // Using Get HTTP Method and process findByName function
$app->post('/users', 'addUser'); // Using Post HTTP Method and process addUser function
$app->put('/users/:id', 'updateUser'); // Using Put HTTP Method and process updateUser function
$app->delete('/users/:id',    'deleteUser'); // Using Delete HTTP Method and process deleteUser function
$app->run();

These all routes call individual function as defined above and in the last $app->run(); used to run Slim application.

let’s see functions:

1. getUsers: $app->get(‘/users’, ‘getUsers’);

function getUsers() {
    $sql_query = "select `name`,`email`,`date`,`ip` FROM restAPI ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt   = $dbCon->query($sql_query);
        $users  = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"users": ' . json_encode($users) . '}';
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }    
}

This function simply return all users information as you can see in this query, to call this API use this URL http://localhost/api/users this is it for your first API using get route.

2. getUser: $app->get(‘/users/:id’,    ‘getUser’); In this route we are sending id.

function getUser($id) {
    $sql = "SELECT `name`,`email`,`date`,`ip` FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $user = $stmt->fetchObject();  
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function check record of given id and return if found any thing,  to call this API use this URL http://localhost/api/users/1.

3. findByName: $app->get(‘/users/search/:query’, ‘findByName’); Route is used to search record with extra parameter and a search query with simple get method.

function findByName($query) {
    $sql = "SELECT * FROM restAPI WHERE UPPER(name) LIKE :query ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $query = "%".$query."%";
        $stmt->bindParam("query", $query);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"user": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function search in database for your given query, to call this API use this URL http://localhost/api/users/search/f.

4. addUser: $app->post(‘/users’, ‘addUser’); API used to add new record and accept post.

function addUser() {
    global $app;
    $req = $app->request(); // Getting parameter with names
    $paramName = $req->params('name'); // Getting parameter with names
    $paramEmail = $req->params('email'); // Getting parameter with names
 
    $sql = "INSERT INTO restAPI (`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("ip", $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        $user->id = $dbCon->lastInsertId();
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API accept post request and insert submitted data in your database as we received parameters in starting of that function. To call this API I have used cURL, you can use jQuery or any other technique.

<?php
if($_POST){
    echo post_to_url("http://localhost/users", $_POST);
} else{
 ?>
ADD RECORD.
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="POST" />
<input type="submit" value="A D D" />
</form>
<?php 
}
?>

This form will be submitted to your action file and there is a curl and that curl will post data as I have used a hidden input of _METHOD with POST value this is because some times your cURL don’t Post data to API (faced this so used this for post as well) and Slim give us this functionality to method override and as our modern browsers do not have native support to PUT and delete so we have to use method overriding like below.

<input type="hidden" name="_METHOD" value="POST" /> <!-- POST data -->
<input type="hidden" name="_METHOD" value="PUT" /> <!-- PUT data -->
<input type="hidden" name="_METHOD" value="DELETE" /> <!-- DELETE data -->

cURL function to post data:

function post_curl($_url, $_data) {
   $mfields = '';
   foreach($_data as $key => $val) { 
      $mfields .= $key . '=' . $val . '&'; 
   }
   rtrim($mfields, '&');
   $pst = curl_init();
 
   curl_setopt($pst, CURLOPT_URL, $_url);
   curl_setopt($pst, CURLOPT_POST, count($_data));
   curl_setopt($pst, CURLOPT_POSTFIELDS, $mfields);
   curl_setopt($pst, CURLOPT_RETURNTRANSFER, 1);
 
   $res = curl_exec($pst);
 
   curl_close($pst);
   return $res;
}

5. updateUser: $app->put(‘/users/:id’, ‘updateUser’); This route accept put HTTP method.

function updateUser($id) {
    global $app;
    $req = $app->request();
    $paramName = $req->params('name');
    $paramEmail = $req->params('email');
 
    $sql = "UPDATE restAPI SET name=:name, email=:email WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("id", $id);
        $status->status = $stmt->execute();
 
        $dbCon = null;
        echo json_encode($status); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function update your data by id, to call this API we need to again use cURL and HTML form.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST); // add id after last slash which you want to edit.
} else{
UPDATE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to update" /><br>
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="PUT" />
<input type="submit" value="U P D A T E" />
</form>
<?php 
}
?>

6. deleteUser: $app->delete(‘/users/:id’,    ‘deleteUser’); Route used to delete specific ID.

function deleteUser($id) {
    $sql = "DELETE FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $status->status = $stmt->execute();
        $dbCon = null;
        echo json_encode($status);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function accept HTTP delete request and to send HTTP delete method we have to used method overriding using our hidden field named _METHOD and value will be DELETE form and cURL code given below.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST);
} else{
 ?>
DELETE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to delete" /><br>
<input type="hidden" name="_METHOD" value="DELETE" />
<input type="submit" value="D E L E T E" />
</form>
 <?php 
}
?>

That’s all for our one of the biggest tutorial for RESTful API, I hope you like this tutorial and please don’t forget to give us your feedback and any issue you have faced in this tutorial please do comment we try our level best to solve your problems.

]]>