Sunday, November 20, 2011

PHP mysql_connect Vs mysql_pconnect

  • Both "mysql_connect" and "mysql_pconnect" are used to connect MySQL database by PHP. Both are having similar function signature.
  • Main difference is, if we use "mysql_pconnect", this function would first try to find a persistant link that is already open with the same host, username and password.
  • In other words, mysql_pconnect() will try to find a connection that's already open, with the same host, username and password. If one is found, this will be returned instead of opening a new connection
  • "mysql_close" function can't close the database object if we connect the database with "mysql_pconnect" method.
  • For low traffic websites, its better to use mysql_pconnect method to increase the performance of the website. And for high traffic websites we should use "mysql_connect". Because, in high traffic, lot of database connections will be opened and they will lag the system performance.

Tuesday, May 17, 2011

Cookies in PHP

There are two types of Cookies present in PHP. One is Persistant Cookie and the other one is Temporary Cookie.
By default, cookies are created as temporary cookies which stored only in the browser's memory. A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
  • Temporary cookies can not be used for tracking long-term information.
  • Persistent cookies can be used for tracking long-term information.
  • Temporary cookies are safer because no programs other than the browser can access them.
  • Persistent cookies are less secure because users can open cookie files see the cookie values

What is MVC Architecture

Model-view-controller (MVC) is a design pattern used in software engineering. In complex computer applications that present lots of data to the user, one often wishes to separate data (model) and user interface (view) concerns, so that changes to the user interface do not impact the data handling, and that the data can be reorganized without changing the user interface. The model-view-controller design pattern solves this problem by decoupling data access and business logic from data presentation and user interaction, by introducing an intermediate component: the controller.

Monday, May 2, 2011

File Uploading with out using Ajax

We can't upload file using normal Ajax. For that we should use advanced javascript frameworks or JSON for passing file content. Also this javascript will not work if it is disabled from the browser.
But we can get this Ajax effect without using ajax or javascript by simply depending on target attribute of the form tag.
Below is the sample script to achive this.



File name: form.html
<iframe src="http://www.genengnews.com/app_themes/genconnect/images/default_profile.jpg" id="targetFrame" name="targetFrame" style="border: 0; height:230px; width: 230px;"></iframe>
<form action="upload.php" target="targetFrame" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>


File name: upload.php
<?php
if(isset($_FILES["file"])) {
 // You can add file uploading script here
 echo "Temporary file location is: " . $_FILES["file"]["tmp_name"] . "<br />";
 if(substr($_FILES["file"]["type"], 0, 5) == "image") {
  echo '<img src="' . $_FILES["file"]["tmp_name"] . '" alt="" />';
 }
?>
<?php
}
?>

Wednesday, April 20, 2011

PHP Access Specifiers

Access Specifiers are the keywords in PHP, which will tell us about the visiblity of property or method.
Public, Private and Protected are the three Access Specifier Keywords in PHP. Below is the difference between each of them.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.
Default access specifier is Public.

Monday, April 18, 2011

HTML Optimization Techniques

Below are some of the techniques for HTML optimization:
1) Minimal Meta Tags usage: Minimizing the size of page's HEAD is an effective means to achieve quicker parsing of the HEAD, followed by the rest of the content of your website, in equally quick succession. The conditional SSI META tags with 200 characters or less and HTML lines with maximum 255 characters fetch favorable search engine results by saving space for browsers visiting your site. Further, there's no need to use commas to separate keywords, as search engines ignore the commas.
2) CSS Layout: Inline CSS will slow down the process page loading and page rendering. Always it will be better to link an external css file to the HTML file. Don't use import statement for css loading.
3) Javascript: Optimization of JavaScript is achieved with short variable names and no spaces etc, which speeds up the display of Web Pages. Avoid writing javascript in HTML file. Always include this javascript file at the end of the page to improve page loading speed.
4) Use DIVs rather than Tabes: Tables will load very slowly compare to DIV. We can achieve complete table layout by using Divs with simple CSS.
5) URL Abbreviation: By abbreviating URL using Apache's mod_rewrite module, we achieve effective cut down to your HTML file size.
6) HTML Compression: Compressing your HTML using utility like mod_gzip, automatically cuts down size of the web page for as much as 40% bandwidth and thus speeds up the page display immensely.
7) Reduce Images: Try to use low size image files in the layout. And try to reduce image backgrounds and achieve it by css properties.
8) Use Sprites: By using Sprites we can reduce maximum number of image requests on server. We can simply use one image for several image displays by modifying its position by using CSS.
9) Use multiple servers for external files: Try to store images and external javascript and css files in sub domains and try to use them in the webpage. By this way both html an images will be loaded simultaneously.

