Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Feb 3, 2012

Learn CakePHP From Novice to Professional : Part 2

Model-View-Controller


Cake enforces an MVC structure for your web applications. Basically, it effectively separates typical operations into specific areas:















MODELS :for all your database interaction
VIEWS :for all your output and displays
CONTROLLERS :for all your commands/scripts for input and program flow

The typical PHP application mixes each of these three functions in the same code, making it difficult to maintain and debug.

The typical flow for PHP scripting

This is the typical flow for PHP scripting (see Figure 1-1):

  1. The client sends a request to a PHP script by typing a URL or clicking a link of some kind.

  2. The script processes the data and then sends the database requests directly to the database.

  3. The script receives any database output and processes the data.

  4. The script generates output and forwards it to the client’s browser.


In short, everything is contained in one PHP script. By using the include() function, developers strip out common functions into other external files, which makes it possible to reduce redundancy. The most complex PHP applications use objects that can be called anywhere in the application and modified depending on the variables and settings passed to them. Developers, when using objects and classes, can structure the application in numerous ways.

MVC improves upon the typical PHP flow and is an effective technique for making class objects available over the whole application. The main goal behind MVC is to make sure that each function of the application is written once and only once, thus streamlining code by reducing redundancy. Cake accomplishes this goal by not only providing the resources to make MVC possible but also by using a consistent method for where to store operations in the application. Simply naming your own files a certain way allows Cake to piece together the various resources without using any code specifications.

How Cake makes use of the MVC structure

MVC can vary depending on the framework with which you’re working, but generally it works as follows (see Figure 1-2):

  1. The client sends a page request to the application, either by typing a URL or by clicking a link of some kind. By convention, a typical URL is usually structured like this:
    http://{Domain}.com/{Application}/{Controller}/{Action}/{Parameter 1, etc.}


  2. The dispatcher script parses the URL structure and determines which controller to execute. It also passes along any actions and parameters to the controller.

  3. The function in the controller may need to handle more data than just the parameters forwarded by the dispatcher. It will send database requests to the model script.

  4. The model script determines how to interact with the database using the requests submitted by the controller. It may run queries with the database and do all sorts of handy data-sorting instructions.

  5. Once the model has pulled any data from or sent data to the database, it returns its output to the controller.

  6. The controller processes the data and outputs to the view file.

  7. The view adds any design or display data to the controller output and sends its output to the client’s browser.


The benefit of using MVC to develop web sites is that repeated functions or tasks can be separated, thus allowing for quicker edits. It can even help in debugging. Say an error keeps occurring during the interaction with the database. Usually the problem will be somewhere in a model. Knowing that all database interactions occur in just one place makes it easier to solve problems.

Feb 1, 2012

Learn CakePHP From Novice to Professional : Part 1

This guide is for beginners to CakePHP. Whether or not you have much experience with the PHP scripting language, working in Cake will require some new methods you may or may not have tried before. If you don’t know what a “has-and-belongs-to-many” relationship is, don’t know how to build your own class object, or don’t know how to parse an array, then this tutorial is a perfect place to start when getting into Cake.

Why Cake?




Ever since Ruby on Rails became a popular web-based framework, teams of developers have been creating clones of Rails or Rails-like frameworks for various languages: TurboGears for Python; Zend, Symfony, and many others for PHP; Catalyst for Perl; and on and on. With so many options out there, why choose CakePHP for your web project?

It’s PHP!


Many PHP developers overlook the benefits of a framework and simply look for premade functions or classes to be used as includes in their scripts or, as with Perl, pullin modules that chew up lots of time on the server and provide little customization. Cake, however, is thoroughly object-oriented in its scope. It supplies objects that can be implemented and modified to your liking and is not just some module or set of includes that give you little control.

Rapid Development


Getting a web project off the ground can be cumbersome and technically demanding, especially when using older methods of development. Cake, however, makes the initial steps of building a web application easy. Rather than run installation scripts from the command line, Cake comes prepackaged as a folder you simply drop onto a server and is ready to run.

Model-View-Controller


Cake enforces an MVC structure for your web applications. Basically, it effectively separates typical operations into specific areas: models for all your database interaction, views for all your output and displays, and controllers for all your commands/scripts for input and program flow. The typical PHP application mixes each of these three functions in the same code, making it difficult to maintain and debug.

CRUD Operations and the Bake Script


Almost all web sites use CRUD operations: create, read, update, and delete. A blog, for example, will need to create posts; users will need to be able to read each post; the author will likely want the ability to edit the post in the future or update the post; and the author will also want access for deleting posts. Cake makes these operations a breeze with its automated CRUD functions. Instead of writing each CRUD operation by hand, it has prebuilt classes that do it for you. Cake includes the Bake script, a handy command-line tool that generates editable CRUD code based on your database schema and customized parameters.

Scaffolding


Getting a web site off the ground is much easier with Cake’s scaffolding abilities. With just one simple line of code, you can call out Cake’s prebuilt scaffold to render views based on the database. In other words, it figures out how some standard interface views should work with your database and outputs the HTML forms, all without you having to write one bit of HTML.

Helpers


Cake comes with standard HTML, Ajax, and JavaScript helpers that make creating views much easier.Your HTML output will be greatly facilitated by intuitive strings of helper code that render the markup for you. And getting Ajax to work, although a little tricky at first, is much easier and far more efficient than if you had to worry about DOM peculiarities.

Customizable Elements


You can customize each of Cake’s features to fit your application. For example, you can bring FCKeditor, the popular WYSIWYG editor for web browsers, into Cake as a plugin. Using customized helpers, you can bring all the functionality of FCKeditor into your Cake application and actually trim out extra lines of PHP code to get it working.

Large Community


Should you need help down the road, a massive online community exists to provide it. In reality, the PHP community is the largest open source programming group on the Web, so if you need a quick workaround for a problem in Cake, someone somewhere will have some help for you, usually within minutes. Cake specialists have also established online forums, chat rooms, and blogs to help others improve and learn the framework. Compared to other PHP frameworks, this community is one of the largest on the Web.
Code samples are a must for anyone getting involved in web development. PHP dominates this field, and Cake has a growing repository of code samples as well. If you are considering another framework, this fact just may tip the scales in favor of Cake if you are wanting to piggyback on someone else’s work.

More Features


Cake aims to simplify the development process for building web applications by providing an overall method for organizing the database and other resource files that cuts down on code. Although this general approach to web programming is itself a major feature Cake offers, its repository of other powerful resources such as built-in validation, access control lists (ACLs), data sanitization, security and session handling components, and view caching make Cake worth any serious developer’s time.

Jan 15, 2012

Google Maps Server Side Geocoding Using PHP and Infobox Fully AJAX

Recently I got a new project of real estate where I had to display about 1000 of projects on the google map. I was having the address of 1000 projects, so I started with my php and js code. When I coded and started testing, I found that on the map only 20-30 markers were shown. When I debugged I found an error of OVER_QUERY_LIMIT. I started googling and found that Geocoding has some limitations on converting address into lat long. In API there are two ways of getting LAT LONG.

  • Client Side

  • Server Side


