Wednesday 21 August 2013

Check out the website i made !!

Monday 10 June 2013

Node.js and real-time applications

Hey there guys , posting after a long long time . Was a bit busy and stuff .
          So let's talk about node.js . What is node.js ? It is a server-side software system that can be used to write scalable web applications . As the name suggests , all the code is basically written in javascript .

So what makes node stand out from conventional server side solutions such as php/jsp or other such stuff ? The main advantage of using node.js is it's advanced push capability . That is server can push information to the client in real time , whenever there is a change in the web page or new content is added which means it enables persistent connection between your page and the web server . Node.js uses a non-blocking event driven I/O . In node each persistent connection won't block other requests .Other languages like php sets up a new server process for each connection and we might end up with using a lot of cpu resources . Thus nodejs is suitable for handling many persistent connections at once without using up a huge amount of resources .

To get the best out of node , use Socket.IO and redis . So what is socket.io ? Socket.IO enables you to broadcast data to clients based on a certain event . It uses websockets protocol primarily if present , but it can use other methods too like Adobe flash sockets , JSONP polling , ajax , long polling . It allows us to have almost "instant" feedback from the server . Redis is a in-memory , key:value store . Redis supports abstract data types like hashes , sets and lists . Also the pub-sub system allows you to subscribe to messages from a certain channel and so on which can be used for notification systems , chat rooms and so on.

Saturday 30 March 2013

Denying access to a particular folder on your web server

Suppose you have a directory in your web server which contains sensitive files like files containing database connection passwords , app-secret id's for using 3rd party services etc . You want to block access to that particular folder . So how are you going to do it ? Well it's pretty simple . Just add a .htaccess file to that folder . Open it up , and add the following lines :-


Order deny,allow
deny from all

This will deny access to any files in that folder . Remember that all those files in the folder can be accessed only if you add a require , include directive in a file on the server-side . However ajax calls or any sort of client request won't work on the files of that directory .

Friday 29 March 2013

PHP Tutorial . Chapter 5 . PHP Control Statements ( Part 2 - Loops 1 (For Loop) )

While writing your code , you might encounter situations when you might want to execute the same set of statements over and over again . PHP like other programming languages implements this in the form of loops . There are three types of looping constructs commonly used in php - for , while , foreach . The last one is usually used for resources , associative arrays .

1) For Loop

The following piece of code illustrates the use of a for loop .

for($i=1 ; $i<=10 ; $i++)
{
       echo $i."<b/>";
}

The above code will print 1 to 10 on different lines . So how does this work ? First we assign $i = 1 . Then when the loop executes each time , the condition $i<=10 . The statements inside the looping construct are executed only if this condition is true . Then the value of the variable i is incremented .

The given code can also be written as the following . It is an example of a loop where no statements are within the control statement itself . We assign the variable out of the loop and also the conditions are checked for and the variable is incremented inside the loop .


$i=1;
for(;;)
{
echo $i++."<br/>";
if($i>10)
break;
}

The only thing that may sound unfamiliar to guys who are new to programming is the break statement . Whenever a break statement is encountered , the loop is terminated then and there . There is also something called continue , which is the opposite of break , continue ends the loop over there and starts a new loop .

Saturday 23 March 2013

Off the grid ...

Hello guys :) I am posting after a long time , it may be yet another couple of weeks until i can get back to blogging regularly , owing to exams/competitions etc etc . Please bear with me :) I Promise to be back with nice tutes and awesome hacks !! Till then cya :) Bye !!

Wednesday 27 February 2013

Working with XML in PHP

Hey guys !! Writing an article after a long long time !! Been a month since i last wrote an article (courtesy mid semester exams) . So today i will give you a basic intro as to how you will load an xml file in php and add stuff to it . It's applications ? Well you may have a sitemap which is to be uploaded in real time as more links are added to your website . Or say you want to store data in xml format and would make an ajax call to the file etc .




 Example of a sitemap.xml file :-

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>localhost/account/id/nraider0207</url>
<url>localhost/account/id/anuragdas</url>
</urlset>


So how can you open up and edit an XML File ?
Consider the following fragment of code :


$xml = new DOMDocument();
$xml-&gt;load("C:\wamp\www\phpweb20\public\sitemap\sitemap.xml");