Sunday, April 17, 2011

MySQL :: How to delete dummy rows in a table

Below is the solution if you don't know how many dummy records present in the table:
CREATE TABLE tmp SELECT DISTINCT * FROM emp;
DROP TABLE emp;
ALTER TABLE tmp RENAME TO emp;
Below is the process if you know the data in the table:
Let us consider below sample table:
Table name user:
fname            lname            salary
Raj                 kumar         15000
Krishna         sumanth    21000
Krishna         sumanth    21000
Mahesh         Kalyan        12000
In the above case if we have to delete the record, "Krishna" use below query:
Delete from user where fname="Krishna" and lname="sumanth" and salary = "21000" limit 1;

MVC Architecture

The main aim of the MVC architecture is to separate business logic and application data from the presentation data to the user. Below are the why should we use MVC design pattern:
1. Re Usable: When the problem recurs, there is no need to invent a new solution. We just have to follow the defined patterns and adapt it as necessary.



2. Expressive: By using this MVC architecture, our application will become more expressive.

3. Easily Managable: Any software developer can easily understand the logic of implemented script.
MVC explanation:
1) Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser. 
2) View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
3) Controller:  Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In  GUIs, the views and the controllers often work very closely together.

OOP features not supported by PHP

Compare to other OOP languages like JAVA, PHP will not support some of OOP concepts. We should aware of these before going to implement complete OOP based programing.
1.Namespaces: Initial PHP5 version has this feature. But its support was removed in lateral stages. It's not clear whether namespace support will be integrated into a future version.
2. Method overloading: The ability to implement polymorphism through functional overloading is not supported by PHP and, according to a discussion on the Zend Web site, probably never will be. Learn more about why at http://www.zend.com/php/ask_experts.php.
3.Operator overloading: The ability to assign additional meanings to operators based upon the type of data you're attempting to modify did not make the cut this time around. According to the aforementioned Zend Web site discussion, it is unlikely that this feature will ever be implemented.
4.Multiple inheritance: PHP does not support multiple inheritance. Implementation of multiple interfaces is supported, however.

Friday, April 15, 2011

Reading Files or Images from a Folder using PHP

<?
class filelist {
 var $files;
 // the class uses extensions like ("jpg","gif","png")
 // the function prepends the document root, so
 // give directory information like "/images/album"
 function GetList($directory,$ext = FALSE) {
  $files = array();
  $handle = opendir($directory);
  while(false !== ($file = readdir($handle))) {
 
   //GET THE FILES ACCORDING TO THE EXTENSIONS ON THE ARRAY
 
   for ($i = 0; $i < count($ext); $i++) {
    if($ext and count($ext)) {
     if (eregi("\.". $ext[$i] ."$", $file)) {
      $files[] = $file;
     }
    } else {
     if($file != "." && $file != "..") {
      $files[] = $file;
     }
    }
   }
  }
  closedir($handle);
  $this->files = $files;
 }
 function WriteList($dir,$ext = FALSE) {
  $this->GetList($dir,$ext);
  foreach ($this->files as $element) {
   echo "$element\n";
  }
 }
 function WriteImages($dir,$ext = FALSE) {
  $this->GetList($dir,$ext);
  shuffle($this->files);
  //for ($i = 0; $i < 4; $i++) {
  foreach ($this->files as $element) {
   echo "<p><img src=\"$dir/$element\" alt=\"Photo Album\" height=147 border=0></p>\n";
  }
 }
}
// usage
$filelist= new filelist();
$ext = array("jpg", "gif", "png");
$filelist->WriteImages("C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures", $ext);
?>

