Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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 !! 

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 .

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 !!

Tuesday, 22 January 2013

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"  !!


Friday, 18 January 2013

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

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>



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();
  }

}