$root = $xml-&gt;firstChild;
$newElem = $xml-&gt;createElement('url');
$root-&gt;appendChild($newElem);
$txt = $xml-&gt;createTextNode("http://localhost/account/id/example");
$newElem-&gt;appendChild($txt);
$xml-&gt;save("C:\wamp\www\phpweb20\public\sitemap\sitemap.xml");


Let us consider the fragment of code line by line :
The first line creates a new object , which might be used to represent an entire HTML/XML document . Since both xml and html semantics are identical , so this can be used for creating/editing html too . The next line will load the file as given by the location . The next line selects the first child of the document root (since we specified $xml as document root in the first line , if you pass along any other element , the first child of that element will be selected) . In the example i cited above the element is selected . In the following line i create a new element with the name (like the other url's i created before as given in the example) . To push this new element into we use the appendChild method in the next line . Finally we have to populate the element with some contents , preferably in the form of text . For that we use the createTextNode method in the following line , followed by appendChild like before . Then the last and final , but the most important step , which is saving the file . For that we use the save method which takes as a parameter the path to the xml file .


Sunday 3 February 2013

PHP Tutorial . Chapter 5 . PHP Control Statements (Part 1 if-else statement)

What fun is programming if you don't have control over the code ? Best coding practices include writing code that responds differently to different situations . Suppose you have a code let's say , which takes in the type of an employee in an office and accordingly outputs the salary for that position , lets say , what would you do ?

( Cookies again for C Programmers , this section is actually same as the if-else you were accustomed to before !! )

The most popular control statement in any programming language is the if-else construct . So how to use the if else construct ? Let's follow the following example and things will seem pretty easy then .

Algorithm :



Example

Lets say that we have a variable that stores the type of an employee at an office . We will check that variable and print out the corresponding salary .


$a = "General Manager";

if($a=="General Manager")
echo "1000000";
else if($a=="CEO")
echo "2000000";
else if($a=="Chairman")
echo "3000000";

?>

The above code outputs 1000000 .

Also an important aspect of php code is that it continues from the last block . Suppose you have a file containing both php and html . You have a block of php code , then you have some html and then again a block of php code , php will continue from the last line of the previous block . This will be clear from the following example .


Example


$a = 5 ;

if($a==5)
{
echo "The number is equal to 5
";
$a++;
echo "Now it's value is :- ".$a."
";
}
else if($a>5)
{
?>




echo "The number is greater than 5
";
echo "Also this statement is in the second php block
";
}
else
{

echo "The number is lesser than 5
";
echo "Also this statement is in the second php block
";
}

?>

This code won't show any error even though the else-if block is spread across the two blocks . This is quite a flexible feature !! It comes in handy if you want to place some html code within the conditions or within an incomplete block .

Friday 1 February 2013

Chapter 4 . Output (echo and print statements)

Obviously you guys don't want to write php code which does not output anything !! That's why you're here !! Today i'll cover some of the basic output methods in php . I will cover two of the most basic output methods today , and i will introduce you to some advanced output methods which we'll cover later on .


ECHO

Firstly the command which i use the most (okay i'm being partial) , ECHO , the echo command can be used in any one of the following ways :-

echo "This is the text that'll be printed !! ";
echo("This is the text that'll be printed");
echo "This is the text "."that'll be printed" ; // The . joins the two strings and prints them

You can also use commas in the echo without parenthesis :-

echo "This is the text","that'll be printed";

However  you can't use commas in the one with parenthesis .

If you want to print variables , you can do it in the following way :-

echo $a;
echo "The value of a is :- ".$a;
echo "The value of a is {$a}";

However if you use single quotes in the last statement , the sentence will be printed as it is without the $a being substituted by the value it's holding .

PRINT

So what's the basic difference between print and echo ? Well as we saw that echo can take multiple arguments or strings and output them together . However that is not so in case of print . In this case you can have only one argument . Also print returns a value which can be used to determine whether the print statement succeeded or not .

Eg :-

print("Hello World !!");
print($a);


Other methods :- There are other advanced methods like print_r() -> Used to print out the array details or var_dump() -> Used to print out the object details , i'll cover these when i cover the respective chapters on array and objects !! 

Wednesday 30 January 2013

PHP Tutorial . Chapter 3 . Comments

Knowing certain commands , implementing them in your code is one thing , but making your code more organised , more readable to others so that when you work in a team , others should have a rough idea of what your variables and member functions are upto . And for that including comments in your code is a very good idea . You don't know who else might be working on your code so it is a very good idea to convey what your program does through comments . C/c++ coders will be happy to know that commenting works the same way in both of them . Others , chillax , grab a cup of coffee and just follow the examples :-

Single Line Comment :-

$a = 5 ;    //This is an example of single line comment.
$b = 6;    #Another example of single line comment

For a single line comment , you have to give two slashes followed by your comment .


Multi-line Comment :-

$c = 9 ; /* This is an example of multi-line comment
                 2nd line....
3rd line ...
and so on ...
........ */
Remember one thing , you cannot nest multi-line comments like :-

$d= "epic-fail"; /* This /* is
not */correct*/


The word "correct" will be interpreted as a part of the code . So be careful !!

Tuesday 29 January 2013

When to use double quotes and single quotes in php ?

The answer is really simple , if you want to put something in a sentence exactly the way it is , use single string , if u want php to do some processing (identifying the variables etc.) use double quotes . Using single quotes you want be able to reference a variable inside it since php will treat the entire stuff in between the single quotes as a string . But it is not so in case of double quotes !! In case of double quotes php will actually do some processing on it's own and see whether any variables are present inside it and will replace them with their values . Consider the following example :-


$var = "Sample Text !!";
echo '$var';         //Outputs $var
echo "$var";       //Outputs Sample Text!!

?>

Now does that mean we should use double quotes always ? NO !! You must be wondering why ? Well , it's obvious that double quotes will require some more overhead since it does processing , so it will take some more time than single quotes . If there is a single line to be printed or so then this is not an issue , but suppose you have a loop that iterates a million times , what then ? It will be that extra time multiplied by a million !!

Suppose you have something inside the loop which is as follows :-

echo "Item Number :- $item";

Then write it as :-

echo 'Item Number :-'.$item;

In case of larger iterations this method should work more quickly than the previous one !!

Monday 28 January 2013

Php this keyword

Today i am going to familiarize you guys with the $this keyword in php . So what does $this do ? Essentially it is used to access member variables from inside a member function in a class .

Consider the following example :-

class webdevfunda
{
public $var;
private $_var;
public function foo()
{
$this->var = 2;
$this->_var = 3;
}
}

class phptute extends webdevfunda
{
public function zoo()
{
$this->var =4;
$this->_var=6; //Will produce an error
}
}

Note that when zoo tries to access _var it produces an error . This is because zoo is trying to access a private variable of it's parent class which it does not have access to . So it produces an error . In case of a function we can use the self::function_name(); command to invoke the function .

PHP Tutorial : Chapter 2 . Variables and Syntax (Part 3)

Integers and Doubles contd.

Numbers can be assigned to variable in any of the three formats :-
1) Decimal
2) Octal
3) Hexadecimal