PHP Age Calculator

<?php
function age_calculator($day,$month,$year){
 if (date("n") > $month)
  $age = (date("Y") - $year);
 elseif (date("n") == $month){
  if (date("j") < $day) $age = (date("Y") - $year) - 1;
  else $age = (date("Y") - $year);
 }
 else $age = (date("Y") - $year) - 1;
 return $age;
}
?>

Real time Email Vaildation in PHP

In most of the application, I've simply checked email pattern for validation. I never tried to implement whether email exists or not. Because of this lots of unnecessary records will be inserted into database.
Using PHP built-in functions (Socket programming and DNS functions) we can find out whether the provided email address is existed or not. I've got this script from ZEND IDE code snippets.
<?
/* =======================================================================
  
 ifsnow's email valid check function SnowCheckMail Ver 0.1
 
 funtion SnowCheckMail ($Email,$Debug=false)
 $Email : E-Mail address to check.
 $Debug : Variable for debugging.
 * Can use everybody if use without changing the name of function.
 Reference : O'REILLY - Internet Email Programming
 ifsnow is korean phper. Is sorry to be unskillful to English. *^^*;;
========================================================================= */
function SnowCheckMail($Email,$Debug=false)
{
    global $HTTP_HOST;
    $Return =array(); 
    // Variable for return.
    // $Return[0] : [true|false]
    // $Return[1] : Processing result save.
    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email)) {
        $Return[0]=false;
        $Return[1]="${Email} is E-Mail form that is not right.";
        if ($Debug) echo "Error : {$Email} is E-Mail form that is not right.<br>";        
        return $Return;
    }
    else if ($Debug) echo "Confirmation : {$Email} is E-Mail form that is not right.<br>";
    // E-Mail @ by 2 by standard divide. if it is $Email this "lsm@ebeecomm.com"..
    // $Username : lsm
    // $Domain : ebeecomm.com
    // list function reference :
http://www.php.net/manual/en/function.list.php
    // split function reference :
http://www.php.net/manual/en/function.split.php
    list ( $Username, $Domain ) = split ("@",$Email);
    // That MX(mail exchanger) record exists in domain check .
    // checkdnsrr function reference :
http://www.php.net/manual/en/function.checkdnsrr.php
    if ( checkdnsrr ( $Domain, "MX" ) )  {
        if($Debug) echo "Confirmation : MX record about {$Domain} exists.<br>";
        // If MX record exists, save MX record address.
        // getmxrr function reference :
http://www.php.net/manual/en/function.getmxrr.php
        if ( getmxrr ($Domain, $MXHost))  {
      if($Debug) {
                echo "Confirmation : Is confirming address by MX LOOKUP.<br>";
              for ( $i = 0,$j = 1; $i < count ( $MXHost ); $i++,$j++ ) {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Result($j) - $MXHost[$i]<BR>"; 
        }
            }
        }
        // Getmxrr function does to store MX record address about $Domain in arrangement form to $MXHost.
        // $ConnectAddress socket connection address.
        $ConnectAddress = $MXHost[0];
    }
    else {
        // If there is no MX record simply @ to next time address socket connection do .
        $ConnectAddress = $Domain;        
        if ($Debug) echo "Confirmation : MX record about {$Domain} does not exist.<br>";
    }
    // fsockopen function reference : http://www.php.net/manual/en/function.fsockopen.php
    $Connect = fsockopen ( $ConnectAddress, 25 );
    // Success in socket connection
    if ($Connect)  
    {
        if ($Debug) echo "Connection succeeded to {$ConnectAddress} SMTP.<br>";
        // Judgment is that service is preparing though begin by 220 getting string after connection .
        // fgets function reference :
http://www.php.net/manual/en/function.fgets.php
        if ( ereg ( "^220", $Out = fgets ( $Connect, 1024 ) ) ) {
            
            // Inform client's reaching to server who connect.
            fputs ( $Connect, "HELO $HTTP_HOST\r\n" );
                if ($Debug) echo "Run : HELO $HTTP_HOST<br>";
            $Out = fgets ( $Connect, 1024 ); // Receive server's answering cord.
            // Inform sender's address to server.
            fputs ( $Connect, "MAIL FROM: <{$Email}>\r\n" );
                if ($Debug) echo "Run : MAIL FROM: &lt;{$Email}&gt;<br>";
            $From = fgets ( $Connect, 1024 ); // Receive server's answering cord.
            // Inform listener's address to server.
            fputs ( $Connect, "RCPT TO: <{$Email}>\r\n" );
                if ($Debug) echo "Run : RCPT TO: &lt;{$Email}&gt;<br>";
            $To = fgets ( $Connect, 1024 ); // Receive server's answering cord.
            // Finish connection.
            fputs ( $Connect, "QUIT\r\n");
                if ($Debug) echo "Run : QUIT<br>";
            fclose($Connect);
                // Server's answering cord about MAIL and TO command checks.
                // Server about listener's address reacts to 550 codes if there does not exist 
                // checking that mailbox is in own E-Mail account.
                if ( !ereg ( "^250", $From ) || !ereg ( "^250", $To )) {
                    $Return[0]=false;
                    $Return[1]="${Email} is address done not admit in E-Mail server.";
                    if ($Debug) echo "{$Email} is address done not admit in E-Mail server.<br>";
                    return $Return;
                }
        }
    }
    // Failure in socket connection
    else {
        $Return[0]=false;
        $Return[1]="Can not connect E-Mail server ({$ConnectAddress}).";
        if ($Debug) echo "Can not connect E-Mail server ({$ConnectAddress}).<br>";
        return $Return;
    }
    $Return[0]=true;
    $Return[1]="{$Email} is E-Mail address that there is no any problem.";
    return $Return;
}
?>