Client side geocoding has some limitation of 20 queries per minute or sec. Server side geocoding also has limitations but after 2500 queries.

google-map

 

So in this tutorial we will first code our simple HTML then PHP and finally our AJAX.

HTML is pretty short and simple.

Filename: index.php

 
[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Google Server Side Geocoding Using PHP and Infobox Fully AJAX</title>

<style>
#wrapper{width:1002px; margin:0px auto;}
#loading {
position: relative;
text-align: center;
top: 45%;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r290/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://localhost:8080/gmap/google.js"></script>

</head>

<body>
<div id="wrapper">
<div id="googlemaps" style="width:500px; height:500px;position:relative;border:1px solid #888888;margin: 0 auto;">
</div>
</div>
</body>
</html>
[/html]
 

Here we are leaving a blank div, which will be filled with our google map.

In our PHP code, we can call the addresses either from database or an array. I am using array in this tutorial.

In server side geocoding we actually pass our address through an URL which returns a CSV or json formatted data.

Then we extract the lat long from this data using explode function and store it in an array. This array is passed to our AJAX function in json formatted.

Filename: gmap.php
 
[php]
<?php
$address = array(
"1" => array("Address" => "Bandra, Mumbai, India" , "Name" => "Bandra"),
"2" => array("Address" => "Khar, Mumbai, India" , "Name" => "Khar"),
"3" => array("Address" => "Santacruz, Mumbai, India" , "Name" => "Santacruz"),
"4" => array("Address" => "Andheri, Mumbai, India" , "Name" => "Andheri"),
"5" => array("Address" => "Jogeshwari, Mumbai, India" , "Name" => "Jogeshwari"),
"6" => array("Address" => "Goregaon, Mumbai, India" , "Name" => "Goregaon"),
"7" => array("Address" => "Malad, Mumbai, India" , "Name" => "Malad"),
"8" => array("Address" => "Kandivili, Mumbai, India" , "Name" => "Kandivili"),
"9" => array("Address" => "Borivali, Mumbai, India" , "Name" => "Borivali"),
"10" => array("Address" => "Dahisar, Mumbai, India" , "Name" => "Dahisar"),
"11" => array("Address" => "Mira Road, Mumbai, India" , "Name" => "Mira Road"),
"12" => array("Address" => "Bhayander, Mumbai, India" , "Name" => "Bhayander"),
"13" => array("Address" => "Naigaon, Mumbai, India" , "Name" => "Naigaon"),
"14" => array("Address" => "Vasai, Mumbai, India" , "Name" => "Vasai"),
"15" => array("Address" => "Nallasopara, Mumbai, India" , "Name" => "Nallasopara"),
"16" => array("Address" => "Virar, Mumbai, India" , "Name" => "Virar"),
"17" => array("Address" => "Churchgate, Mumbai, India" , "Name" => "Churchgate"),
"18" => array("Address" => "Charni Road, Mumbai, India" , "Name" => "Charni Road"),
"18" => array("Address" => "Grant Road, Mumbai, India" , "Name" => "Grant Road"),
"19" => array("Address" => "Dadar, Mumbai, India" , "Name" => "Dadar"),
"20" => array("Address" => "Mahim, Mumbai, India" , "Name" => "Mahim"),
"21" => array("Address" => "King Circle, Mumbai, India" , "Name" => "King Circle"),
"22" => array("Address" => "Worli, Mumbai, India" , "Name" => "Worli"),
);

foreach($address as $Idx => $key){
$addr = urlencode($key['Address']);
$url = 'http://maps.google.com/maps/geo?q='.$addr.'&output=csv&sensor=false';
$get = file_get_contents($url);
$records = explode(",",$get);
$lat = $records['2'];
$lng = $records['3'];

$data[] = array('Lat'=>$lat, 'Lng'=>$lng, 'Name'=>$key['Name']);

}
echo json_encode($data);
?>
[/php]
 

Now we call our ajax function on the load of the page.

Filename: google.js

 
[js]
jQuery(function($) {
$(document).ready(function() {
getAdress();//On page load initialize our map function.
});
});
[/js]
 

We will use infobox to create stylish markers and windows. When we load our function on page load, this function consists with an AJAX call, which gets the data from our gmap.php file, which will be in JSON formatted. We convert it into normal array using JSON.parse(). Finally we throw this array into foreach loop and store the lat, long values in a variable.

 

These lat long variables are also an array so one more for loop and then we pass it to our createmarker function which will be creating the markers on map.

Filename: google.js

 
[js]
function getAdress() {
jQuery(function($) {
$("#googlemaps").html('<div id="loading"><img src="loading.gif" /></div>');
$.ajax( {
url : "gmap.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var latitude = new Array();
var longitude = new Array();
var name = new Array();
var logo = new Array();
var i = 0;
var j = 0;
var k = 0;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
//Creating an array of latitude, logitude
if(x == 'Lat')
{
i = i + 1;
latitude[i] = y;
}
if(x == 'Lng')
{
j = j + 1;
longitude[j] = y;
}
if(x == 'Name')
{
k = k + 1;
name[k] = y;
}
});
});
$("#googlemaps").html('');
//passing the array to initialize function, where our map will be formed
initialize(latitude,longitude,name, logo);
}
});
});
}
function initialize(latitude,longitude, name, logo) {

//initialization of map.
var geocoder = new google.maps.Geocoder();
var initCenter = new google.maps.LatLng(19.0759837, 72.87765590000004);//By default Mumbai is loaded
var map = new google.maps.Map(document.getElementById('googlemaps'), {
zoom: 11,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

//initialization of infowindow
var infoWindow = new google.maps.InfoWindow;
var boxText = document.createElement("div");

var j = 1;
var image = new google.maps.MarkerImage('icon-home.gif');//Setting the marker image

//Infowindow is fully customizable, here we make our infowindow stylish by adding css styles to it.

var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 181
,zIndex: null
,boxStyle: {
background: "#000000"
,color: "#fff"
,width: "auto"
,padding: "10px"
,borderRadius: "20px"
,fontFamily: "Tahoma"
,opacity: "0.5"
}
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,closeBoxURL: ""
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);

//Final for loop for creating the markers
for(var a = 1; a < latitude.length; ++a)
{
createMarkers(geocoder, map, name[a], latitude[a], longitude[a], ib, image);
}
}


function createMarkers(geocoder, map, name, latitude, longitude, ib, image) {

//Setting the onclick marker function
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
ib.setContent(name);
ib.open(map, marker);
};

google.maps.event.addListener(map, 'click', function() {
ib.close();
});

//In array lat long is saved as an string, so need to convert it into int.
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);

var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});

//Adding the marker.
google.maps.event.addListener(marker, 'click', onMarkerClick);
}
[/js]
 