Decimal is the default format , to assign a number in octal the octal value should be preceded by a leading 0 , and to assign a number in hexadecimal , the number should be assigned with a leading 0x . The following example assigns the value 4 in decimal , octal and hexadecimal .

$a = 4;
$b = 04;
$c = 0x4;

The largest integer that can be assigned to a variable is 2^31 - 1 and the smallest integer is -(2^31-1) .
Keep in mind that double added to an integer will always yield a double . And doubles print with as minimum places after the decimal as possible . For example 3.645+0.055 will yield 3.7 and not  3.700 .

Booleans

Booleans can attain the value true or false . Howerver how will you determine which constant gives what boolean value ?

Suppose we have something like this :-

if($x)
{
//Perform Something
}

$x might not necessarily contain a boolean value , however the expression inside if will be cast into a boolean value during the execution of the code . So what are the rules followed during such a casting ?

a) Remember that a NULL value evaluates to false .
b) Empty string,array evaluates to false .
c) Any numeric value evaluates to false .

Also i will come to variables holding resources and so on while covering databases afterwards . For now just remember that a variable holding a "failed" value such as a failed database connection , or failed socket connection holds a false value in most of the cases . However it may depend on the situation .

Sunday 27 January 2013

PHP Tutorial : Chapter 2 . PHP Syntax and variables (Part 2)

Suppose you have an expression like the following :-

$a = (9+5)*8/2+3-1*2+7 ;

S what will the expression evaluate to ? While evaluating , it should be kept in mind , that evaluation of expression occurs just like in normal mathematics , i.e. , first the expression within brackets are evaluated then division takes place , after that multiplication , followed by addition and ultimately subtraction . What happens in case the operators have same precedence ? Consider the following example :-

$a = 8.0/2.0/4.0 ;

