File Browser the Customized Way

Hello guys, its been a long time since I posted in this blog.

Today I am here to show you how to display your website directory contents like folders,images or even some files in a customized way.

See how GitHub is displaying our repository files and folders.

So, let’s get started.

What the default way looks like

The default way is what we see when we type any folder, that exists on a particular domain, is in the image below.

default-file-listing

But how our’s final one looks like is…

Custom-file-listing

What do we do here

Here we customize the URL parameters and identify the folders and files using PHP.

How to do it

  1. First we represent all folders with a “directory” image.

  2. Then we identify each file (text or any other) with a File icon.

The procedure for identifying the folders is…


<?php

function listDir($dir){

$files = array();

$links = array();

if(file_exists($dir)){

if(count(scandir($dir)) > 2){

$dh = scandir($dir);

foreach($dh as $folder){

if($folder != '.' && $folder != '..'){

if(is_dir($dir.'/'.$folder)){

$files[] = $folder;

$links[$folder] = "project.php?url=".$dir.'/'.$folder;

}else{

$files[] = $folder;

$links[$folder] = "project.php?url=".$dir.'/'.$folder;

}

}

}

}

return [$files,$links];

}else{

return "";

}

}

?>

This PHP code will return an array of files or sub-folders as an array to the callee of function.

Using this array of files, we can style our webpage to display how these values to be displayed.

My way of styling is as follows.


<?php

if(is_file($url)){

echo "<pre><code>".nl2br(htmlentities(file_get_contents($url)))."</code></pre>";

}else{

$file_links = listDir($url);
if(!empty($file_links)){
$files = $file_links[0];
$links = $file_links[1];
echo "<div class='files'>";
foreach($files as $f){
echo "<div>";
foreach($links as $key => $l){
if($f == $key){
if(is_dir($url.'/'.$key)){
echo "<span class='file-icon'><img src='directory.png'/></span>";
}else{
echo "<span class='file-icon'><img src='code.png'/></span>";
}
echo "<span class='file-name'>";
echo "<a href='".$l."'>".$key."</a>";
echo "</span>";
}
}
echo "</div>";
}
echo "</div>";
}

}

?>

Reading File contents

 

Live Demo     Download

Hope you guys enjoyed this.

 

Advertisements

How I Wished my Friend for Christmas Eve?

Hello guys! Today I’m going to share my another experience in coding with a beautiful language PYTHON.

What exactly I did?

I have been working on python since 2 weeks. I have gathered information from my friend about APIs using Python. Then I have learnt Twilio API. This API enables us to send SMS/voice calls/MMS for a verified numbers from your account. Using this API, I created an application that will send a quotation as an SMS for every 10 seconds to my friend.

Christmas Wishes

How I did all these?

This application is done using the libraries in python-

  1. requests to fetch all the quotations from the website
  2. time
  3. twilio

For this application I have  fetched all the popular quotations about  Christmas from the  popular website BrainyQuote .

You can find the code for fetching all the quotations from my github repository

Now lets go deep into the coding part of the application.

Step 1: 


from twilio.rest import TwilioRestClient

import time

These two statements will import necessary modules for working with our application

  1. time module will enable us to send an SMS with a specified delay
  2. TwilioRestClient module is for authenticating, creating messages and sending to receiver (your friend).

Step 2:


auth_id = "your account SID here"

auth_token = "your secret_token here"

client = TwilioRestClient(auth_id,auth_token)

These statements will authenticate  us to the Twilio API

You can get your account SID and auth_token from the Twilio website

Step 3:

Now we have to fetch the quotations from the text file we already have.


f = open("quotes.txt","r")

for quote in f.readlines() :

    sendmsg(quote)

    time.sleep(10)

Explanation:

  1. The statement f = open(“quotes.txt”,”r”) will open the specified file in read mode.
  2. The statement for quote in f.readLines(): will loop us till all the lines in the file are parsed.
  3. The statement sendmsg(quote) will send the quote fetched to a function sendmsg().
  4. The statement time.sleep(10) will make the program to sleep for 10 seconds befor sending another quotation to the function.

Step 5: sendmsg() function


def sendmsg(body):

    message = client.messages.create(body=body,to="the verified receiver's number",from_="your twilio account number")

    print client.messages.get(message.sid).status

Explanation:

The sendmsg(body) module will create a message with body, to_address and from address.

This will also send the message as soon as it is created.

For conformation we can know the status of message

For full documentation visit: Twilio Docs

The full source is available at my github repository

HTML5 Drag and Drop File Upload with JQuery

Today we will see how to upload files with the wonderful Drag And Drop feature of HTML5 and JQuery with AJAX.

Lets begin the tutorial.

Drag And Drop FIle Upload

Drag And Drop FIle Upload

Live Demo  Download

Step 1

Add the Javascript library JQuery for Ajax


