SlimAPI Framework Installation

Nowadays, The internet is full of third-party and custom APIs that offer a wide range of functionalities and Features. PHP offers several frameworks for web app, mobile app api development rapidly. However, time is always the crucial part of web developers and the app needs to be pushed at an impossible deadline. In such times, frameworks are the best option for rapid application development.

In this atricle, I will introduce you to Slim framework for PHP. Slim is fast becoming the most-opted framework for API development and small web apps as well as large web apps and mobile application development backend api. Although you can create REST API in several other frameworks like CakePHP, Symfony Laravel, Codeigniter, they have a steep learning curve and are often too cumbersome to use in rapid development scenarios.

Slim Frameword is microframe work which is only created for the developer who choose to develop apis.

Understanding Slim Framework

Slim is super lightweight framework, ideal for rapid web app development. One of the important usages is in REST API development. Slim supports all HTTP method (GET,POST,PUT,DELETE). Slim contains very handy URL structure with routers, middlewares, bodyparser along with page templates, flash messages, encrypted cookies and lots more.

At this point, it is important to understand the structure of the REST API.

Understanding REST API

REST is the abbreviation of Representational State Transfer. This is a bridge or medium between data resource and application interface, whether it’s on mobile devices or desktops. REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:

GET is used for reading and retrieving data.
POST is used for inserting data.
PUT is used for updating data.
DELETE is used for deleting data.

Basically, REST phenomena works on actions and resources. Whenever any action URL is invoked, it performs an individual method (or a set of methods) on that URL. I will further discuss this below with examples.

First we will need to install Slim framework for the REST API project.

System Requirements

  • Web server with URL rewriting
  • PHP 5.5 or newer

Role of Composer

  1. Enables you to declare the libraries you depend on.
  2. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).

If you are working on the localhost, you need to install it. If you haven’t installed it yet, just go to the following link and follow the instructions.

Instruction and more details about Composer Here.

How to Install Slim

We recommend you install Slim with Composer. Navigate into your project’s root directory and execute the bash command shown below. This command downloads the Slim Framework and its third-party dependencies into your project’s vendor/ directory.

composer require slim/slim "^3.0"

After installing Slim, the following piece of code will require it in the index.php file to require autoload file and instantiate Slim.

<?php

require 'vendor/autoload.php';
$app = new Slim\App();

Making a .htaccess File for Clean URL Structure

To make your life easier, you should create a .htaccess file that defines clean URL structure. At the root directory, make a .htaccess file and add the below code in it. This will provide a clean URL structure for the PHP file. (this just means that you don’t want to include PHP filename in the URL calls).

RewriteEngine On
RewriteCond %{Request_Filename} !-F
RewriteCond %{Request_Filename} !-d
RewriteRule ^ index.php [QSA,L]

If your index file is located in different folder (for instance, the “public” folder), then you can insert the full path of the index file in the last line:

RewriteRule ^ public/index.php [QSA,L]

Create a Database in MySQL

Now it is time for the first API call. Let’s make it systematically.

Retrieving Data

Enter the following code in the index.php file to get all the books from the database. A GET call is used for retrieval.

$app->get('/fetch', function() {
 require_once('dbConfig.php');
 $query = "select * from table order by id";
 $result = $connection->query($query);
 while ($row = $result->fetch_assoc()){
 $data[] = $row;
 }
 echo json_encode($data);
});

To streamline working with the API calls, I recommend using Postman (available from the Chrome App Store). This plugin greatly helps in API management and usage.

In postman, make a GET call with API URL.

This is all for the basic REST API in the Slim Framework. However, this API will not work until you add this command at the end of the code.

$app->run();

Conclusion

Creating and using the REST API with Slim framework is very easy. The biggest advantage of the framework is its ease of use and lightweight. The icing on the cake is that it is very easy to learn and a good developer could pick up the framework in a matter of hour. To summarize, Slim receives HTTP requests, review them and invokes the appropriate callback routine for HTTP requests and return the appropriate response(s).

If you need clarification about this article or have any other query about the Slim Framework, do let me know through the comment section.

Must-Know Visual Studio Keyboard Shortcuts

Here, I will give you a short list of keyboard short-cuts for things you probably do often in Visual Studio.

Visual Studio Keyboard Shortcuts

Project Related Keyboard Shortcuts

  • Ctrl + Shift + B = Build your project
  • Ctrl + Alt + L = Shows Solution Explorer
  • Shift + Alt + C = Add new class
  • Shift + Alt + A = Add new item to project