In this case always remember that , the operations will be carried out from left to right . The expression will have a value of 1.0 and not 16.0 .
----------------------------------------------------------------------------------
To do Create an sample.php file in the following directory C:/wamp/www (the directory may differ based on where you installed wamp) , in case of linux go to /var/www and put the file in there . Now open the file with a text editor and key in the following :-


< html >
< head >
< title > Welcome to my first PHP Program < /title >
< /head >
< body >
< ?php
$a = (19+17)/(3*4)/(3) ;
echo $a ; // Echo takes a string as input and outputs it to the file
? >
< /body >
< /html >


First evaluate the expression yourself and check whether it tallies with the output . To run the file , open up a browser , and type localhost/sample.php .
----------------------------------------------------------------------------------

PHP offers us the following variable types :-

1) Integers . Eg:- 1,-1,0,2,6,-178 and so on
2) Doubles (Numbers with a decimal point) . Eg:- 1.78 , 3.9461 etc
3) Booleans , which can have only two values TRUE and FALSE .
4) NULL is a special type having only one value NULL (i.e., no value)
5) Strings , sequences of characters . E.g :- "This is a string"
6) Arrays , holds a collection of other values . E.g :- $a = array(1,2,"apple",TRUE);
7) Objects , instances of a class (Don't worry i'll explain this in much more detail later on)
8) Resources , variables holding stuff like database connection or stuff like that .

One should keep the following in mind about php variables :-

a) No explicit type declaration is required . For the ones who have programmed in other languages before you must have come across keywords like int,float while defining a variable . Well those are not required over here .

b) Automatic type conversion . PHP automatically converts type as and when required . For eg :-
$c = 3 + 0.14 ; will be evaluated to a double variable .

c) PHP assigns type depending on the situation . For example :-

$sub = substr (45981,2,3);
Substr is a function which extracts a string from another string where the string is the first input , and the next two inputs are the starting point and length of the string to be extracted . However in this case we gave a number so that should give us an error !! However php treats even that number as a string , and we have the output 981 . Thus php does type conversion based on the situation it is in , making it more flexible than other languages !!



Saturday 26 January 2013

PHP Tutorial : Chapter 2 . PHP Syntax and variables (Part 1)

Firstly let me mention something :- Cookies for you c/c++/java programmers or anyone with prior coding experience , for php will seem just like a walk in the park to you guys !!  For others or for first timers , don't worry , PHP is well , rather easy !!

We assign variables in php , in the following manner :-
$var = 1 ;
$str ="This is a string" ;

or just simply :-

$var ;

Confused c/c++/java programmers ? No int , no float , in other words no type declaration ? Well php does not need any type declaration , it's done automatically !!

The following things should be kept in mind about php's syntax :-

1) It is case-sensitive .
2) All statements should end in semi-colon .
3) White spaces are not taken into consideration . For eg :- $x= 2 + 2 ; is the same as $x=2+2;

Php Tutorial : Chapter 1 . Introduction to PHP

What is PHP ? PHP (PHP Hypertext Preprocessor) is an open source server side scripting language . So what is a server side scripting language ? You must have seen some html/css code before by examining the source code of various sides . Now some of these pages are static i.e no matter who the user is , the page will always show the same content . PHP along with some database solution helps us in making web pages dynamic i.e we can show the same page with different data to different users . Example :- Facebook profile page . The basic outlook of the page is the same for all users , however the data that needs to be displayed is different for different users !! Now this cannot be achieved by using traditional html/css . For this we need a server-side scripting solution and a database which will store all the user information . So basically what php does is , it produces the html which will be displayed in the client side . Note that unlike javascript , which can make changes to the page after the page has loaded in the user's browser , php can't make any changes once the page has been sent . This is the primary difference between a client side scripting language (javascript in this case) and a server side scripting language .

Why php and not any other server side scripting language ?

To install php :-

1) For windows :- Download the latest wamp package from here .
2) For linux (in ubuntu) : - Go to the shell and type sudo apt-get install lamp-server^
P.s. DO NOT miss out the ^ after lamp-server .

Thursday 24 January 2013

Notification !! Beginner's corner !!

We'll launch a beginner's section soon !! There you can learn the very basics of web development !! We will post a new lesson everyday !! I apologize for the fact that i cannot upload the whole tutorial at one go due to time constraints . Nevertheless you'll find the tutorial interesting and informative . Please feel free to give suggestions . It'll be highly appreciated :) 

Wednesday 23 January 2013