<script src="jquery.min.js"></script>

Step 2

Add a div tag to body which handles the file drag and drop

<div id="draganddrophandler" align="center">Drag and Drop Files Here</div>

Step 3

Now add the styles to the tags to identify when files are dropped onto the dragandrophandler

#draganddrophandler{
 border:2px dotted #0B85A1;
 width:400px;
 color:#92AAB0;
 height:200px;
 text-align:center;vertical-align:middle;
 padding:10px 10px 10 10px;
 margin-bottom:10px;
 font-size:200%;
 }
 .progressBar {
 width: 200px;
 height: 22px;
 border: 1px solid #ddd;
 border-radius: 5px;
 overflow: hidden;
 display:inline-block;
 margin:0px 10px 5px 5px;
 vertical-align:top;
 }

 .progressBar div {
 height: 100%;
 color: #fff;
 text-align: right;
 line-height: 22px; /* same as #progressBar height if we want text middle aligned */
 width: 0;
 background-color: #0ba1b5; border-radius: 3px;
 }
 .statusbar
 {
 border-top:1px solid #A9CCD1;
 min-height:25px;
 width:700px;
 padding:10px 10px 0px 10px;
 vertical-align:top;
 }
 .statusbar:nth-child(odd){
 background:#EBEFF0;
 }
 .filename
 {
 display:inline-block;
 vertical-align:top;
 width:250px;
 }
 .filesize
 {
 display:inline-block;
 vertical-align:top;
 color:#30693D;
 width:100px;
 margin-left:10px;
 margin-right:5px;
 }
 .abort{
 background-color:#A8352F;
 -moz-border-radius:4px;
 -webkit-border-radius:4px;
 border-radius:4px;display:inline-block;
 color:#fff;
 font-family:arial;font-size:13px;font-weight:normal;
 padding:4px 15px;
 cursor:pointer;
 vertical-align:top
 }

Step 4

Handle Drag and Drop events with JQuery

var obj = $('#draganddrophandler');
 obj.on('dragenter',function(e){
 e.stopPropagation();
 e.preventDefault();
 $(this).css('border','2px solid #0B85A1');
 });
 obj.on('dragover',function(e)
 {
 e.stopPropagation();
 e.preventDefault();
 });
 obj.on('drop',function(e)
 {
 $(this).css('border','2px dotted #B85A1');
 e.preventDefault();
 var files = e.originalEvent.dataTransfer.files; //get all the files from drop event

 handleFileUpload(files,obj); //function that handles all the file drag-and-drop
 });

If the files are dropped outside the DIV,we have to prevent the page from redirecting to another.


$(document).on('dragenter',function(e)
{
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover',function(e)
{
e.stopPropagation();
e.preventDefault();
obj.css('border','2px dotted #B85A1');
});
$(document).on('drag',function(e)
{
e.stopPropagation();
e.preventDefault();
});

Step 5

Read the files from the HTML5 FormData() object.


function handleFileUpload(files,obj)
{
for(var i=0;i<files.length;i++)
{
var fd = new FormData();
fd.append('file',files[i]);
var status = new createStatusbar(obj);
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}
}

Step 6

Sending FormDat() to the server using JQuery AJAX API


function sendFileToServer(formData,status)
{
var uploadURL ="./upload.php"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);

$("#status1").append("File upload Done<br>");
}
});

status.setAbort(jqXHR);
}

That’s it! Its so simple. Now let’s put all these lines together.

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<style>
body{
padding:70px;
}
.navbar a{
color:turquoise !important;
}
#draganddrophandler{
border:2px dotted #0B85A1;
width:400px;
color:#92AAB0;
height:200px;
text-align:center;vertical-align:middle;
padding:10px 10px 10 10px;
margin-bottom:10px;
font-size:200%;
}
.progressBar {
width: 200px;
height: 22px;
border: 1px solid #ddd;
border-radius: 5px;
overflow: hidden;
display:inline-block;
margin:0px 10px 5px 5px;
vertical-align:top;
}

.progressBar div {
height: 100%;
color: #fff;
text-align: right;
line-height: 22px; /* same as #progressBar height if we want text middle aligned */
width: 0;
background-color: #0ba1b5; border-radius: 3px;
}
.statusbar
{
border-top:1px solid #A9CCD1;
min-height:25px;
width:700px;
padding:10px 10px 0px 10px;
vertical-align:top;
}
.statusbar:nth-child(odd){
background:#EBEFF0;
}
.filename
{
display:inline-block;
vertical-align:top;
width:250px;
}
.filesize
{
display:inline-block;
vertical-align:top;
color:#30693D;
width:100px;
margin-left:10px;
margin-right:5px;
}
.abort{
background-color:#A8352F;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;display:inline-block;
color:#fff;
font-family:arial;font-size:13px;font-weight:normal;
padding:4px 15px;
cursor:pointer;
vertical-align:top
}
</style>
<script>
function sendFileToServer(formData,status)
{
var uploadURL ="./upload.php"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);