This above js file can be minified further, there are other ways of getting the data, but I found this very simple and easy. You can check the live demo. Any suggestions are welcome. Happy geocoding

Jan 9, 2012

Learn Codeigniter | Codeigniter Tutorial | Codeigniter Lessons | Part 1 | Webs Tutorial

What is CodeIgniter?

CodeIgniter is an open source PHP framework. This framework is used to build web applications and websites. CodeIgniter is best for developers who are into front-end development. It’s easy to learn and it’s fully flexibe.

To learn CI (CodeIgniter), you should know PHP, MYSQL, OOPs and MVC. If you are new to PHP and MYSQL, then I would recommend you to first learn it, you can learn from here.

What is MVC?

If you have selected to head start with CI, then you should know MVC.

MVC is nothing but a flow of code, it tells the framework which code to execute, at what time, and where to show the executed code. Normally when you create a simple php file which accesses the database, queries data and display it on index.php page, at that time all looks clear and simple. Now imagine you have a huge database, about 100+ SELECT queries, and suddenly your boss rings a bell and asks you that where is this query??? If at that time you would do CTRL+F and find that query statement, then you are really in a mess. MVC makes your job easy. MVC is a model, view and controller. When a request is triggered from client side using a view, that request reaches directly to the controller, controller decides whether it is a database request or simple HTML request. If it’s a database request then, it passes the essential code to model, a model handles all database calls and requests. Model interacts with database, gets the data and passes again to controller. Then controller passes the data to view and finally the flow ends. If the request was an html request, then controller directly passes the data to view.

It is simple, a view is war ground. A controller is the headquarters and a Model is an inventory base.

If I have confused you in understanding the flow of MVC, then you can refer this image.

MVC

Now let’s start the CI, first download the latest version of CI from here.

Before I start further, we need following things to begin.

  • Localhost server: I am using WAMP

  • Text Editor: I am using Eclipse


After download completes, you would be having a zip file, extract that into www folder, rename that folder to ci or your project name. Go inside system folder, cut application folder and paste it inside CI folder.

So your CI folder structure should be like this:

ci-folder-structure

Now in your browser run the following URL: http://localhost/ci/

It would display the default CI welcome page. If everything goes well till here, then you have successfully installed CI.

Let’s start first with a controller.

Create a new file inside controller folder, name it as home.php

MVC is made in OOPs, so we need to make a class inside our home.php file.

[php]
<?php

class home extends CI_Controller
{
function index(){
echo 'Welcome to CI Home';
}
}

?>
[/php]

Remember: Never echo anything inside our controller but as this is our first example so just to understand the MVC pattern we are doing it.

In the above function we made a class which extends the Controller class of CI. In CI the function named with index is loaded as default function. So when there are many functions inside a class, the function named as index loads the first.

Now just run this program: http://localhost:8080/ci/index.php/home

You can see your newly created controller.

Now suppose we had another function inside our controller, then how would we access it?

Just add one more parameter in URL after /home/

So let’s create one more function within our controller.

[php]
function another(){
echo 'Welcome to CI Home - This is another function within the same class of home controller';
}
[/php]

Access this function simply by adding the function name to the URL

http://localhost:8080/ci/index.php/home/another

When into some project we should never echo out any data or string from our controller, instead we should use controller to access the database through model or load some views, or in some case both.

At this part we have understood controller, now let’s understand a view.

In CI, many people say to follow naming conventions for naming the files. But you can name to view as per your choice.

Create a new file inside views folder. Name it home-view.php

home-view.php:

[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Welcome To Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Home View loaded successfully!!!</p>
</body>
</html>
[/html]

We will invoke the view through a controller.

Edit our home controller, delete our old functions and add a new index function.

In this example we are actually loading a view from a controller.

Home controller Index function:

[php]
function index()
{
$this->load->view('home-view');
}
[/php]

CI has libraries and classes which help us to write less and do more. The basic syntax to invoke a view is $this->load->view(‘Name of the view file’);

Run the code in browser and check it

URL http://localhost:8080/ci/index.php/home/

So now you are able to see the entire view.

Till now we just worked with Controller and a view. The only thing remaining is the model. But before we start with model let’s do some more within our controller and view.

Now we will pass some variables from controller to our view.

Within our index function, let’s create an array and store some values into it.

This array will be passed to our view.

[php]
function index()
{
$data['value1'] = 'My first Value';
$data['value2'] = 'My second Value';
$this->load->view('home-view', $data);
}
[/php]

In CI to pass some data to view, we simply add it as a second parameter in our load view line.

So in our view, we can directly access to value1 and value2 without getting into any loops

[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Welcome To Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Home View loaded successfully!!!s</p>

<?php
echo $value1 . '<br>';
echo $value2;
?>
</body>
</html>
[/html]

I explained this example instead of heading towards model, because it’s essential for you to understand how values are passed and how they are accessed in our view.

Here I end part 1 tutorial of CI, I recommend you to do some more examples within this tutorial so that in next part you would be use to CI. In our next tutorial we are going to understand the entire MVC which will interact with database. After understanding the basic use of CI, we will start making our first CMS or a website in CI framework which will have Insert, Update and Delete functionality.

Tips: In CI, if you want to make a controller function private, then just pre-pend _ before the function name.

[php]
function _anything()
{
$this->load->view('private-view', $data);
}
[/php]

Dec 19, 2011

How To Show Latest Tweets Using PHP JQuery

Today I am sharing my newly PHP and JQuery coded snippet which is going to display your latest tweets in a fade in and fade out effect using Twitter timeline RSS feeds.



Here is the PHP function to get the tweets:

 
[php]
<?php
function latest_tweets(){
//global $post;
$doc = new DOMDocument();
$meta='webstutorial';
$feed = "http://twitter.com/statuses/user_timeline/$meta.rss";
$doc->load($feed);

$outer = '<ul id="tweets">';
$max_tweets = 15;
$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
//if you want to remove the userid before the tweets then uncomment the next line.
//$tweet = substr($tweet, stripos($tweet, ':') + 1);
$tweet = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)@',
'<a href="$1">$1</a>', $tweet);
$tweet = preg_replace("/@([0-9a-zA-Z]+)/",
"<a href="http://twitter.com/$1">@$1</a>",
$tweet);

$outer .= "<li>". $tweet . "</li>n";


if($i++ >= $max_tweets) break;
}
$outer .= "</ul>n";
return "<div class='post'><p><b>Latest Tweets </b>".$outer."</div>";
}
echo latest_tweets();
?>
[/php]
 

In the above function we are fetching the RSS feed from the twitter timeline. Then we finally break it into segments and display it using the loop method.

Now we have to display the tweets with jquery effect.

So here is the jquery function to display the tweets in a fadeIn effect.

 
[js]
<script type="text/javascript">
function tweetRender( prospectID )
{
prospectID.delay() .fadeIn() .delay(2000).fadeOut(
function(){
if(prospectID.next().length > 0)
{tweetRender( prospectID.next() );}
else
{tweetRender( prospectID.siblings(':first'));}

}
);
}