Why use PHP ?

There are other server-side alternatives such as Ruby On Rails , JSP , ASP.Net etc , So why is php so popular or what are the advantages of php over other server side programming languages ?

Open Source :- Who likes free cookies ? Everyone !! Yes php is open source and comes for free !! Also if you've prior experience in programming languages like C,C++,Java , php is going to be a walk in the park for you !!

Cross platform/Platform independent :- PHP works across various operating systems . They are platform independent and can be used across various platforms . Version compatibility may be an issue sometimes , however most of the newer servers are back-compatible !!

Huge Number of communities :-  So while i was in my initial days of web-development and just become familiar with the concepts of server side and client side , after doing some research i found out that the number of discussion forums , the number of communities of php out numbered those of any of it's other counterparts . So quite obviously , the more the fan following , more is the popularity . Seldom you'll find bugs in your code that hasn't been answered in any discussion forum or community !!

Number of good Frameworks :- It has a large number of good and open source frameworks which includes CakePHP,Zend Framework etc !! These frameworks have a lot of functionality built into them and it'll make life easier for you as a coder !!

Extensions :-  Php has a lot of extensions available out there and therefore is extremely scalable !!

Meme :p

Couldn't help but share this :D



IE meme :D

Tuesday 22 January 2013

Accessing Zend Services behind a proxy !!

Now i am going to share with you guys something that peeved me quite a bit !! I had been writting a small snippet of code which was utilizing Zend_Service_Amazon . I wrote all the code back at home , expecting it to work fine when i went back to my college , so i could finish writing the remaining portion over there . But as soon as i fired up my php script in the browser i started getting an error stating that there was no response received . At first i was confused , then after enabling the error stack trace option in zend , i found out that there was a problem with the client.php file inside zend_install_folder/library/Zend/Http/ .

To use web services behind proxy we need to find the following in the client.php file :-

"protected $config= ..." ,

In the array which is assigned to the config variable , add the following lines :-

'proxy_host'=>'YOUR_PROXY_HOST',
'proxy_port'=>'YOUR_PROXY_PORT'

and find  'adapter'=>'Zend_Http_Client_Adapter_Socket' ,
Change it to 'adapter'=>'Zend_Http_Client_Adapter_Proxy'

And you'r done !!

Create a like button just like facebook !!


Facebook Like Button


Hullo there guys , today i'm gonna give you a step by step tutorial for creating a like button using php/jquery , much like facebook !! So what is the general algorithm that is to be followed ? It's quite simple :-

When a user presses the like button two things should happen :- One , the number of likes should be updated in the database and two , the changes should be communicated to the the front-end that is the number of likes which all the other users are seeing , should be dynamically updated without affecting other page contents .

So how to acheive this ?

First create a mysql table called likes like the following :-

Item_Number   |    Likes
--------------------------

item number is the serial number for the item(post/image/link etc) for which the number of likes are stored in the corresponding column . Now create a php file with the following contents :-

Like.php  (This file will give us the number of likes)

<?php
if(isset($_REQUEST['item_number']))
{
$x = $_REQUEST['item_number'] ;
$connection = mysql_connect("hostname","username","password");
$query = "SELECT * from database_name.likes WHERE Item_Number='{$x}' LIMIT 1";
$result = mysql_query($query);
$r = mysql_fetch_array($result);
echo $r["Likes"];
}
else if(isset($_REQUEST['add']))
{

$x = $_REQUEST['add'] ;
$connection = mysql_connect("hostname","username","password");
$query = "UPDATE Likes SET Likes=Likes+1 from database_name.likes WHERE Item_Number='{$x}'";
$result = mysql_query($query);

}
?>


Now , go to the file which will display the number of likes in real-time . suppose you want to display the number of likes in a div with an id "number_of_likes" , then the following jquery code will help you update the number of likes in real time :-


$(document).ready(function(){
setInterval(function(){
var item_number = 2 ; //say
var request_url = "Like.php?item_number="+item_number; //Build the request url
$.get(request_url,function(res){ $("#number_of_likes").html(res); })
},500)

//Other javascript/jquery code

$("#add").click(function(){

var item_number = 2 ; //say
var request_url = "Like.php?add="+item_number; //Build the request url
$.get(request_url,function(res){ $("#number_of_likes").html(res); })

})

});