$("#status1").append("File upload Done<br>");
}
});

status.setAbort(jqXHR);
}

var rowCount=0;
function createStatusbar(obj)
{
rowCount++;
var row="odd";
if(rowCount %2 ==0) row ="even";
this.statusbar = $("<div class='statusbar "+row+"'></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
obj.after(this.statusbar);

this.setFileNameSize = function(name,size)
{
var sizeStr="";
var sizeKB = size/1024;
if(parseInt(sizeKB) > 1024)
{
var sizeMB = sizeKB/1024;
sizeStr = sizeMB.toFixed(2)+" MB";
}
else
{
sizeStr = sizeKB.toFixed(2)+" KB";
}

this.filename.html(name);
this.size.html(sizeStr);
}
this.setProgress = function(progress)
{
var progressBarWidth =progress*this.progressBar.width()/ 100;
this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
if(parseInt(progress) >= 100)
{
this.abort.hide();
}
}
this.setAbort = function(jqxhr)
{
var sb = this.statusbar;
this.abort.click(function()
{
jqxhr.abort();
sb.hide();
});
}
}
function handleFileUpload(files,obj)
{
for(var i=0;i<files.length;i++)
{
var fd = new FormData();
fd.append('file',files[i]);
var status = new createStatusbar(obj);
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}
}
$(document).ready(function()
{
var obj = $('#draganddrophandler');
obj.on('dragenter',function(e){
e.stopPropagation();
e.preventDefault();
$(this).css('border','2px solid #0B85A1');
});
obj.on('dragover',function(e)
{
e.stopPropagation();
e.preventDefault();
});
obj.on('drop',function(e)
{
$(this).css('border','2px dotted #B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;

handleFileUpload(files,obj);
});
$(document).on('dragenter',function(e)
{
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover',function(e)
{
e.stopPropagation();
e.preventDefault();
obj.css('border','2px dotted #B85A1');
});
$(document).on('drag',function(e)
{
e.stopPropagation();
e.preventDefault();
});
});
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="./">Demos</a>
</div>
<div class="collapse navbar-collapse">
<ul class="navbar-nav nav navbar-right ">
<li class="login"><a href="https://kmvkrish.wordpress.com" title="Tutorials">Go to Tutorial</a></li>
</ul>
</div>
</div>
</div><br/><br/><br/><br/>
<div class="container">
<div id="draganddrophandler" align="center">Drag and Drop Files Here</div>
<br><br>
<div id="status1"></div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

What you see is What you GET

How many of you have seen different styles of text in a page content? Many of you have written CSS for styling the page content. But there is an entire different way of styling text (Some parts or entire text) using Javascript.

This will be described here as WYSIWYG editor.

so let’s begin the HTML code is… For the layout of buttons

&lt;/pre&gt;
&lt;div id=&quot;wysiwyg_cp&quot; style=&quot;padding: 8px; width: 700px;&quot;&gt;&lt;input class=&quot;fa fa-bold&quot; type=&quot;button&quot; value=&quot;B&quot; /&gt; &lt;input class=&quot;fa fa-underline&quot; type=&quot;button&quot; value=&quot;U&quot; /&gt; &lt;input class=&quot;fa fa-italic&quot; type=&quot;button&quot; value=&quot;I&quot; /&gt; &lt;input class=&quot;fa fa-text-height fa-text-width&quot; type=&quot;button&quot; value=&quot;Text Size&quot; /&gt; &lt;input class=&quot;fa fa-color&quot; type=&quot;button&quot; value=&quot;Text Color&quot; /&gt; &lt;input class=&quot;fa fa-list&quot; type=&quot;button&quot; value=&quot;UL&quot; /&gt; &lt;input class=&quot;fa fa-list&quot; type=&quot;button&quot; value=&quot;OL&quot; /&gt; &lt;input class=&quot;fa fa-link&quot; type=&quot;button&quot; value=&quot;Link&quot; /&gt; &lt;input type=&quot;button&quot; value=&quot;HR&quot; /&gt; &lt;input type=&quot;button&quot; value=&quot;UnLink&quot; /&gt; &lt;input type=&quot;button&quot; value=&quot;Image&quot; /&gt;&lt;/div&gt;
&lt;pre&gt;

For typing text we can use either a DIV or an IFRAME so that the effects can easily be seen during styling. Here I use a DIV.  The code for typing text into a div is simple by using a simple attribute in HTML. Just make a div editable by the attribute contenteditable

&lt;/pre&gt;
&lt;div id=&quot;post_status&quot; class=&quot;form-control&quot; style=&quot;overflow: auto;&quot; contenteditable=&quot;true&quot;&gt;&lt;/div&gt;
&lt;pre&gt;

By making the DIV editable you can use this as a normal textarea where the effects of styling can easily be felt. Next comes the Javascript that is the heart of the editor functioning. This makes us to style our content in the way we want it to appear. First we will see the javascript code and later examine how each function works


function iBold(){
document.execCommand('bold',false,null);
}
function iUnderline(){
document.execCommand('underline',false,null);
}
function iItalic(){
document.execCommand('italic',false,null);
}
function iFontSize(){
var size = prompt('Enter a size 1 - 7', '');
document.execCommand('FontSize',false,size);
}
function iForeColor(){
var color = prompt('Define a basic color or apply a hexadecimal color code for advanced colors:', '');
document.execCommand('ForeColor',false,color);
}
function iHorizontalRule(){
document.execCommand('inserthorizontalrule',false,null);
}
function iUnorderedList(){
document.execCommand(&quot;InsertOrderedList&quot;, false,&quot;newOL&quot;);
}
function iOrderedList(){
document.execCommand(&quot;InsertUnorderedList&quot;, false,&quot;newUL&quot;);
}
function iLink(){
var linkURL = prompt(&quot;Enter the URL for this link:&quot;, &quot;http://&quot;);
document.execCommand(&quot;CreateLink&quot;, false, linkURL);
}
function iUnLink(){
document.execCommand(&quot;Unlink&quot;, false, null);
}
function iImage(){
var imgSrc = prompt('Enter image location', '');
if(imgSrc != null){
document.execCommand('insertimage', false, imgSrc);
}
}

The first function iBold() makes the content to be BOLD using the function execCommand(‘bold’,false,null); execCommand() is the function that executes the properties of text in the background as some SHELL COMMAND. iItalic() makes the content to be ITALIC and similarly all the names suggests the meaning and thus using a single and simple function,  execCommand(), we can make the editor work well.

Working with MongoDB shell commands

Previously I have shown you the installation procedures of MongoDB on windows or Linux or MAC

Today, in this post we will see how to get working with the shell commands of MongoDB.

Connecting to MongoDB

Connecting to MongoDB

Firstly, you have to connect to the database as shown in the image above.

We will be given a sample database named “test” in the software.

  1. You can create any database by using the command–>

>use manoj;

This will create if the database is not available.

Thie return value of this command will be

Creating or switching databases

Creating/switching databases

  1. To list database available in your server, use the command…

>show dbs

This will list all databases available specifying their size.

In MongoDB, we call tables as COLLECTIONS and each row of data is called TUPLE

The default datatype for storing data into Collections is called document, and that in MySQL it is an array

The format of document is similar to JSON but it is binary instead of ASCII.

for example

In MongoDB:

document = {“title” : “my new cms with MongoDB”,”description” : “MongoPress is the latest scalable cms developed in MongoDB”};

This seems a bit awesome structured rather than look like array in MySQL.

  1. To insert documents into collections use the command—

>db.collection.insert(document);

Inserting data into collections

Inserting data into collections

  1. To update previously stored data…use the command update()

>db.collections.update({document});

This is similar to the SQL command UPDATE collections SET “title” = “mongodb” WHERE “id” = 12;

  1. To remove the unwanted data or remove based on criteria use the command—-remove()

>db.collections.remove({“criteria”});//criteria is your condition to remove data

THis is similar to the SQL command DELETE FROM collections WHERE id=12;

  1. To find data use the command….find()

>db.collections.find(); //this will display all the data in your collection.

To get a good looking output similar to JSON format use the sub function pretty()

>db.collections.find().pretty();

finding data

finding data

This is similar to the SQL command SELECT * FROM collections

To find only one tuple from database based on criterion use the command findOne()

>db.collections.findOne({“title”:”my new tutorial”}).pretty();

This is similar to the SQL command…

                  SELECT * FROM collections WHERE title=”my new tutorial”

  1. To list all the collections in the database use the command….

>show collcetions;

We will see integration of MongoDB with PHP in the next post.

MongoDB-The best NoSQL ever

MongoDB is the new featuring of sql servers that doesn’t need qetting a large set of queries to get our work done.

This is a NoSQL kind of database (Not Only SQL) that is written in C++.

This can be used like any other Database Server we use on many Operating Systems.

To get started we follow the following things…

1.Download source files.

You can download the source file (.msi/.exe/.zip) from the downloads page of MongoDB Website

Notice: Please download the file as .zip extension as it doesnot need much work to get installed and it is the safest procedure.

2.Installation:

After downloading now extract the mongodb folder and place it in the root directory of your ‘C’ drive(This is only for better performance…you can install MongoDB in any drive).

Now you should see the following files in c:/mongodb/bin

Files in mongodb directory

Mongodb files

Most of all your work you will work with some data that is stored in your file system. This is the main advantage of MongoDB.

So,you have to create a data file that will use the data you have updated previously.

To do that, just create a folder named data in the root of your mongoDB directory..This should look like this…

mongodb data folder

MongoDB data folder

 

Now you can chose to create a log file using the procedure as follows.

1.create a file called mongod.config (you can name it what ever you want…), and type the following lines in it

dbpath = C:\mongodb\data  //here is where all your data will be stored while you work
port = 27017  //this is the default port number on which mongoDB runs.
logpath = C:\mongodb\logs\mongo.log  //here is where all your log will be stored

2.Create a folder called logs

3.Running MongoDB service

  1.  After you have succesfully installed mongoDB, open a command window (terminal in Linux).

  2. Switch to the directory where you installed mongodb.

for example in my case, I go to the directory using the command, cd /

  1. type the command to start MongoDb service…

c:\>  cd mongodb/bin

                 c:\mongodb\bin\> mongod –config c:/mongodb/mongod.config

now you should see some data that speaks about starting the service.

4.Connecting to the Database

To connect to the database just open another command window and type the following commands..

c:\>  cd mongodb/bin

                 c:\mongodb\bin\> mongo

or you can run the Database by double-clicking the mongo.exe file in the bin folder

Now you should see the following result on the window…

Connecting to MongoDB

database connectivity

you can execute the basic functions here.

We will see how mongoDB works in the next lesson..

Simple chat Application using Javascript APIs

Today I will show you the basic design of chat application without using any MySQL or any databases, instead we use Javascript API.

This is popularly known as Firebase. To learn the API fully please visit Documentation Site

Chat app using JavaScript

Displaying No. of messages..

chat2

Chat app using JavaScript APIS

Live Demo

The code might look like…

For styling the textboxes and the chat display area…


#comment-container {
border: 1px solid #d0d0d0;
height: 400px;
overflow-y: scroll;
}

.comment-container {
padding: 10px;
margin:6px;
background: #f5f5f5;
font-size: 13px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}

.comment-container .label {
margin-right: 20px;
}

.comment-container:last-of-type {
border-bottom: none;
}

For the mark-up…


<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h4>A Simple chat API Using FIREBASE</h4>
</div>
<div class="panel-body">
<div class="comment-container" id="comment-container">
<!-- To display the inserted messages//-->
</div>
</div>
<div class="panel-footer">
<div class="form-group">
<label for="comments" class="sr-only">Comments Here...</label>
<input type="text" id="name" class="form-control primary" placeholder="Enter your name..."/>
<input type="text" id="comments" class="form-control" placeholder="Place your comments here..."/>
</div>
<button type="submit" class="btn btn-success" id="submit" >Submit</button>
<button type="reset" onClick="javascript:clearData();" class="btn btn-danger" id="clear">Clear</button>
</div>
</div>
</div>

For the Javascript Calls…


$(document).ready(function(){
var firebaseRef = new Firebase('<Your_FIREBASE_URL LOCATION>');
$('#submit').click(function(){

var comment = $('#comments').val();
var name = $('#name').val();
if(comment.length === 0)
{
alert("Please Fill this field...");
}
else{
firebaseRef.push({name:name,text:comment});

}
$('#comments').val('');
});
firebaseRef.on('child_added',function(snapshot){
var message = snapshot.val();
$('<div/>').text(message.text).prepend($('<em/>')
.text(message.name+': ')).appendTo($('#comment-container'));
$('#comment-container')[0].scrollTop = $('#comment-container')[0].scrollHeight;
});

});

Simple Calculator in PHP

Today i will show you how to create a simple calculator in php that will evaluate the input string given by the user… Lets start…

Calculator in AJAX and PHP

Calculator screenshot

         Live Demo

The HTML markup for textboxs, operator selection and submit button


<div class="container">
 <div class="panel panel-primary">
 <div class="panel-heading">
 <h4>Basic Calculator in PHP and AJAX</h4>
 </div>
 <div class="panel-body">
 First Input:<input type="text" class="form-control" name="input1" id="input1"/><br/>
 Second Input:<input type="text" class="form-control" name="input2" id="input2"/><br/>
 Operator:<select id="operator">
 <option>--Select An Operator--</option>
 <option>+</option><br/>
 <option>-</option>
 <option>*</option>
 <option>/</option>
 <option>%</option>
 <option>++</option>
 <option>--</option>
 </select><br/><br/>
 <input type="submit" value="Calculate" class="form-control btn btn-primary" onClick="javascript:ajax_post();"/>
 <div id="status" ></div>
 </div>
 </div>
 </div>

Notice: The best way of doing a simple calculations is using switch case and compare operator with condition and do the task…as i did here…

The Javascript Function that Performs ajax calls is ajax_post().

The code of function is here…


<script type="text/javascript">
function ajaxObj( meth , url )
{
var x = new XMLHttpRequest();
x.open(meth , url , true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x)
{
if(x.readyState == 4 && x.status == 200)
{
return true;
}
}
function ajax_post(){
var ajax = ajaxObj("POST","calc.php");
var inp1 = document.getElementById("input1").value;
var inp2 = document.getElementById("input2").value;
var operator = document.getElementById("operator").value;
var datastring = "name="+inp1+"&id="+inp2+"&op="+operator;
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
document.getElementById("status").innerHTML ="Value = " + ajax.responseText;
}
}
ajax.send(datastring);
document.getElementById("status").innerHTML = "Processing...";
}
</script>

Explanation:


function ajaxObj( meth , url )
{
var x = new XMLHttpRequest();
x.open(meth , url , true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}

This function ajaxObj makes ajax calls that opens and passes the parameters to the url(File Name).


function ajaxReturn(x)
{
if(x.readyState == 4 && x.status == 200)
{
return true;
}
}

This function ajaxReturn returns the readystate of the ajax object if everything is OK.


function ajax_post(){
var ajax = ajaxObj("POST","calc.php");
var inp1 = document.getElementById("input1").value;
var inp2 = document.getElementById("input2").value;
var operator = document.getElementById("operator").value;
var datastring = "name="+inp1+"&id="+inp2+"&op="+operator;
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
document.getElementById("status").innerHTML ="Value = " + ajax.responseText;
}
}
ajax.send(datastring);
document.getElementById("status").innerHTML = "Processing...";
}

ajax_post() is used to process our input strings that are given by the user…

we handle creation of ajax object(XMLHttpRequest object) and compare the readystate of every event that is invoked by the user…

Next we send the parameters(that are collected using javascript document object ) to the

ajax.send()

method that  are passed to the calc.php file.

Full Code….

For Calculating the output….


<?php
 $i1 = $_POST['name'];
 $i2 = $_POST['id'];
 $op = $_POST['op'];
 switch($op)
 {
 case "+":
 $output = $i1 + $i2;
 echo $output;
 break;
 case "-":
 $output = $i1 - $i2;
 echo $output;
 break;
 case '*':
 $output = $i1 * $i2;
 echo $output;
 break;
 case '/':
 $output = $i1 / $i2;
 echo $output;
 break;
 case '%':
 $output = $i1 % $i2;
 echo $output;
 break;
 case '++':
 echo $i1 ++;
 break;
 case '--':
 echo --$i1;
 break;
 default:
 echo $output = "Not Found...Please Enter only Integers or Decimals...";
 }
?>

For The Mark-up….


<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Basic Calculator in PHP and AJAX</h4>
</div>
<div class="panel-body">
First Input:<input type="text" class="form-control" name="input1" id="input1"/><br/>
Second Input:<input type="text" class="form-control" name="input2" id="input2"/><br/>
Operator:<select id="operator">
<option>--Select An Operator--</option>
<option>+</option><br/>
<option>-</option>
<option>*</option>
<option>/</option>
<option>%</option>
<option>++</option>
<option>--</option>
</select><br/><br/>
<input type="submit" value="Calculate" class="form-control btn btn-primary" onClick="javascript:ajax_post();"/>
<div id="status" ></div>
</div>
</div>
</div>

Highlight Source Code using PHP

If you want to show the source code of a small piece of example code on your blog without paring them on the browser then come check the simple code using PHP…

Declare a string in php

Send that string as parameter for the builtin function highlight_string().

Code is…


<?php

    highlight_string('<?php
        $i = 1;

        function rockOut()
        {
            alert('Wah Wah Wah');
        }
    ?>');

?>

output:

highlight_string() function usage

highlight_string Function usage

SQL-based Authentication in PHP

Do you want to build a secure authentication system in PHP? Then try this sample php code…

To use this you have to install php_mysql module on your server.

<?php

    function connect_db($database, $db_user, $db_password, $host = ‘localhost’, $port = NULL, $die = false) {
    // Returns a MySQL link identifier (handle) on success
    // Returns false or dies() on error depending on the setting of parameter $die
    // Parameter $die configures error handling, setting it any non-false value will die() on error
    // Parameters $host, $port and $die have sensible defaults and are not usually required

    if(!$db_handle = @mysql_connect($host.($port ? ‘:’.$port : ), $db_user, $db_password)) {
        if($die)
            die(“Can’t connect to MySQL server:\r\n.mysql_error());
        else
            return false;
    }
    if(!@mysql_select_db($database, $db_handle)) {
            if($die)
               die(“Can’t select database ‘$database‘:\r\n.mysql_error());
           else
              return false;
    }
    return $db_handle;
}

        function create_user($username, $password, $db_handle) {
            // Returns the record ID on success or false on failure
           // Username limit is 32 characters (part of spec)
            if(strlen($username) > 32)
                return false;

         // Create pass_md5
        $pass_md5 = md5($password);

        // Make it all binary safe
      $username = mysql_real_escape_string($username);
  
        // Try to insert it into the table – Return false on failure
        if(!@mysql_query(“INSERT INTO users (username,pass_md5) VALUES(‘$username‘,’$pass_md5‘)”, $db_handle))
            return false;

         // Return the record ID
        return mysql_insert_id($db_handle);
}

function authenticate_user($username, $password, $db_handle) {
       // Checks a username/password combination against the database
    // Returns false on failure or the record ID on success

    // Make the username parmeter binary-safe
        $safe_username = mysql_real_escape_string($username);

        // Grab the record (if it exists) – Return false on failure
        if(!$result = @mysql_query(“SELECT * FROM users WHERE username=’$safe_username‘”, $db_handle))
return false;

          // Grab the row
         $row = @mysql_fetch_assoc($result);

        // Check the password and return false if incorrect
        if(md5($password) != $row[‘pass_md5’])
              return false;

             // Return the record ID
               return $row[‘userid’];
}

?>

Time-Ago in PHP

Did anyone try to display x-seconds/minutes/years ago style of time like in @twitter or #Facebook?

Today I will show you how to do that in a simple way using PHP basic implementations…

<?php
function nicetime($date)//a user-defined function for conversion of time
{
if(empty($date)) {
return “No date provided”;
}

// an array that stores units of time…

// an array that stores values like seconds,days,hours, etc.,

$periods = array(“second”, “minute”, “hour”, “day”, “week”, “month”, “year”, “decade”);
$lengths = array(“60″,”60″,”24″,”7″,”4.35″,”12″,”10”);

$now = time();
$unix_date = strtotime($date);
if(empty($unix_date))
{
return “Bad date”;
}
if($now > $unix_date) {
$difference = $now – $unix_date;
$tense = “ago”;

} else {
$difference = $unix_date – $now;
$tense = “from now”;
}

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
$periods[$j].= “s”;
}
return “$difference $periods[$j] {$tense}”;
}

?>

// How to use this code??

//just callthis function sending curent date of posting as parameter and use the return value to display…

<?php

//set default time-zone of your location…
date_default_timezone_set(“Asia/Calcutta“);
$date = “2014-05-08 21:10”;
echo nicetime($date);

?>

Creating Tag Cloud in PHP

Did you see whether some popular websites have language packs (or) tags of popular posts at the footer of the webpages?

Have you looked at the code how they have done that?

Today I will show you a simple way to do that…

It’s very Interesting…

//Declare all the Cloud tags as an array in PHP

<?php

$arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44,
‘Background’ => 43,
‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11,
‘Crop’ => 42,
‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12,
‘Encryption’ => 30,’Extract’ => 28, ‘Filters’ => 42);