$(function(){
$('#tweets li').hide();
tweetRender( $('#tweets li:first') );

});
</script>
[/js]
 

In this tutorial we are using basic PHP and JQuery to display the tweets. You can download it and check the Demo.

Dec 7, 2011

Learn PHP | PHP Tutorials | PHP Lessons | Part 2

So welcome back to part 2 of the PHP tutorial. If you are new to PHP then I would recommend you to first check the Part 1


Variables




  • Within this lesson you will learn how to assign values to variables in PHP and use them in some expression.

  • The topics covered are :



  1. Understanding Variables.

  2. Data Types.


Let’s get started right away…..


Understanding Variables




  • Variables

    • Variables are containers in which values can be stored and later retrieved.

    • They are basically the building blocks of any programming language.




For eg :- you can have a variable called “$number” that holds the value the value  “5



[php]$number = 5;[/php]

OR


$name that holds the value “bruce



[php]$name = "bruce";[/php]

Note :-        In PHP a variable will always be prefixed with a “$” symbol. If you can remember that declaring variable will be SUPER-EASY….




  • Just take “=” symbol with variable name on the left and value you want on right.


Here take a look at the example : -



[php]$name = "bruce";
echo "Hello";
echo $name;[/php]

 









Output produced is : Hello bruce.


  • Above example uses the “echo” command to display the value stored in a variable, in the same way that you would display a fixed piece of text.



  • The more descriptive your variable names are the more easily you will remember what they are used for, when you come back to a script several months later.



  •  Good variable name tells exactly what kind of value you can expect to find and stored in them.

  • Also, Variable name can only contain letters, numbers and underscore character. And each must begin with a letter or a underscore.

  • When the variable is assigned, the value given doesn’t have to be a fixed value


For eg :-



[php]$sum = 16 + 30;[/php]

-      ’16 + 30’ can also be an expression. An expression is where two or more values are combined using an operator to produce a result.


Let’s take a look at this …..



[php]$sum = 16 + 30;
echo $sum;[/php]

-      As seen above the values ‘16’ and ‘30’ are combined using the ‘+’ symbol & result is returned using “echo” command.




  •  Text Strings

    • Text Strings always have to be enclosed in quotation mark(“”) mark, and most of the time it doesn’t make any difference whether you use single(‘’) or double(“”) quotes.

    • But when you are dealing with variables it does make a difference.




Let’s look at an example to be clearer on this.



[php]$name = "bruce";
echo "Hello, $name";[/php]

  • Here the value of the variable is included in the string.








Output produced is : Hello, bruce.

Now look at this example below.



[php]$name = 'bruce';
echo 'Hello, $name';[/php]

  • Here no substitution of any variable takes place and output thrown is








Output produced is : Hello, $name.


  • You can overcome this by using ( ) OR { }



  • So if you want to display weight value with a suffix, your statement might look like this


[php]echo "The total weight is { $weight } lb";[/php]

  • If the braces hadn’t being placed around this particular weight variable , PHP would find a value which doesn’t exist. Like this


[php]echo  "The total weight is $weight lb";[/php]

  • Not to be too confusing but you can also do the same thing by using concatenation operator “.” to join two or more strings together as shown here


[php]echo 'The total weight is ' . $weight . 'lb' ;[/php]

-      The three values here are two fixed string and a variable.


-      If you assign a value to variable i.e $weight = 99 . The statement would produce output like this.









Output produced is : The total weight is 99lb.

Data Types




  • Each variable that holds certain value has a data type that defines what kind of a value it is holding.


























Data-type



Description


BooleanA truth value can be TRUE or FALSE
IntegerA number value, can be a positive / negative whole number
Double (or float)A floating point value can be any decimal number
StringAny alphanumeric value, any ASCII character.


  • When you assign a value to a variable the data type is also set.

  • PHP determine the data type automatically, based on value you assign to the variable.

  • If you need to check what data-type PHP thinks the value is you can use the gettype() function.


[php]$value = 7.2 ;
echo gettype($value);[/php]

  • Running this function, the data-type of a decimal number is double.

  • The complimentary function of gettype() is settype(), which lets you overwrite the data-type of a variable.


For eg:-



[php]$value = "22 January 2010";
settype( $value, "integer");
echo $value;[/php]

  • In this case the string begins with number, but the whole string is not an integer. The conversion converts the first non-numeric character and discards the rest and the output produced is just the number 22.


 









Output produced is : 22


  • Sometimes PHP will perform an implicit data-type conversion if values are expected to be of a particular type which is known as Type Juggling.


     For eg:-



[php]echo 100 + "10 inches" ;[/php]

-      The addition (+) operator expects to sit between two numbers. String type values are converted to double or integer in this case “10 inches” is treated is “10” before the addition operation is performed so the result is “110









Output produced is : 110


  • The same thing happens when a string operator is used on numeric data.

  • If you perform a string operation on numeric data-type, the numeric value is converted to a string first. We saw this earlier when we used the concatenation “.” operator to display a numeric value.

  • It is possible to use the value stored in a variable as the name of another variable.


-      Again, I know this might sound a bit confusing so let’s look at an example.



[php]$my_age = 21 ;
$varname = "my_age";
echo "the value of $varname is ${ $varname }";[/php]

-      The output produced in this example is









Output produced is : The value of my_age is 21

-      Because the string “my_age” is enclosed in a double quotes the dollar($) sign indicated that a variables value should become a part of string.


-      The construct shown i.e $ { $ varname } indicates that the value of variable should become a part of the string which is known as Variable Variables.


-      The braces around the variable $ { $ varname } is to indicate that it should be referenced first.


-      The next example shows the same output as the last one except that it uses the concatenation operator.



[php]echo 'The value of ’ . $varname . 'is' . $$varname;[/php]






Output produced is : The value of my_age is 21

So here we end our part 2 and I recommend you to go through the entire tutorial once again, and replicate all the examples in your localhost and test it if you are prepared for the 3 part.

download

Dec 4, 2011

Simple JQuery Toggle Tutorial | CSS JQuery Slide Toggle

Today I am going to share a very common and easy jquery tutorial with you. A JQuery Slide Toggle function.

.slideToggle() function is used to hide or show matched elements in a sliding effect.

So the basic syntax is

[js]$("div").slideToggle("slow");[/js]

So this was the basic syntax on how to slide toggle a div, now lets start with some real working examples.

So first the basic html code:



[html]
<div id="toggle">
<ul>
<li>Youtube Video Scraping</li>
<div>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="http://webstutorial.com/youtube-video-scraping-fetch-youtube-video-through-rss/programming/php">Continue reading</a>
</div>
<li>WordPress Multiple Category Search</li>
<div>
Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works. So finally decided to go more into...<a href="http://webstutorial.com/wordpress-multiple-category-search/content-management-system-cms/wordpress-cms">Continue reading</a>
</div>