So how does the code work ?
 The setInterval function takes in two parameters , the function to be executed and the number of milliseconds after which it'll be executed again and again , so basically what it does is it runs the function at an interval of every 500 milli-seconds  . So what does this function do ? The function basically fetches the contents of the file like.php?item_number=itemno after an interval of 500 milliseconds !! And what does Like.php contain ?? It contains the number of like sfor that particular item number !! So what does the script do then ? Yes it updates the number of likes every 0.5 seconds (1second = 1000 milli-second) , so eureka !! We're Done !!

The add button works in a similar way , just that we invoke it only when an user clicks the like button instead of repeating it !!


Creating the Buton

Just create a button and give it an id of "add"  !!


Sunday 20 January 2013

Implementing your own Image captchas (javascript)


Prevent Automated Input !! Use captchas !!

Hey there guys !! Time for a brief detour from the usual server side coding stuff , let's focus on something more cool today . After going through this post you can pretty much create your own captchas . So why
should we use captchas ?? Let's first see what is the full-form of captcha : "Completely Automated Public Turing test to tell Computers and Humans Apart" .. So i guess now you've got a rough idea what a captcha is used for ? Those of you who are still confused , well , just know that captcha is used to prevent automated software actions . Also there are audio captchas for the visually impaired and so on .


Captcha Text !!


 
So what algorithm did i follow or how did i make the captcha ?
Simple !! I had a pool of images , i just took the input from the user , and then i checked whether the input is a sub-string of the file name of the image , since i had named the files as captcha_<image_text>.jpg . One of the image was chosen at random when the user loaded the page . Is it foll proof ? NO !! Even the recaptcha provided by google isn't , cause the computer knows only one of the two words it shows , it assumes that if u know one word correctly , then you know the other one two , still it works most of the time without any problems !!


I included my version of the captcha below as a drop-box download link .
-->How to use it ?
Just open index.html , Enter the text you see and click ok , if you enter it correctly it'll show success , else it'll show a failure alert .

You can use the code in any way you like , though i personally recommend using the google recaptcha for commercial or large-scale purposes  .

Download The html/Javascript for Captcha

Friday 18 January 2013

Installing Zend Framework


Zend Framework


Installing Zend Framework in WAMP (Windows (7) , Apache , MySQL , PHP) :-

I used the following version of the softwares :-

1) Apache 2.4.2
2) PHP 5.4.3
3) MySQL 5.5.24
4) Zend Framework 1. 12.0

You can use any other databases or packages as you like , the general installation procedure is the same !
My installation directory :- F:\wamp\www\zend , i will use this for future reference .

Step 1 .  Download Zend Framework here (Zend Framework Download Link)

Step 2 . Extract the zipped archive into any directory (in this case F:/wamp/www)

Step 3 . Open php.ini , normally this is situated inside apache/apache2.x.x/bin/ (F:/wamp/bin/apache/apache2.4.2/bin) . If u don't know where it is situated , create a php file with the following as it's contents :-
<?php
echo phpinfo();
?>

Then open it from your browser , it'll list all your php settings and which php.ini file was loaded , you can get the location of php.ini from there !

Step 4 .  Find the following lines :-

; Windows: "\path1;\path2"
include_path = ".;f:\php"   <Your drive , or directory may differ>

Now add the following to include_path :- ;Path\to\zend\library
In my case i had something like this :-

; Windows: "\path1;\path2"
include_path = ".;c:\php\includes;f:\wamp\www\zend\library"

Step 5 . Restart Apache

Step 6 . Add Path\to\zend\bin (Eg :- F:\wamp\www\zend\bin) to your Path system variable (For more information on how to add it to path system variable See This)

That's it , you are all done now !!

To test your installation of Zend Framework , type this at the command prompt :-

zf show version , it should output the current Zend Framework Version !!






PHP Frameworks : What is Zend Framework , and what is MVC?

First things first , What is a framework ?   In real life framework refers to a supporting structure , which helps support something of larger dimensions . In other work a skeleton is to a body what a framework is to a structure ! So in a nutshell what does a framework do ? IT SUPPORTS A LARGER STRUCTURE !!


So what are software frameworks ?

All of you whether you are a coder or not must have come across frameworks . For instance the dot net framework (.NET ) being one of them . Some of you geeks or experienced coders might also have come across other frameworks for python , java or other programming languages . So what is a software framework ? The most simplest way to explain this is :- A software framework is something which gives you lots of pre-baked code , makes your project more structured and hides your implementation details , and in some cases it saves a lot of time . A more nerdier way to put it would be :- It provides various layers of abstraction along with which it provides a pleothra of support programs, API's(Application Programming Interface) etc . Frameworks are not only limited to web applications , there are frameworks for other platforms too . 