Tuesday, April 12, 2011

PHP Coding Standards

How many of us are using proper coding standards. Of course I'm also not following proper defined coding standards.
To know about your mistakes, bugs or issues in your coding install a PEAR package, "PHP_CodeSniffer".
It will calculate number of spaces in code indentation also. Being a professional developer we should start with this framework and make our coding standards as good as possible.
Please refer the link http://pear.php.net/package/PHP_CodeSniffer for complete usage of this PEAR package.
Thanks to my PL Mr. Akilan for providing me the information on this tool.

Automated Test cases in PHP

Yesterday I had a discussion with my new Project Lead Mr. Akilan T, I came to know this information.
If we are ready to follow Extreme Programing guidelines, we should define proper test cases before starting coding part. Not only testing but also developers should involve in writing test cases. Being a developer, I know the difficulties in writing test cases being a developer prospective. To overcome this overhead process we can make use automated tools for writing these test cases.

PHPUnit provides a framework for creating a test suite to automate testing of functions and classes. While writing a class file we should extend "PHPUnit_TestCase" class and move forward. From this extended class we can send testing data and also we can get defined test cases after executing the class file.
For more information about this framework please go through the URL: http://pear.php.net/manual/en/package.php.phpunit.php

Friday, April 8, 2011

How to configure the Apache mod_rewrite module

  1. Open the Apache configuration file located at /etc/httpd/conf/httpd.conf
  2. Change AllowOveride None to AllowOveride All inside the DocumentRoot Directory Directive, normally <Directory "/var/www/html">

How to prevent Email addresses from spambots in a webpage using PHP

If we place direct email address in our webpages hackers spombots will read the email addresses and hackers will send automated spam emails to these email addresses.
These public email addresses will receive lots of automated spam emails every day.
To prevent this effect we have to use HTML encrypted string or URL encrypted string in the place of direct email address.
For example: If we place below HTML tag in the website,
In anchor link we should use URL encrypted string and in navigation text we should place HTML encrypted text.
So our updated HTML script will be similar t below:
<a href="m%61i%6c%74o:%74e%73t%65%6da%69l%64e%6da%69%6c%2ecom">t&#101;st&#101;&#109;&#97;i&#108;&#64;e&#109;&#97;il&#46;co&#109;</a>
If we place above script in HTML file output will be our normal URL.
We can use below PHP functions to convert email address to encrypted string.
<?php
/**
 * Function to return url/html encrypted email address
 *
 * @param string $emailId
 * @param string $displayType, values should be text or url
 * @return string encrypted email address
 */