<li>Youtube Video Scraping</li>
<div>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="http://webstutorial.com/youtube-video-scraping-fetch-youtube-video-through-rss/programming/php">Continue reading</a>
</div>

<li>Ten WordPress Useful Functions And Snippets</li>
<div>
Some useful WordPress PHP funtions. Just copy and paste these functions in your themes functions.php file Change the WP Login Logo & URL Link Load JQuery From Google CDN How to remove the WordPress Version Information Remove Default WordPress Meta...<a href="http://webstutorial.com/ten-wordpress-useful-functions/content-management-system-cms/wordpress-cms">Continue reading</a>
</div>

<li>A Good PHP Developer Can Answer This | PHP Test</li>
<div>
PHP developers go through 3 stages in their life Beginner Good Best A beginner PHP coder is some one who just started making some PHP projects in CMS like WordPress, Joomla, Magento and other PHP based CMS. A good PHP... <a href="http://webstutorial.com/good-php-developer-answer-php-test/programming/php">Continue reading</a>
</div>

</ul>
</div>
[/html]


And finally our js


[js]
<script type="text/javascript">
$(document).ready(function() {
$("li").click(function(){
$(this).toggleClass("active");
$(this).next("div").stop('true','true').slideToggle("slow");
});
});
</script>
[/js]

Explanation:

In our basic html layout, we have placed a div exactly next to our li. So we tell the jquery to slide exactly the next div of the current clicked li. If we directly write slideToggle then it will slide all the div's of the current page. In the above js code, we are also using a stop() function. This is essential to use, to avoid multiple clicks on a same li making it to slide for continuous multiple times of sliding.

Here's a working demo of the above code

Nov 27, 2011

Youtube Video Scraping | Fetch Youtube Video Via RSS

Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape youtube videos through GDATA RSS.



[php]
<?php
$search = 'linkinpark';//Search Term
$file = file_get_contents('http://gdata.youtube.com/feeds/base/videos?q='.$search.'&client=ytapi-youtube-search&v=2');
$rss = new SimpleXMLElement($file);
$limit = '10'; //Videos Limit to display
$ctr = '0';
foreach($rss->entry as $idx => $key)
{
if($ctr == $limit)
{
break;
}
else{
echo '<div id="video">';
echo '<p class="title">'.$key->title.'</p>';
echo '<p class="video">'.$key->content.'</p>';
echo '</div>';
$ctr++;
}
}
?>
[/php]


My idea behind getting the videos is first to fetch the entire contents of the GDATA RSS page using file_get_contents

After storing the RSS into a file as a string, we will convert it into proper XML using SimpleXMLElement

We store this XML version into a variable which consists of arrays and objects.

Finally we bring the foreach and break down the array into pieces. Thats it. Go and test it yourself.

This function is the basic version, I am sure you can modify it and make more flexible.


download

Oct 29, 2011

A Good PHP Developer Can Answer This | PHP Test

PHP developers go through 3 stages in their life

  • Beginner

  • Good

  • Best


A beginner PHP coder is some one who just started making some PHP projects in CMS like Wordpress, Joomla, Magento and other PHP based CMS.

A good PHP coder completed or knows all PHP based CMS and is about to finish PHP Frameworks like Yii, Cake, Symphony, CI and others.

A best PHP coder is a complete package of Beginner and Good, that person needs no questions cause he might be ready with all the answers.

Now its time to rate yourself in PHP, I googled and found some questions which only a Good coder can answer.

Q1: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon ::). This is valid for PHP 4 and later only.

Q2: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Reason: body data was sent, causing headers to be sent too. This normally occurs when white space is sent accidentally.

Q3: What's wrong in this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: This is the worst practice to select some row or fetch data, use specific row instead of *. Use PDO prepared statements to avoid SQL Injections.

Q4: What is wrong with this if statement: if( !strpos( $thread, $needle ) ...?
A: strpos returns the index position of needle, it could return false if its at 0 position. Instead give a if else check if( false !== strpos( $thread, $needle )...

Q5: What is the preferred way to write this if statement, and why?
if( 5 == $someVar )
or if( $someVar == 5 )
A: The former, it prevents accidental assignments of 5 to $somevar if you forgot two == signs(if( $someVar = 5 ))

Q6: In the below code, whats the value of $a and $b after the function call and why?

[php]
function doSomething( &$arg )
{
$return = $arg;
$arg += 1;
return $return;
}

$a = 3;
$b = doSomething( $a );
[/php]

A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.

Q7: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Q8: What is wrong with this code:

[php]
class SomeClass
{
protected $_someMember;

public function __construct()
{
$this->_someMember = 1;
}

public static function getSomethingStatic()
{
return $this->_someMember * 5; // here's the catch
}
}

[/php]

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Q9: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Q10: Which one is correct?: $array[name] or $array['name']?
A: Both of them will output the value, but only the quoted form is correct. To check this define(name,0); and see the bugs flying in the website.

Now how much did you score out of 10, comment your score below, and if you have any more questions then let me know after all sharing is caring ;)

Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif


Now we will add basic html code into our index.php file

[html]

<body>
<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>
</div>

</body>

[/html]

Now comes the main AJAX code.

Inside your head tag, add the following code:

[html]

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
{
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
{
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
return;
}
else{
$('#name').removeClass('error');
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

$.ajax({
url : 'data.php', //Declaration of file, in which we will send the data
data:{
"name" : term_name                //we are passing the name value in URL
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);
}
});
}
}

</script>

[/html]

Explanation:

In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code

[php]

<?php
$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
{
echo '<tr><td>'.$row['Name'].'</td></tr>';
}
}

mysql_close($con);
?>

[/php]

Conclusion:
Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:


download


download

Oct 21, 2011

PHP Multidimensional Array Shuffle | Shuffle Array In PHP

Multi-Dimensional array is an array within array. It is the most common used php function to store multiple values within a variable.

Here is my small snippet share for shuffling multidimentional array values.

Just call this function and pass the multidimensional array through parameters.


[php]public static function shuffle_array($array)
if (!is_array($array)) return $array;
$keys = array_keys($array);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$shuffle[] = $array[$key];
}
return $shuffle;
}
[/php]

Aug 22, 2011

How To Make A Shoutbox Using PHP & MYSQL | Create A Shout Box Using PHP MYSQL | Make A Simple Shout Box

First of all, let me explain you what is a shoutbox.

A Shoutbox is nothing but a chat program, where anyone can chat with any anonymous user.
You can read more about shoutbox at this link : http://en.wikipedia.org/wiki/Shoutbox

So lets make a shoutbox.

We will make this shoutbox in basic php and mysql.

First you need to make a database where you will store this chats, so from phpmyadmin you can create a databse.
Next we will add a table, so in sql query window, just paste the below code:

[php]
CREATE TABLE `shoutbox` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(60) NOT NULL,
`post` TEXT NOT NULL,
`ipaddress` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
);
[/php]

PhpMyAdmin

Here we made a table with name, email, id and ipaddress fields, where all values is must, id is set to auto increement and we are using IP address to track the user.

Next we will create a file named as db.php, where we make our MYSQL Connection, so just paste the below code in your file db.php

[php][/php]


<?php
$host = 'localhost'; //Normally localhost
$username = 'root'; //Username which is added to your database, root is default
$password = ''; //Password for your user, for root password is null
$database = 'shoutbox'; //your database name
?>

[php][/php]

Now we will create our actual shoutbox code file, make a file and name it to index.php, and add following code in it

[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shoutbox From WebsTutorial</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">

<h1>Shoutbox</h1>
<h5><a href="http://www.webstutorial.com" title="WebsTutorial">WebsTutorial</a></h5>

<div id="boxtop"></div>
<div id="content">

<?php
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
include ('db.php'); // for db details

// defines a $connect variable, which when used
// will attempt to connect to the databse using
// details provided in config.php
// if it fails, will display error - or die();
$connect = mysql_connect($host,$username,$password) or die('<p>Unable to connect to the database server at this time.</p>');

// connect to database using details provided
// and uses the $connect variable above
// if it fails, will return error - or die();
mysql_select_db($database,$connect) or die('<p>Unable to connect to the database at this time.</p>');

// checks the POST to see if something has been submitted
if(isset($_POST['send'])) {
// are any of the fields empty? the || means 'or'
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {
echo('<p>You did not fill in a required field.</p>');
} else {

// if there are no empty fields, insert into the database:

// escape special characters to stop xss and sql injecting
// we take the 'name' and 'post' parts from the POST
// and run it through htmlspecialchars()
// this stops users sending HTML code, as it could be malicious
//
// also runs through mysql_real_escape_string()
// stops users sending SQL code, which could be used to access the db
$name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
$email = htmlspecialchars(mysql_real_escape_string($_POST['email']));
$post = htmlspecialchars(mysql_real_escape_string($_POST['post']));

// this is our SQL string to insert shouts into db
$sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";

// we run the SQL string now
// if it succeeds, display message
if (@mysql_query($sql)) {
echo('<p>Thanks for shouting!</p>');
} else {
// if it errors, send message
echo('<p>There was an unexpected error when posting your shout.</p>');
}
}
}

// now we retrieve the 8 latest shouts from the db
$query = "SELECT * FROM shouts ORDER BY `id` DESC LIMIT 8;";

// run the query. if it fails, display error
$result = @mysql_query("$query") or die('<p>There was an unexpected error grabbing shouts from the database.</p>');

?><ul><?php
// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {

$ename = stripslashes($row['name']);
$eemail = stripslashes($row['email']);
$epost = stripslashes($row['post']);

// Woop! We can use Gravatars aswell!!
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

echo('<li><div><p>'.$ename.'</p><img src="'.$grav_url.'" alt="Gravatar" /></div><div><p style="padding:20px 0 0 0;">'.$epost.'</p></div></li>');

}
?></ul>

<!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post">
<h2>Shout!</h2>
<div><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>

</div><!--/content-->
<div id="boxbot"></div>

</div><!--/container-->

</body>
</html>
[/html]

Explanation:
OK, in this file first we get the IP address of the person and open the db connection by including our first created db.php file.

Then we pass a check condition to check the emptiness in the textboxes. And we also store the values in respective variables, here while storing them we are using php functions htmlspecialchars, to avoid html characters and mysql_real_escape_string to avoid sql statements, this two are very important in terms of security else anyone will pass html and sql codes and pamper the database or server.

After storing them, we finally code the insert query and echoes a custom message of successful execution.

Wait a minute, this is not the end, now we will also have to display the recently 8 shouts, so we fire a select query and  store the array in a variable.

And finally in a while loop we echo the email, name and the shout message.

Woila, done, but arghhhhhhhhhhh without CSS, its like image without color, so make a file style.css and add the following css code in it.

[css]
/* Shoutbox PHP tutorial from WebsTutorial */

* {
margin: 0;
padding: 0;
}

body {
background: #323f66 top center url("images/back.png") no-repeat;
color: #ffffff;
font-family: Helvetica, Arial, Verdana, sans-serif;
}

h1 {
font-size: 3.5em;
letter-spacing: -1px;
background: url("images/shoutbox.png") no-repeat;
width: 303px;
margin: 0 auto;
text-indent: -9999em;
color: #33ccff;
}

h2 {
font-size: 2em;
letter-spacing: -1px;
background: url("images/shout.png") no-repeat;
width: 119px;
text-indent: -9999em;
color: #33ccff;
clear: both;
margin: 15px 0;
}

h5 a:link, h5 a:visited {
color: #ffffff;
text-decoration: none;
}

h5 a:hover, h5 a:active, h5 a:focus {
border-bottom: 1px solid #fff;
}

p {
font-size: 0.9em;
line-height: 1.3em;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
}

p.error {
background-color: #603131;
border: 1px solid #5c2d2d;
width: 260px;
padding: 10px;
margin-bottom: 15px;
}

p.success {
background-color: #313d60;
border: 1px solid #2d395c;
width: 260px;
padding: 10px;
margin-bottom: 15px;
}

#container {
width: 664px;
margin: 20px auto;
text-align: center;
}

#boxtop {
margin: 30px auto 0px;
background: url("images/top.png") no-repeat;
width: 663px;
height: 23px;
}

#boxbot {
margin: 0px auto 30px;
background: url("images/bot.png") no-repeat;
width: 664px;
height: 25px;
}

#content {
margin: 0 auto;
width: 664px;
text-align: left;
background: url("images/bg.png") repeat-y;
padding: 15px 35px;
}

#content ul {
margin-left: 0;
margin-bottom: 15px;
}

#content ul li {
list-style: none;
clear: both;
padding-top: 30px;
}

#content ul li:first-child {
padding-top:0;
}

.meta {
width: 85px;
text-align: left;
float: left;
min-height: 110px;
font-weight: bold;
}

.meta img {
padding: 5px;
background-color: #313d60;
}

.meta p {
font-size: 0.8em;
}

.shout {
width: 500px;
float: left;
margin-left: 15px;
min-height: 110px;
padding-top: 5px;
}

form {
clear: both;
margin-top: 135px !important;
}

.fname, .femail {
width: 222px;
float: left;
}

form p {
font-weight: bold;
margin-bottom: 3px;
}

form textarea {
width: 365px;
overflow: hidden; /* removes vertical scrollbar in IE */
}

form input, form textarea {
background-color: #313d60;
border: 1px solid #2d395c;
color: #ffffff;
padding: 5px;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
margin-bottom: 10px;
}

ul li{
border: 1px solid #2A3556;
float: left;
margin-right: 10px;
padding: 10px;
position: relative;
right: 12px;
margin-bottom:5px;
}
[/css]