//now declare a function to create Cloud Tags

function getCloud($data = array(), $minFontSize = 12, $maxFontSize = 30 )

{

$minimumCount = min($data);
$maximumCount = max($data);
$spread = $maximumCount – $minimumCount;
$cloudHTML = ”;
$cloudTags = array();

$spread == 0 && $spread = 1;

foreach( $data as $tag => $count )
{
$size = $minFontSize + ( $count – $minimumCount )
* ( $maxFontSize – $minFontSize ) / $spread;
$cloudTags[] = ‘<a style=”font-size: ‘ . floor( $size ) . ‘px’
. ‘” class=”tag_cloud” href=”#” title=”\” . $tag .
‘\’ returned a count of ‘ . $count . ‘”>’
. htmlspecialchars( stripslashes( $tag ) ) . ‘</a>’;
}

return join( “\n”, $cloudTags ) . “\n”;
}

?>

//Now to call the function use the code as…

<?php

echo getCloud($arr, 20,30);

//send the array of tag clouds along with the minimum and maximum font size as parameters

?>

HashTag system in PHP

Did you ever try converting hashtags in your website into links of a post or comments…?

Did you ever try to learn it from other sources…?

Look how Facebook Team did it in PHP using Regular Expressions…

Today I will teach you how to do that easily in  PHP Regular Expressions.