function makeSpambotFree($emailId, $displayType="text") {
 $output = "";
 $displayType = ($displayType == "url") ? "url" : "text";
 srand(microtime() * 1000000);
 if($displayType == "text") { // for displaying the email address in web page
  for ($i = 0; $i < strlen($emailId); $i = $i + 1) {
   $j = floor(rand(0, 1));
   if ($j==0) {
    $output .= '&#'.ord(substr($emailId,$i,1)).';';
   } elseif ($j==1) {
    $output .= substr($emailId,$i,1);
   }
  }
  $output = str_replace('@','&#64;',$output);
 } else { // for passing email address in anchor link
  for ($i = 0; $i < strlen($emailId); $i = $i + 1) {
   $j = floor(rand(0, 1));
   if ($j==0) {
    $output .= substr($emailId,$i,1);
   } elseif ($j==1) {
    $output .= '%'.padZeros(dechex(ord(substr($emailId, $i, 1))), 2);
   }
  }
  $output = str_replace('@','%64',$output);
 }
 return $output;
}
/**
 * For returning url encrypted character
 *
 * @param int $number
 * @param int $length
 * @return return url encrypted string
 */
function padZeros($number, $length) {
 return sprintf('%0'.$length.'s', $number);
}
// Usage
echo makeSpambotFree("testemail@email.com"); // for text
echo makeSpambotFree("mailto:testemail@email.com", "url"); // for anchor url
?>

REST Requests in PHP

REST is a way of interacting with resources on the web via a plain URL. It stands for REpresentational State Transfer.
REST-style architectures consist of clients and servers. Clients initiate requests to servers and Servers process these requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources.
A basic web page is an example of a REST resource.
The REST architectural style describes six constraints applied to the architecture as below
Client–server, Stateless, Cacheable, Layered system, Code on demand (optional) and Uniform interface
We can know more info about REST from WIKI by searching for "Representational State Transfer".
PayPal API, Twitter API, Google HTTP Geo Coder are some of the examples for REST APIs.
In PHP how do we call these REST Requests:
CURL and FILE_GET_CONTENTS are the two methods by which we can send REST Requests to remote servers.

Difference between Abstract and Final Classes

  • Abstract class can not be instantiated. In other words we can't create direct object to Abstract class. But for Final classes we can create an instance.
  • Abstract class must be extended where are Final class can not be.
  • Final class can't contain abstract methods but Abstract class may contains final methods.

Thursday, April 7, 2011

How Session works if Cookies are disabled in PHP

Session will work if cookies are enabled in browser. If cookies are disabled, then apache checks whether PHP is configured with
--enable-trans-sid
and
--enable-track-vars
options.

If these values are set true, then PHP will pass session id by POST method automatically. But we have to use session functions regularly.
If "--enable-trans-sid" and "--enable-track-vars" values are set to FALSE, we need to pass session id by using the SID constant.
< a href="index.php?<?= SID ?>" >Navigate from here< /a >

Ajax Disadvantages

  • If you use ajax, Hackers can apply cross-Scripting, and can attack your website easily.
  • One biggest problem of ajax is browsers support or its integration with browsers. Ajax will not work in older browsers and text browsers and javascript disabled browsers.
  • Some times dynamically created ajax pages,wont register in browsers history. To do this, most of them uses frame, even though it is one of the major disadvantage
  • Bookmarking the page that uses the ajax will not work properly,
  • It take too much time to get response for request.
  • Latency in the network will be slow.
  • SEO will be failed in Ajax.

Ajax Advantages

  • Reducing load on server by fetching required data from server.
  • Reduction of unnecessary web server hits
  • Rich, responsive user interface
  • Real-time web page updates
  • Language neutrality
  • Faster web page renderings
  • Less consumption of server's resources (memory and processor load is reduced)
  • In the Ajax enabled web applications, requests are sent to the server only for the data that is needed. The entire web page is not submitted at one go.

Ajax Browser Compatibility