This was your last step by styling the shoutbox.
Feel free to ask any questions if you didn't understand any point or if I missed something

Final Layout:

WebsTutorial Shoutbox

download

Aug 7, 2011

How To Stop SQL Injections in PHP | Best Way To Stop MYSQL Injections

Now a days hacking has became a hobby for young generations, people start hacking and destroy the websites just for the sake of fun or business, amongst all of them SQL injections also known as DdoS is becoming very famous. But what is SQL injections? Suppose you have a website or a forum where a user can find something for him/her. That person searches the keyword by using Search option, this is where SQL injections start, a normal search is ok, say about a server can handle couple of searches at a time, but what if same website opened in 100 windows and at the same time 100 searches or more then that are made, then your server will go down and hackers can easily break the firewall and hack your website data from the server.

This is very common now a days, so to get rid of this the php code of search should be changed.

Default Search Code:

[php]
// connect to the mysql database

$unsafe_var = $_POST["keyword"];

mysql_query("SELECT * FROM table1 where keyword='". <code>$unsafe_var</code> ."'");

// disconnect from the mysql database
[/php]

The best way is to use prepared statements
Something Like this

[php]
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');

$preparedStatement->execute(array(':name' => $name));

$rows = $preparedStatement->fetchAll();

[/php]

This is the best way to get rid of SQL Injections.
In the above SQL statements you pass to prepare is parsed and compiled by the database server. By specifying parameters (:name) we are telling the database engine where the filter should be on. Then when we call execute the prepared statement is combined with the parameter values we specify.

Simple and secure

So always use safe coding, after all coding is fun not destruction.

Happy Coding :)

Aug 2, 2011

Learn PHP | PHP Tutorials | PHP Lessons | Part 1

Learn PHP – Tutorial

(Part 1) Lesson -1

In this lesson we will focus on the following topics:-

  1.   PHP Basics

  2.   Server Side Scripting

  3.   PHP tags

  4.   The “echo ” command

  5.   Creating your first script


Let’s get started right away.

PHP Basics:

What is PHP ?

  • PHP is PHP:Hypertext  Preprocessor.

  • It is a programming language that is specially designed for creating Dynamic websites.

  • PHP language is flexible, making it easy to learn even if you have not done any programming in the past.


For example you could use PHP to show the current date and time on top of each page on your website.

[php]

Today’s date and time

The date is <!--?php  echo date(‘j F Y’); ?-->
and the time is <!--?php echo date(‘H:i:s’); ?-->

[/php]

  • Also it can easily process data submitted in HTML form and talk to various database systems( like SQL, MySQL, ..etc.) allowing generation of webpage based on SQL query.


 

Server Side Scripting:

  •         The most important concept to learn when starting out with PHP is where exactly it fits in a web environment. When you understand this, you will understand what PHP can and cannot do.



  •         A PHP module attached to your web server is telling the server that files with a particular extension (i.e. time.php) should be examined for PHP code. It processes instructions sent in a webpage by the client machine i.e. any PHP code found in the page is executed, thereby code is replaced by the output before it is sent back to the client’s web browser.  For eg. time.php file. The file contains basic HTML code along with PHP to display the current date and time. Here the PHP module in the server searches the file for the PHP code and replaces the code with the output. The following output is shown on the screen.


Output:-

The date is 1 August 2011 and the time is 14:29:54

  •          Once the page is downloaded, PHP plays no further part until another web page is requested by the client’s web browser.



  •          One thing PHP is not capable of doing is Client-Side-Validation. Now you’ll wonder what is Client-Side-Validation ?.


Consider a form(form.php) where you have to fill in all your details like Name, Address, Zip-code etc.

Client-Side-Validation checks value entered in a particular field like “Name:-..” meets certain criteria before moving to the next field i.e. in simple words you cannot enter your “Zip-code” in the area where you have to enter your “Name:-..” .

So to check the value entered is proper and valid is Client-Side-Validation. Client-Side-Validation can be achieved when PHP works with JavaScript.

  •          The beauty of PHP is that it doesn’t rely on the web browser at all. Your script will run the same no matter what browser you use. There is no need to worry about enabling JavaScript on your browser.


 

PHP tags:

Today is <?php echo date (‘j F Y’); ?>

  •          Above code is from a PHP driven web page that displays the current date

  •          The tag “<?php ”  tells that everything that follows is program code rather than HTML until the closing tag “?>”

  •          The “echo” command tells PHP to display the very next item on the screen. “echo” is used for printing output on the screen, “echo” is similar to “print” statement.

  •          The “date(‘j F Y’);” produces the formatted version of date, containing the day as “j” month as “F” and “Y” as the year.



  •           Also note that anything that appears outside the PHP tag will be displayed on the screen. As seen in the above line of code where “Today is:” which is outside the PHP tag is displayed on the output screen just before the generated date.


Note:-  In this tutorial PHP code appears inside tags that look like this “<?php ”

            and “?>”. Other tag styles can be used such as

“<%” – Asp tag style..

“<script language = “PHP”>” – the script tag.

The “echo ” command:

  • The “echo” command is used to sent output to the browser


For example:-

[php]
<?php /* php code to display date
and time */
echo “The time is ”;       / use of double quotes /
echo date(‘H:i:s’);
echo ‘and the date is ’      / use of single quotes /
echo date(‘j F Y’);
?>[/php]

  • You can either use the double quotes (“”) or single quotes (‘’) to display string.



  • You can even add “comments” to your code.


“Comment” – It is basically a piece of free text that can be shown an where in the script and is completely ignored by PHP.

Different “comment” styles supported by PHP are :-

1.      Single line comment (i.e. “/……/” or  “#” )

2.      Multi-line comment  (i.e. “/*………….*/”).

 Creating your first script:

  • In order to create and run your PHP scripts you will have to install PHP, MySQL, Apache.If you do not have PHP and other stuffs installed follow this link here which has a complete package of all the software’s you need.


http://www.wampserver.com/en/download.php

Note:- WAMP is Windows Apache MySQL PHP. Where the initial “W” determinesthe platform compatibility. Similarly there are LAMP, MAMP , and XAMPP.

“X” is compatible on all platforms i.e. LINUX, MAC, WINDOWS.I assume that most of them are using WINDOWS platform here.

The installation includes :-

- Apache 2.2.17

 - Php 5.3.3

 - Mysql 5.1.53 (version 64 bits)

 - Mysql 5.5.8 (version 32 bits)

 - PhpMyadmin 3.2.0.1

 - SQLBuddy 1.3.2

  • After installing WAMP, a new directory will be created in your “C:” drive which will contain a folder “www


Note:- when ever you create a PHP file you should save it in c:wampwww”.


  • To run any PHP file first start the “WAMP” server by double clicking on  the icon created on your desktop.



  • After the server is online i.e. “ON” next thing to do is to open your web browser and type in


http://localhost/time.php

Alright we have now completed Lesson 1 (Part 1).Hope you like this tutorial. You have now learnt how  PHP works on a web environment and what a simple PHP script looks like. We will discuss about variables in the next Lesson. You can download the files for practice that I have included in the Download.

PHP Tutorial Part 2


download

Jul 12, 2011

How to display errors while the display_errors is off in the php.ini file

Display_error feature is turned off or disabled mainly by your web hosting ISP or provider from the php.ini file. I hope this small tutorial will be of great help to display your php errors.

php.ini file will contain code some what like this

[php]
; display_errors = Off [Security]
; With this directive set to off, errors that occur during the execution of
; scripts will no longer be displayed as a part of the script output, and thus,
; will no longer be exposed to remote users. With some errors, the error message
; content may expose information about your script, web server, or database
; server that may be exploitable for hacking. Production sites should have this
; directive set to off.

; Print out errors (as a part of the output). For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below). Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On
[/php]