Should I Use a framework ?  

Whether to use a framework or not , it actually depends on the size of your project , suppose you have in mind a website which is just about a few pages and uses a single sql table or so , then it is best not to use a framework since it will only add to the size , and a project of such a small scale does not need that much of structuring . You should use a framework when , number one , the project is of a large scale . Two , initially you have just a few visitors , but you know that there will be a substantial increase over time . Three you want scalability !

What is Zend ?



Zend framework is an open-source , object-oriented application framework . It was implemented using PHP5 and is licensed under the new BSD license . It implements the model-view-controller(MVC) pattern . We can use zend for a large number of projects other than using it in application frameworks . I am using Zend for my current project and it's really easy to setup whether you are a windows fan or a linux buff . Also you have total control of your code . Say you want to use only a certain fragment of what zend has to offer , then you can easily use that along with your code or any other api . However it has some issues when it comes to forms . You can't design the form the way you want , you have to bypass the output using php's string functions and so on .


What is MVC ?

MVC is not a new term . Like many great things in the history of computers , it's origin can be traced back to Xerox's PARC ( Trygve Reenskaug) during the late 70's . MVC (Model-view-controller) is a software architecture pattern consisting of three main components as is evident from it's name -> Models , Views and controller . Speaking in terms of web development , view will contain your ultimate html output , that is the one which will be presented to the user . Controller is the one who is responsible for making changes to the databases , or updating a view etc . A model mediates between the views and controllers , it notifies the change in state in either of the view or controller to the other one .


In the next post i will describe the installation process for zend , till then take care !! cheers !!

Download Zend FrameWork here :- Zend FrameWork Download








Thursday 17 January 2013

Secure PHP Programming : Prevent SQL Injection

What is sql injection ?

Consider the following fragment of code :-

$query = "SELECT * FROM table_name where column_name='$some_value'";

AND 

the same query in a different manner :-

$query = "SELECT * FROM table_name where column_name='";
$query.=$some_value;     //some_value contains a value given by the user .
$query.="'";

Consider the second case . Now let us see all the possibilities -

Normally a user would give a regular value which matches the value of a certain field , however say some hacker wants to destroy all your data , he gives something like :-

table_name';DELETE * FROM table_name;

Now consider the entire string :-

SELECT * FROM table_name where column_name='table_name';DELETE * FROM table_name;'

SQL interprets this string in the following way -> since in sql ; signifies the end of a query-statement , so we get two query-statements , one of select and the other one of delete . I hope it is not necessary for me to say what the latter statement can do to your data !! Thus sql can be injected in this way to your site and you will keep on wondering as to where did all the data go !! Deletion , granting of privileges to anonymous users , just think of what can happen , if you don't properly take care of this thing !!



Problem , SQL injection ?


How to prevent sql injection ?

1) Use quotes the way i used them in the first statement , i.e., instead of appending , build the string at one go.

2) Check the type of user's Submitted values.

3) Escape dangerous characters . Use something like mysql_real_escape_string()

Wednesday 16 January 2013

Want Faster database queries ? Try INDEX'ing !!

What is indexing ?

Consider this - suppose you are browsing through the pages of a book and you want to find a particular topic , what would you do ?

Option 1 ( The Dumber Way) - Browse through each page , manually go through all the contents of it , and find the topic you are looking for .

Option 2 (The Smarter Way) - View the contents page , see the page number for that topic , and go to that page .

Indexing works much like option 2 . In other words , indexing allows us to find the data fast without going through all the items in a table .


When to implement indexing ?

Suppose you have a table like this :-

Serial No |  Continent          |  Country
------------------------------------
1             |  Asia                   | India
2             |  Asia                   | China
3             | North America    | USA 
4             | North America    |Canada
5             | Europe                | UK                       ....... and so on

and suppose most of the time you retreive a row or query the table by the name of the country , then you should create an index on the field "country"  . You can also have multiple indexes for a table . When i used index for the first time , i was astonished to see the results . On an average each query was speeded up by atleast 70-80 times !! 

!! WORD OF CAUTION  
Updating a table with syntaxes takes more time than updating one without any , so use indexes carefully . Use them only on fields which are frequently searched against !!


How to implement ?    

Mysql
-------

CREATE INDEX name_of_index ON table_name (fieldname)