Ajax is having Cross Browser compatibility issue. We need to use different objects for different browsers. For IE 5 and IE 6 we need to use ActiveXObject. For IE7+ and Gecco browsers we need to use XMLHttpRequest.

What is Ajax


The main challenge of web developer is to provide a simple, fast and attractive presentation to end users. These challenges can be achieved by using the powerful concept called AJAX.
The term Ajax, stands for "Asynchronous JavaScript and XML"
Below is the description for these three terms:
Asynchronous
When we send a request to server, we need to wait for the response to come back, We are free to do other things until we get the response. Probably the response may not come back immediately. So we need to set up a function that will wait for the response to be sent back by the server, and react to it once that happens.
JavaScript
Javascript is technology independent. We can integrate Javascript in multiple technologies. JavaScript is used to make/send a request to the server. Once the response is returned by the server, we will generally use some more JavaScript to modify the current page's DOM source in some way to show the user that the submission went through successfully.
XML
The data that which we receive back from the server will often be packaged up as a snippet of XML, so that it can be easily processed with JavaScript. This data can be anything you want, and as long as you want.
Ajax is technology independent. It can be implemented in JAVA, PHP, Ruby, Microsoft .NET and many more.

Wednesday, April 6, 2011

SQL injection - Complete description

Its a very severe issue lots of low slandered websites are facing this issue.
SQL injection is a code injection technique that impose on a security vulnerability occurring in the database layer of an application.
The unsteadiness is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.
It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.
By this SQL injection will give a chance to hackers to login to website with out proper user details, to delete the table data or its a possibility to drop entire database. Here is a some examples of SQL injection techniques.
Below is the simple PHP program which we will use to fetch user data.
<?php
$sql = "SELECT * FROM user where user_name = '" . $_POST["username"] . "' AND password = '" . $_POST["password"] . "'";
$result = mysql_query($sql);
?>
In the form I'll submit below values
Username = testuser
password = testpassword
Then our SQL query will become as below:
SELECT * FROM user where user_name = 'testuser' AND password = 'testpassword';
This above query will execute properly with out any issues.
But I'll provide the data as below:
Username = testuser' OR 1=1;--
Password = hellostring
Now the query becomes:
SELECT * FROM user where user_name = 'testuser' OR 1=1; --' AND password = 'hellostring';
In MySQL "--" represents a comment. Query will not be executed after "--".
So my executable query becomes,
SELECT * FROM user where user_name = 'testuser' OR 1=1;


This above query will definitely returns not null result set. So hacker can login in automatically.
If hacker knows database table name or database name then hacker can simply drop the data.
I'll simply enter the values as below:
Username = testuser' OR 1=1; drop table user; --
Password = dummydata
Now our query will become:
SELECT * FROM user where user_name = 'testuser' OR 1=1; drop table user; --' AND password = 'dummydata';
";" is a statement terminator in MYSQL. So first two queries will be executed with one instance and our user table will be dropped.
How to prevent SQL injection:
SQL Injection will be solved if we handle single quote and/or double quote in parameter values. We need to escape those quotes. For that simply we need to replace "'" with "\'" and '"' with '\"'. Then there won't be any issues with SQL injection.
In PHP we are having built in function to escape single quotes: mysql_real_escape_string
This fuction will add a backslash before single quote in the passed parameter.
So your select query must be in the below mentioned pattern:
<?php
$sql = "SELECT * FROM user where user_name = '" . mysql_real_escape_string($_POST["username"]) . "' AND password = '" . mysql_real_escape_string($_POST["password"]) . "'";
$result = mysql_query($sql);
?>

Wednesday, March 23, 2011

Differences between PHP 4 and 5

1. In PHP 4 all values are Passed by value where as in PHP 5 all values are passed by reference.
Ex:
$person1 = new Person();
$person1->sex = 'male';
$person2 = $person1;
$person2->sex = 'female';
echo $person1->sex; // Will be 'female'

2. If you want to duplicate the object we should use “Clone” keyword.

3. Access Specifiers have been implemented:
         1. Public is the most visible, making methods accessible to everyone and properties readable and writable by everyone.
         2. Protected makes members accessible to the class itself and any subclasses as well as any parent classes.
         3. Private makes members only available to the class itself.