Editor Related Keyboard Shortcuts

  • Ctrl + Enter = Insert blank line above the current line
  • Ctrl + Shift + Enter = Insert blank line below the current line
  • Ctrl + Space = Autocomplete using IntelliSense
  • Alt + Shift + arrow keys(←,↑,↓,→) = Select custom part of the code
  • Ctrl + } = Match curly braces, brackets
  • Ctrl + Shift + } = Select text between matched braces, brackets
  • Ctrl + Shift + S = Saves all files and projects
  • Ctrl + K, Ctrl + C = Comments the selected lines
  • Ctrl + K, Ctrl + U = Uncomments the selected lines
  • Ctrl + K, Ctrl + D = Do proper alignment of all the code
  • Shift + End = Select the entire line from start to end
  • Shift + Home = Select the entire line from end to start
  • Ctrl + Delete = Deletes the word to the right of the cursor

Navigation Related Keyboard Shortcuts

  • Ctrl + Up/Down = Scrolls the window without moving the cursor
  • Ctrl + – = Take cursor to its previous location
  • Ctrl + + = Take cursor to its next location
  • F12 = Go to definition

Debugging Related Keyboard Shortcuts

  • Ctrl + Alt + P = Attach to process
  • F10 = Debug step over
  • F5 = Start debugging
  • Shift + F5 = Stop debugging
  • Ctrl + Alt + Q = Add quick watch
  • F9 = Set or remove a breakpoint

Search Related Keyboard Shortcuts

  • Ctrl + K Ctrl + K = Bookmark the current line
  • Ctrl + K Ctrl + N = Navigates to next bookmark
  • Ctrl + . = If you type in a class name like Collection<string> and do not have the proper namespace import, then this shortcut combination will automatically insert the import
  • Ctrl + Shift + F = Find in Files
  • Shift + F12 = Find all references
  • Ctrl + F = Displays the Find Dialog
  • Ctrl + H = Displays the Replace Dialog
  • Ctrl + G = Jumps to the line number or go to the line
  • Ctrl + Shift + F = Find the references of the selected item in the entire solution

Print selected webpage data using Javascript

Many times we would like to place a button on webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.

The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event and also set which portion would be printed.

See the Example as below :

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
            function printthis() {
                var printthis = document.getElementById('printthis');
                var popupWin = window.open('', '_blank', 'width=1000,height=600');
                popupWin.document.open();
                popupWin.document.write('<html><body onload="window.print()">' + printthis.innerHTML + '</html>');
                popupWin.document.close();
            }
        </script>
    </head>
    <body>
        <div>
            Other contents
        </div>
        
        <div id="printthis">
            <div>
                Print this portion
            </div>
        </div>
        <div>
            <input type="button" value="print" onclick="printthis();" />
        </div>
    </body>
</html>

 

sometimes we want some portion of the page need to be print not a whole page,as per above example set id or class to portion which need to print (here #printthis).
when javascript function call on onclick then this function prints part of page which having data within #printthis div.

How to Secure Cookie in PHP using Session

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

But now you want to set permissions on these session variables or values to accessing on other folder or page.for this you want to set the session cookie parameters.

Set the session cookie parameters PHP have function:

session_set_cookie_params();

 

Parameters :

lifetime – Lifetime of the session cookie, defined in seconds.
path – Path on the domain where the cookie will work. Use a single slash (‘/’) for all paths on the domain.
domain – Cookie domain, for example ‘www.example.com’. To make cookies visible on all subdomains then the domain must be prefixed with a dot like ‘.example.com’.
secure – If TRUE cookie will only be sent over secure connections.
httponly – If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

 

Example :

if (ini_get("session.use_cookies")) {
    session_set_cookie_params(0, '/abc/xyz/', '', false, true);
}

In above example says now values of cookies that will be created anywhere inside the page of abc/xyz folder will be accessable only inside abc/xyz folder not in other folder present anywhere on server.

This function has not returned any value and you need to call session_set_cookie_params() for every request and before session_start() is called.

Get the session cookie parameters :

To get the session cookie parameters PHP have function

session_get_cookie_params();

Returns an array with the current session cookie information, the array contains the following items:

lifetime – The lifetime of the cookie in seconds.
path – The path where information is stored.
domain – The domain of the cookie.
secure – The cookie should only be sent over secure connections.
httponly – The cookie can only be accessed through the HTTP protocol.

Example :

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
}

$params returned array with 5 parameters as listed above.

MySQL Transactions

MySQL transactions can be used when you want to make sure all the statements you specify are executed. Only the tables of InnoDB storage engine support transactions.

In a transaction, if at least one statement fails, all the changes will be rolled back and database will be in its initial state.

In web applications, it’s common that you want to either run set of statements or do no change since success of only few statements can cause data corruption.

Think you need to add data in 2 tables

$query1 = INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES (1, 'test', 'user');

$query2 = INSERT INTO `profile` (`pid`,`id`, `gender-`, `mobile`,`email`) VALUES (1, '1', 'male','123456789','test@example.com');