to drop an index :-

DROP INDEX name_of_index ON table



MongoDB
-------

database.collection_name.ensureIndex({fieldname1 : 1, fieldname2 : -1})

In this case indexes will be created on both the fields , however , fieldname 1 will be arranged in an ascending order and fieldname 2 in descending !!




PHP : Warning: Cannot modify header information - headers already sent




Consider the following code segment :-

<!DOCTYPE html>
<html>
<head>
<title>
Headers
</title>
</head>
<script>
.
.  /*Your scripts here*/
.
</script>
<?php
.
. /*some code*/
header ('Location: http://www.mysite.com/');
?>


The given code will give you an error , stating that headers were already sent

Why ??

Headers are normally sent before a session is started . Here before the php code , we already have something which the client side browser will render , and so headers will already be sent . Even if there is nothing but a whitespace , then also we'll have a similar error.

Solution !!

Place the php script containing the header at the beginning of the php file . That'll settle all issues !! Remember there shouldn't even be any white spaces before the opening <?php tag .

 --------------------------------------------------------------------------------------
<?php
.
. /*some code*/
header ('Location: http://www.mysite.com/');
?>
<!DOCTYPE html>
<html>
<head>
<title>
Headers
</title>
</head>
<script>
.
.  /*Your scripts here*/
.
</script>



MongoDB : What , Why and When ?

What is MongoDB ?
MongoDB is an open-source database system , developed by 10gen which is document-oriented unlike many other relational databases like mysql . It belongs to a family known as "NoSQL" . Instead of storing data in tables , like relational databases , MongoDB stores data in JSON-like documents , the format being commonly known as BSON . However it incorporates some traditional features like replication , indexing etc much like normal relational databases do . It incorporates a javascript shell , through which we can carry out the common querying tasks .


MongoDB Meme
Mongo FTW !!



Why should MongoDb be used and when should we use it ?
MongoDb , like other NoSQL Databases , is used , when the data under question does not follow a relational model . 

For example :-
{
"_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
"name" : "Anurag",
"lastname" : Das,
}  


{
"_id" : ObjectId("4b2b9f67a1f631733d917a7c"),
"Country" : "India",
"State" : "West Bengal",


Both of these documents (analogous to rows in SQL) are a part of the same collection (analogous to tables) , notice that the two field names are different !! Cool , isn't it ? That's the flexibility you get by using MongoDB , or other NoSQL Databases

The data can be structured , that is not a problem , but it's used when retreival of large amounts of data from the database , rather than the relationship between the data items , matter the most . In the posts to follow you'll get a clear understanding as to what is MongoDB and how you should use it .

Tuesday 15 January 2013

How to download a file to your own server (from a remote source) ?

Download file (without proxy)

The following php script helps you to download a file from a remote url ($url) to your local server directory($dir) :-



function download($url,$at)
{
$remote_url = "$url";
$local_filename = $at; // say :- "C:/123.jpg"
try
  {
  $file = fopen ($remote_url, "rb");
  if (! $file) {
        throw new Exception("Could not open the file!");
 }
  if ($file) {
    $newf = fopen ($local_filename, "wb");

    if ($local_filename)
    while(!feof($file)) {
      fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }

  if ($file) {
    fclose($file);
  }

  if ($newf) {
    fclose($newf);
  }
  }
  catch(Exception $e)
  {
  echo "Error (File: ".$e->getFile().", line ".
          $e->getLine()."): ".$e->getMessage();
  }
}

------------------------------------------------------------------------------------------------------------

Download File (With Proxy)



This method does not work if you use a proxy . For that we need to use a modified method , which will be something like this :-



function modified_download($url,$at)
{

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'proxy'=>"YOUR_PROXY:PORT",
'header'=>'Content-type : image/JPEG',
'request_fulluri' => True // do not miss out this line
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */



$target = $url;
$local_filename = $at;
try
  {
  $file = fopen($target,"rb",false,$context);
  if (! $file) {
        throw new Exception("Could not open the file!");
    }
  if ($file) {
    $nf = fopen ($local_filename, "wb");

    if ($nf)
    while(!feof($file)) {
      fwrite($nf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }

  if ($file) {
    fclose($file);
  }

  if ($nf) {
    fclose($newf);
  }
  }
  catch(Exception $e)
  {
  echo "Error (File: ".$e->getFile().", line ".
          $e->getLine()."): ".$e->getMessage();
  }

}