4. Class constants have been implemented. These are similar to “define” constants but these are contained with in the class only. We can access these variables by using “::” operator.
  
5. Static keyword has been implemented to define static methods with in the class. There is no need to create class object to access static methods of the class. We can use “::” operator.
  
6. Unified constructors and destructors have been added. In PHP4 constructor is a method in class having the name as class name. With any reason if we modify class name we should modify all constructor instances in all over the code. The new constructor method name is “__construct” and new destructor method name is “__destruct”. Destructor will be called when object is destroyed.

7. Abstract classes have been added in PHP5
  
8. PHP5 introduces Interfaces as well to implement better OOP concept.
  
9. Magic methods (Ex: __call, __get, __set, __toString etc) have been added.
  
10. Final keyword and __autoload function are also added.
  
11. Exceptions have been added in PHP5
 
12. Type Hinting is also implemented. This means you can enforce what kind of variables are passed to functions or class methods.
 
13. IN PHP4 “foreach” method works only for arrays where as in PHP5 it will work for both arrays and objects.
 
14. New Extensions: SimpleXML, DOM and XSL, PDO and Hash extensions have been added.
 
15. Lots of extra functions on Arrays, InterBase, iconv, streems, date and time related, strings and other functions have been added. You can find the list of these functions in http://php.net/manual/en/migration5.functions.php URL

Monday, February 28, 2011

How to create VIRTUAL HOST in APACHE

We need to modify Apache configuration file httpd.conf for creating virtual host. At the end of the file we need to place below sample code.

<VirtualHost www.sunwaretech.net>
ServerAdmin admin@sunwaretech.net
DocumentRoot /home/apache/share/htdocs/hostedsites
ServerName www.sunwaretech.net
ErrorLog /home/apache/logs/error/hostedsites/error_log
TransferLog /home/apache/logs/access/hostedsites/access_log
</VirtualHost>


Simply we need to mention domain name, server admin email address, document root, server name and log files path.

Difference between CHAR and VARCHAR datatypes

CHAR is a fixed-length character data type where as VARCHAR is a variable-length character data type.
CHAR should be used for storing fixed length character strings. String values will be space/blank padded before stored on disk. If this type is used to store variable length strings, it will waste a lot of disk space.
 
Where to use:
You can use CHAR when the data entries in a column are expected to be the same size.
You can use VARCHAR when the data entries in a column are expected to vary considerably in size.

Sunday, February 27, 2011

How to use PHP CURL

Below is the sample basic code for using the curl.

<?php

 // create a new cURL resource
 $ch curl_init();
// set URL and other appropriate options

 $options = array(CURLOPT_URL => 'http://www.example.com/',
                 
CURLOPT_HEADER => false
                
);
curl_setopt_array($ch$options);


//curl_setopt($ch,CURLOPT_URL,'http://google.com'); You can use this line rather than the above two lines for initializing the URL.

 // grab URL and pass it to the browser 
curl_exec($ch);
// close cURL resource, and free up system resources

 curl_close($ch);

?>


Below is the explanation of the above functions
  • curl_init method used to initiate curl object.
  • curl_setopt method for setting options to curl object
  • CURLOPT_URL = Curl Option URL, here we need to set the remote server URL
  • curl_exec method will execute the curl object.
  • curl_setopt_array method used to send multiple parameters as an array.
Start make use of this cURL features and feel the joy of it.

PHP CURL Installation in Windows and Linux

PHP has a very powerful library to fetch data from remote servers which is nothing but CURL. It stands for Client URL.

PHP must be compiled with curl library to make use of these libraries.

In Linux, you need to compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In include folder there should be a folder named curl which should contain the easy.h and curl.h files. It should be a file named libcurl.a located in the lib folder. From PHP 4.3 you can configure PHP to use cURL for URL streams -- with-curlwrappers.

For Windows, go to PHP environment path, WINDOWS/System32 folder is the default one for windows XP operating system. You must copy php_curl.dll to this folder.

In php.ini file remove ";" from the line extension=php_curl.dll

Restart Apache services. Then cURL will be enbled