Lets start now…

First retrieve the content of the post using $_POST in php

<?php

if(isset($_POST['hashtag']))

{

echo convertToHash($_POST['hashtag']);//convertToHash is a function for converting hashtags into urls…

}

function convertToHash($str)

{

//declare a regular expression…

$regex = "/#+([a-zA-Z0-9_.]+)/";

$string = preg_replace($regex,'<a href="http://facebook.com/$1″ target=”_blank”>$0‘, $str);

return $str;

}

?>

To use this function just use the html form…

Linkify text into Clickable Hyperlinks

Are you surprised of seeing URLs on the #Facebook or #Twitter or on Gmail when you typed or composed a content containing some text along with urls in it….??

Did you ever try of doing that???

Today i will show you how to do that thing in a simple but efficient way in about 6 lines of Code…

<?php
function autolink($string)
{
$content_array = explode(” “, $string);
$output = ”;

foreach($content_array as $content)
{
if(substr($content, 0, 7) == “http://“)
$content = ‘<a href=”‘ . $content . ‘”>’ . $content . ‘</a>’;
if(substr($content, 0, 4) == “www.”)
$content = ‘<a href=”http://‘ . $content . ‘”>’ . $content .'</a>’;

$output .= ” ” . $content;
}

$output = trim($output);
return $output;
}
?>

To use this function just call it on buttom click or during inserting into database….
<?php
echo autolink(“Hello I’m Krishna Manoj..my website is
https://kmvkrish.wordpress.com“);
?>

An example code for using the same is….

<?php

if(isset($_POST[‘url’]))

{

$url = $_POST[‘url’];

autolink($url);

}

function autolink($string)
{
$content_array = explode(” “, $string);
$output = ”;

foreach($content_array as $content)
{
if(substr($content, 0, 7) == “http://”)
$content = ‘<a href=”‘ . $content . ‘”>’ . $content . ‘</a>’;
if(substr($content, 0, 4) == “www.”)
$content = ‘<a href=”http://’ . $content . ‘”>’ . $content .'</a>’;

$output .= ” ” . $content;
}

$output = trim($output);
return $output;
}

?>
<html>
    <body>
        <form method=”post” action=””>
<input type=”text” name=”urlplaceholder=”enter url… size=”120″>
<input type=”submit” value=”Linkifyname=”submit“>
</form>
    </body>
</html>

Explanation…

First retrieve the text entered by the user….

Divide the text based on a delimiter into array…(Explode function dvides the text into array)

for every variable in the array check for http:// or www. values in the array values…

if present display them using <a> tag…else display them as plain text…

Thats it!!..its very simple..Have a good day…

PHP STATIC Keyword

we all know how a ststic keyword works in an object-oriented Programming Language like JAVA….we can also implement same concept in PHP too…

Let’s see how it works….

<?php

/*create a class of your choice…*/

class myclass

{

/* declare a static variable $name for example…*/

public static $name = “KRISHNA MANOJ”;

public static getName()

{

return self::$name;

/**self:: is to be used to indicate that $name  belongs to this class only…else we will not get any printed Output…**/

}

}

/* execute the function with object….*/

$obj = new myclass();

echo  $obj->getName();//works well as we are printing name from a function

/* with the classname itself….*/

echo myclass::getName();

?>

Extract URL contents using PHP, JQuery and AJAX

Do you want to extract url contents and display it to the user before he posts it to your site?…..

Just check it out the below code….

1. Starting with Basic HTML

<html>

<head>

</head>

<body>

<textarea id=”urls” cols=”40″ rows=”8″ placeholder=”Enter a url here…”></textarea>

<div id=”extr”></div>

</body>

</html>

2. The Javascript Code

Insert this code between the head tag of your html file….

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js></script>

<script>

$(function(){

$(‘#urls’).live(“keyup”,function(){

$.ajax({

type: “POST”,

url: “extract.php”,

data: “url=” + $(‘#urls’).val(),

cache: false,

success:function(html)

{

$(‘#extr’).html(html);

}

});

});

});

</script>

3.The extract.php file

<?php

                         if(isset($_POST[‘url’]))

{

$url = $_POST[‘url’];

                                  if($url == ”)

{

                                           echoURL Mustnot be Empty…Please Enter something…“;

}

                                  else{

                                       echo file_get_contents($ur;);

}

}

              ?>

Generate Random Password

Are you designing a website where a user can register himself?

Do you want to help him generating a random password? Try this simple code….

<?php

function generatePassword($length=16)
{

$chars =”ABCDEFGHIJKLMNOPQRST
UVWXYZabcdefghijklmnopqrstuvwxyz1234567890″;//length:36
$final_rand=””;
for($i=0;$i<$length; $i++)
{
$final_rand .= $chars[ rand(0,strlen($chars)-1)];

}
return $final_rand;
}
?>

How To execute??

<?php

echo generatePassword(10);  //call the function….

?>

 

 

Validate Email Address of a User

Do you want to validate the email address given by the user manually…..use php for doing that….

its easy and simple to understand…..

Lets  start  now…

<?php
$email_a = “kmvkrish@gmail.com”; //declare a sample email address
$email_b =”kmvkrish@12 box.com”; //false email id

 if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo “This ($email_a) email address is considered valid.”;
}
 if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo “This ($email_b) email address is considered valid.”;
}
?>

In the above code….

filter_var($var, FLAG) is a function of the PHP library which checks each character  of the email address and if matched the pattern exactly returns TRUE else returns FALSE