Here you can see in second query gender field having speeling mistake, hence no data will be added for this operation and data from first query will be inserted successfully.When running these two statements, think that second one fails and first one succeeds.

If we ran these two statements in a MySQL transaction, if the second statement fails then the first statement will be rolled back making no changes.

In PHP, we can execute a transaction using MySQLi functions like below.

/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'root', 'username', 'db_name');

mysqli_autocommit($dbConnection, false);
$flag = true;

$query1 = INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES (1, 'test', 'user');

$query2 = INSERT INTO `profile` (`pid`,`id`, `gender-`, `mobile`,`email`) VALUES (1, '1', 'male','123456789','test@example.com');

$result = mysqli_query($dbConnection, $query1);

if (!$result) {
    $flag = false;
    echo "Error details: " . mysqli_error($dbConnection) . ".";
}

$result = mysqli_query($dbConnection, $query2);

if (!$result) {
    $flag = false;
    echo "Error details: " . mysqli_error($dbConnection) . ".";
}

if ($flag) {
    mysqli_commit($dbConnection);
    echo "All queries were executed successfully";
} else {
    mysqli_rollback($dbConnection);
    echo "All queries were rolled back";
}

mysqli_close($dbConnection);

When you execute mysqli_query() function, result is immediately committed to the database. Using mysqli_autocommit() function, you can turn off this behavior so that result won’t be committed to the database permanently till you command.

After that we simply execute the necessary statements and set the $flag to false if any statement fails. If there are many statements to run, consider storing the statements in an array and using a for or foreach loop.

At the end, if flag is true (no error has occurred), we commit the results to the database permanently using mysqli_commit(). Else we roll back the results using mysqli_rollback() function.

If you ran above PHP script, you would notice that no statement is executed since the field name gender having spelling mistake.While transactions will help you to eliminate data corruptions in programming level.

Asp.net Difference between Website and Web Application

Generally whenever we are trying to create new web project in visual studio we will found two options ASP.NET Web Application and Web Site. What is the difference between these two which one we need to select to create project in asp.net?

It’s choice of the people can go for web application or website we cannot say that which one is better because both is having advantages and disadvantages. Check below details for web aplication and website.

Web Application

  • If we create any class files / functions those will be placed anywhere in the applications folder structure and it is precomplied into one single DLL.
  • In web application we have chance of select only one programming language during creation of project either C# or VB.NET.
  • Whenever we create Web Application those will automatically create project files (.csproj or .vbproj).
  • We need to pre-compile the site before deployment.
  • If we want to deploy web application project we need to deploy only .aspx pages there is no need to deploy code behind files because the pre-compiled dll will contains these details.
  • If we make small change in one page we need to re-compile the entire sites.
  • By default explicit namespaces are not added to pages, controls or classes, but you can add them manually.

WebSite

  • If we create any class files/functions those will be placed in ASP.NET folder (App_Code folder) and it’s compiled into several DLLs (assemblies) at runtime.
  • In website we can create pages in multi programming languages that means we can create one page code in C# and another page code in vb.net.
  • Web Sites won’t create any .csproj/.vbproj files in project
  • No need to recompile the site before deployment.
  • We need to deploy both .aspx file and code behind file.
  • If we make any code changes those files only will upload there is no need to re-compile entire site
  • By default explicit namespaces are added to pages, controls and classes

when you want to create an Informational project, then go for Website and when you want to create an Interactive project that requires programmatic user input or data processing, and then go for Web Application.

MULTIPLE MYSQL SERVERS FROM ONE PHPMYADMIN INSTANCE

At some point in your development career, it is likely that you will want to work on multiple MySQL servers. Personally, I like using phpMyAdmin for quick database management. However, what I don’t want to do is maintain multiple instances of phpMyAdmin. I also don’t want to install phpMyAdmin on any production web-servers.

What I would much rather do is install a local instance on my development machine, make sure it isn’t accessible to the outside world, and let it manipulate my local (test/development) environment and on occasion my production environments. Luckily, phpMyAdmin allows you to do just that.

To set this up you will want to navigate to the installation directory of phpMyAdmin (Mine is in C:\wamp\apps\phpMyAdmin-4.0.4.1) and check to see if you have a file named config.inc.php floating around in there. Follow the next steps based on whether that file exists:

If File doesn’t exist:

    • Create a file config.inc.php
    • Add the following updating for your server’s connection data and increment $i for each subsequent server added:
      <?php
       
      /* Servers configuration */
      $i = 0;
       
      $i++;
      $cfg['Servers'][$i]['verbose'] = '<Server 1>';
      $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
      $cfg['Servers'][$i]['port'] = '';
      $cfg['Servers'][$i]['socket'] = '';
      $cfg['Servers'][$i]['connect_type'] = 'tcp';
      $cfg['Servers'][$i]['extension'] = 'mysqli';
      $cfg['Servers'][$i]['auth_type'] = 'config';
      $cfg['Servers'][$i]['user'] = '<username>';
      $cfg['Servers'][$i]['password'] = '<password>';
      $cfg['Servers'][$i]['AllowNoPassword'] = true;
       
      $i++;
      $cfg['Servers'][$i]['verbose'] = '<Server 2>';
      $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
      $cfg['Servers'][$i]['port'] = '';
      $cfg['Servers'][$i]['socket'] = '';
      $cfg['Servers'][$i]['connect_type'] = 'tcp';
      $cfg['Servers'][$i]['extension'] = 'mysqli';
      $cfg['Servers'][$i]['auth_type'] = 'config';
      $cfg['Servers'][$i]['user'] = '<username>';
      $cfg['Servers'][$i]['password'] = '<password>';
      $cfg['Servers'][$i]['AllowNoPassword'] = true;
       
      ?>
    • Save the file
    • Navigate to your phpMyAdmin instance using a browser
    • On the left-hand navigation pane you will now see a drop-down near the top preceded by the words “Current Server:”
    • When you change this your phpMyAdmin instance will reload itself with the new server in scope

If File does exist:

  • Open the file config.inc.php in your favorite editor
  • Make sure your file has the following code in it:
    <?php
    /* Servers configuration */
    $i = 0;
  • After this code add the following updating for your server’s connection data and increment $i for each subsequent server added:
    $i++;
    $cfg['Servers'][$i]['verbose'] = '<Server 2>';
    $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
    $cfg['Servers'][$i]['port'] = '';
    $cfg['Servers'][$i]['socket'] = '';
    $cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = '<username>';
    $cfg['Servers'][$i]['password'] = '<password>';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
  • Save the file
  • Navigate to your phpMyAdmin instance using a browser
  • On the left-hand navigation pane you will now see a drop-down near the top preceded by the words “Current Server:”
  • When you change this your phpMyAdmin instance will reload itself with the new server in scope

MANAGE REMOTE MYSQL DATABASE LOCALLY USING PHPMYADMIN

In many web applications, we have to work with remote databases. It is very hard to manage those databases by accessing the remote server which our database run. Therefore, if we have a way to manage those databases locally using a UI, our task is getting easier.

Now I will show you how to manage those databases using phpMyAdmin locally. For that, we have to do some configurations.

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['username']      = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Pay attention that the config array is called cfg and it’s a multidimensional array and that all servers, have to be part of the $cfg[“Servers”] inner array. The way this works is by using an increment variable $i that sets a different inner array for each server inside the $cfg[“Servers”] array. For this to work you need to make sure each new set of config options starts with an incremented $i by using $i++.

Let’s see what is the meaning of this variables.

  • $i++ :- Incrementing variable for each server
  • $cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
  • $cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
  • $cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
  • $cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
  • $cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
  • $cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
  • $cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
  • $cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
  • $cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this part to the config.inc.php file, restart your local server. Now your phpMyAdmin home page will display like follow.

phpmyadmin_home

Now in server choice field, there will be a localhost and new server that you configured. Choose that remote server and enter username and password of that remote database. Then click ‘Go’ button and it will connect to your remote database and now you can manage it locally.

Display Image Preview Without Saving File to Folder – ASP.Net

Hiii, It is easy to upload and save an image to folder and display the uploaded file in Image Control in ASP.Net. But what to do when we want to display an image preview to Image Control of ASP.Net without/before saving to folder ???

So here is the solution for this problem…Check this….

Design Code :

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick = "Upload" />
<hr />
<asp:Panel ID = "Panel1" runat = "server" Visible = "false" >
    <asp:Image ID="Image1" runat="server"/>
    <br />
    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick = "Save" />
</asp:Panel>

Load Event Code :

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["Image"] = null;
    }
}

 

Upload Button Event Code :

protected void Upload(object sender, EventArgs e)
{
    Session["Image"] = FileUpload1.PostedFile;
    Stream fs = FileUpload1.PostedFile.InputStream;
    BinaryReader br = new BinaryReader(fs);
    byte[] bytes = br.ReadBytes((Int32)fs.Length);
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
    Image1.ImageUrl = "data:image/png;base64," + base64String;
    Panel1.Visible = true;
}

Save Button Event Code :

protected void Save(object sender, EventArgs e)
{
    HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];
    postedFile.SaveAs(Server.MapPath("~/Uploads/") + Path.GetFileName(postedFile.FileName));
    Response.Redirect(Request.Url.AbsoluteUri);
}

Leave your reply if this post helps you… Thank You.  🙂