Considering some security issues display_errors is usually disabled  by many web hosting companies in order to protect your website from any harm. One way to display errors while the display_errors is off in the php.ini file, is to add these functions at the beginning of your script files .

Just copy and paste this code at the beginning of your script files.

[php]
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
[/php]

And thats it you can now display errors.

Jul 10, 2011

Best way to include JQuery | Correct way to include JQuery

JQuery is the javascript library, but just copy pasting the JQuery snippet will not do, it will start conflicting with other JQeries, so the best practice is to use the following method

[php]<?php wp_enqueue_script("jquery"); ?>[/php]

Browser Caching with .htaccess

Is your site very slow, then why not you use caching? just copy the below snippet to your .htaccess file

[php]## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
## EXPIRES CACHING ##[/php]

Top 10 PHP snippets

Simple page caching using PHP


Implementing page cache on a website is the best thing to speed up the site. Using this function will help getting the page cache work.
[php]
<?php
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) &amp;&amp; time() - $cachetime <filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
<html>
output all your html here.
</html>
<?php
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>[/php]



How to Calculate distance measurement in PHP


This Function will calculate distance from one point to another using longitudes and latitudes. This function returns the output in miles, kilometers, or nautical miles.

[php]function distance($lat1, $lon1, $lat2, $lon2, $unit) {

$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);

if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}[/php]
Usage:
[php]echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";[/php]


Conversion of  seconds into time (years, months, days, hours…)


Following function will convert seconds into years, months, days, hours.
[php]function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" =>0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}[/php]


Force a file to download


Use PHP to force a file to download.
Use the following function for that.
[php]function downloadFile($file){
$file_name = $file;
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($file_name); // push it out
exit();
}[/php]


Using Google API, get whether stats.



Get the current whether information of your city or any other, using Google API. In the code below, edit the line 1 code, and replace address with your desire location.
[php]$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS');
$information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition");
echo $information[0]->attributes();[/php]


Create a basic PHP WHOIS



WHOIS service is used to get the details of a domain name, domain owner, creation date, registrar etc. WIth the help of PHP and whois unix, it is extremely easy to get the function working.
REMEMBER:the WHOIS unix command must be installed on your website server for getting this code to work.
[php]$domains = array('home.pl', 'w3c.org');

function creation_date($domain) {
$lines = explode("\n", `whois $domain`);
foreach($lines as $line) {
if(strpos(strtolower($line), 'created') !== false) {
return $line;
}
}

return false;
}

foreach($domains as $d) {
echo creation_date($d) . "\n";
}[/php]



Again using Google API to get the longitude and latitude of an area.



Just follow the below function for getting the Latitude and longitude.
[php]function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&amp;q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') >1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}[/php]


Get the favicon of a domain by using simple PHP and Google



[php]function get_favicon($url){
$url = str_replace("http://",'',$url);
return "http://www.google.com/s2/favicons?domain=".$url;
}[/php]


How to Calculate Paypal fees?



Want to calculate your paypal fees? then use the below function
[php]function paypalFees($sub_total, $round_fee) {

// Set Fee Rate Variables
$fee_percent = '3.4'; // Paypal's percentage rate per transaction (3.4% in UK)
$fee_cash = '0.20'; // Paypal's set cash amount per transaction (£0.20 in UK)

// Calculate Fees
$paypal_fee = ((($sub_total / 100) * $fee_percent) + $fee_cash);

if ($round_fee == true) {
$paypal_fee = ceil($paypal_fee);
}

// Calculate Grand Total
$grand_total = ($sub_total + $paypal_fee);

// Tidy Up Numbers
$sub_total = number_format($sub_total, 2, '.', ',');
$paypal_fee = number_format($paypal_fee, 2, '.', ',');
$grand_total = number_format($grand_total, 2, '.', ',');

// Return Array
return array('grand_total'=>$grand_total, 'paypal_fee'=>$paypal_fee, 'sub_total'=>$sub_total);
}
<?php
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) &amp;&amp; time() - $cachetime <filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
<html>
output all your html here.
</html>
<?php
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>[/php]

Jul 7, 2011

How To Add Simple Pagination To WordPress

Many sites uses pagination to navigate to the older posts. If you install twenty ten or twenty eleven default wp theme, then you will notice that instead of pagination, it gives you old fashion links.
So to have pagination write the below function to your functions.php file

 

[php]function paginate() {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

$pagination = array(
'base' => @add_query_arg('page','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' =>true,
'type' =>'list',
'next_text' => '»',
'prev_text' =>'«'
);

if( $wp_rewrite->sing_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );

echo paginate_links( $pagination );
}[/php]

After some PHP code, we will need to add some CSS styling, so it gets the looks of actual pagination.
So add the following CSS code to your style.css file

 

[php]/* Pagination */

ul.page-numbers {
margin: 20px 0 10px;
width: 100%;
padding: 0;
font-size: 12px;
line-height: normal;
clear: both;
float: left;
}

ul.page-numbers li {
float: left;
}

ul.page-numbers a,
ul.page-numbers span {
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
background: -webkit-gradient(linear, left top, left bottom, from(#E4E3E3), to(#FFFFFF));
background: -moz-linear-gradient(top, #E4E3E3, #FFFFFF);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E4E3E3', endColorstr='#FFFFFF');
padding: 3px 4px 2px 4px;
margin: 2px;
text-decoration: none;
border: 1px solid #ccc;
color: #666;
}

ul.page-numbers a:hover,
ul.page-numbers span.current {
border: 1px solid #666;
color: #444;
}[/php]

The above CSS is really simple, if you want to make your pagination to match your theme, then simply edit the CSS. Its damn Simple.
To include the pagination, we need to call the function.
So if you are going to display the pagination on the home dynamic page, then goto index.php file, and replace the below function with your old boring pagination.

[php]
<?php paginate(); ?>
[/php]

To know more about paginate_links()
Refer the Codex: http://codex.wordpress.org/Function_Reference/paginate_links