Aug 12, 2010

PHP - verify if a class is defined

PHP has the class_exists() function to check if a class has already been defined. You may need to take action depending if a class exists or not, and need to watch out for "gotchas" when also using__autoload().

Basic Usage

This is how it works:
if(class_exists('foo')) {
  ... do something ...
}
else {
  ... do something else ...
}
Or if you only want to test if the class doesn't exist, then just do this:
if(!class_exists('foo')) {
  ... do something ...
}
You can actually declare a class within those curly braces like this:
if(!class_exists('foo')) {
  class foo {
    function bar() {
      echo 'foo';
    }
  }
}
But you might instead include a file with the class definition etc or take some other action required if the class does not exist.

__autoload gotcha

PHP 5 introduced the __autoload() magic function (which I have written about already) and added a second parameter to the class_exists() function which is whether or not to call the __autoload function when checking to see if the class exists. The default is true, which maintains backward compatibility.
The reason I've called this a "gotcha" is it "got me" just yesterday when I was using the class_exists function inside __autoload and it was causing errors because the naming of the particular class didn't match what my __autoload was trying to do.
It took me a while to work out what the problem was but it was actually quite fortunate the class and file trying to autoload didn't match my naming convention becuase it alerted me to the issue and also would have meant it was loading an uncessary class file.
If you don't want autoload to automatically load the class file when using class_exists, pass false as the second parameter like so:
if(class_exists('foo', false)) {
  ... do something ...
}

Aug 11, 2010

Tutorial WEBservice in PHP

In the last 2 weeks I have searched the simpliest and complete tutorial about webservices in PHP. I have founded followings:


One of the Internet's current hot topics is Web Services, introduced by Kevin Yank in his article Web Services Demystified.
If you've been following industry news on the subject, you may think this is some high level technology, of interest only to big companies with huge budgets. But if you did, you'd be wrong.
The concepts behind Web Services are remarkably simple, and in this article we'll be taking a deeper look at what's involved. Then, with a little help from our good friend PHP, we'll set up our first Web Service.
We will assume some knowledge of PHP, MySQL and XML, which -- if you're uncertain of -- you can quickly pick up from Building your own Database Driven Website using PHP & MySQLand XML - An Introduction.
So here's what's on the menu:
The Basics of Web Services: To start with we'll be quickly reviewing the basic concepts behind Web Services.
Introducing XML-RPC: Next, we'll introduce you to an XML standard for the exchange of data between systems, and we'll put it into context with Kevin's article.
PHP XML-RPC Implementations: Then we'll review some of the Open Source implementations of XML-RPC in PHP: code you can use to quickly build your own Web Service, or access other Web Services from your site.
Your first Web Service: If you want to get straight down to business, this is the place to be. Here, we'll take one of the implementations described previously, and build a Web Service for it in PHP.
What you can do with XML-RPC: Wondering what to do next? We'll give you some ideas for what you could do with XML-RPC and Web Services.
Let's get started!
The Basics of Web Services
The first thing to understand about Web Services is they're not really anything new. If you've ever used an RSS Feed to take news from another Website and place it on your own, you've already got a good idea of how Web Services work (see Kevin Yank's article: PHP and XML: Parsing RSS 1.0).
Web Services are about exchanging data between a server and a client, using a standard XML format to "package" requests and data so that both systems can "understand" each other. The server and the client could both be Web servers, or any other electronic device you care to think of.
Network-wise, data exchange in a Web Service typically happens via TCP port 80, using standard HTTP protocol POSTs. Put another way, Web Services operate in basically the same way your browser does when it POSTs an HTML form to a site, and receives a Web page in response. The only real difference is that, instead of HTML, Web Services use XML. And this means Web Services can be available anywhere on the Internet, passing through firewalls the same way viewing a Web page does. The data exchange happens at the packaging layer.
On top of the data exchange, you also need information that describes the interface (or Application Program Interface - API) to the service. This makes the Web Service useful to the rest of the Internet, allowing other developers to develop programs that can access your Web Service. This is called the description layer, and the WSDL (Web Service Description Language) standard that will make this happen is under development.
Above that, there's information that describes the nature of the service itself (not unlike the HTML-descriptive META tags), so that it can be categorised and found on sites that offer Web Service directories. This is the discovery layer, which is currently being addressed by the UDDI (Universal Description, Discovery and Integration) standard.
Both the description and discovery layers are simply XML, governed by a particular format that enables relevant information to be found for all Web Services on the Internet.
Perhaps what's made Web Services a hot topic recently -- aside from marketing by the likes of Microsoft and IBM -- is the development of these standards. They'll allow Web Services to be rolled out en masse across the Internet, backed by development tools that'll make access to them both predictable and easy.
But it should be remembered that everything a Web Service does now, in terms of data exchange, could also have been done 5 or even 10 years ago using the HTTP standard and whichever XML format you chose to use or invent (RSS feeds being a prime example). The "hot news" today is that building and distributing a Web Service is now a lot easier than in the past.
Anyway, if you're looking for a hype-free news source for the technological development in Web Services, try XML Hack.
We'll skip further generalities, but suffice it to say that this article focuses on the packaging layer, i.e. how you build and access a Web Service.

Aug 4, 2010

MySQL Database and PHP

MySQL Database and PHP


Almost all websites have content which is dynamic. I mean content is into database and PHP extract content from there.
The most used database on the internet is MySQL. Mysql is free and is the quickiest database on the web.

You can download Mysql Database from mysql.com


Mysql and PHP for beginners
This article assumes a few things.

You know how to use PHP. If you don't, the best place to start is by reading Welcome to PHP
You know how to run basic queries in a database. If you don't, I suggest you visit Getting started with SQL or parts 1 and 2 of Introduction to Databases for the Web
You have access to a server (or servers) running PHP and MySQL. If yuo don't, you can get hold of the software, for free, along with installation instructions at the PHP site and the MySQL site.
The server running PHP can connect to the server running MySQL. Test this from the command line first. If you can't connect without PHP, you're not going to be able to connect with PHP. If you're using other servers, you may need to ask the systems administrator for help
There's an existing database and table already running on MySQL, which we'll use with the PHP scripts. The database is called first_test, and has a table called people with some data in it. Run the following SQL to create and populate the table:
mysql> CREATE DATABASE first_test;
Query OK, 1 row affected (0.31 sec)
mysql> USE first_test;
Database changed
mysql> CREATE TABLE people (
id int UNIQUE NOT NULL,
first_name varchar(40),
surname varchar(50),
PRIMARY KEY(id)
);
Query OK, 0 rows affected (0.24 sec)
mysql> INSERT INTO people VALUES(1,'Ann','Brache');
Query OK, 1 row affected (0.09 sec)
mysql> INSERT INTO people VALUES(2,'Narcizo','Levy');
Query OK, 1 row affected (0.02 sec)
mysql> INSERT INTO people VALUES(3,'Tony','Crocker');
Query OK, 1 row affected (0.00 sec)
Your table should now look as follows:


mysql> SELECT * FROM people;
+----+------------+---------+
| id | first_name | surname |
+----+------------+---------+
| 1 | Ann | Brache |
| 2 | Narcizo | Levy |
| 3 | Tony | Crocker |
+----+------------+---------+
3 rows in set (0.19 sec)
Connecting

There are many MySQL functions in PHP. Perhaps you've taken a look at the official documentation and been intimidated by what looks like an endless task. But the good news is that to perform basic queries from within MySQL is very easy. This article will show you how to get up and running. Once you're comfortable with the basics, you can start to investigate the other functions, and you'll see that many of them are just duplicate ways of doing the same thing. Let's get started. The first thing to do is connect to the database.
All mysql functions begin with mysql_, so it comes as no surprise that the function to connect to MySQL is called mysql_connect. Let's assume you would connect to MySQL from the server you're running PHP with the following details:

Username pee_wee
Password let_me_in
From the command line, you'd type the following:
mysql -upee_wee -p
You'd enter the password once the prompt appears (you can also enter it directly on the command line, but get into the habit of doing it this way - it's more secure!). PHP can connect in the same way. The mysql_connect() function looks as follows:

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

This function returns a resource which is a pointer to the database connection. It's also called a link identifier, or a database handle, and we'll use it in later functions.
Let's replace your connection details, and run this in a script:
<?php
$username = "pee_wee";
$password = "let_me_in";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
print "Connected to MySQL<br>";
// you're going to do lots more here soon
mysql_close($dbh);
?>
All going well, you should see "Connected to MySQL" when you run this script. If you can't connect to the server, make sure your password, username and hostname are correct, and that you've copied the script exactly.

The last line of the script contains another MySQL function - mysql_close(). Although this isn't strictly speaking necessary, PHP will automatically close the connection when the script ends, you should get into the habit of closing what you open. If you start developing more serious applications, or move to other, less tolerant languages, you will find the transition more difficult if you haven't learnt the basics well from the beginning.

Once you've connected, you're going to want to select a database to work with. Let's assume the database is called first_test. To start working in this database (the equivalent of typing USE first_test in MySQL), you'll need the mysql_select_db() function.

bool mysql_select_db ( string database_name [, resource link_identifier])

To change to the first_test database, add the mysql_select_db() function call to your script, as follows:

<?php
$username = "pee_wee";
$password = "let_me_in";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
print "Connected to MySQL<br>";
$selected = mysql_select_db("first_test",$dbh)
or die("Could not select first_test");
// you're going to do lots more here soon
mysql_close($dbh);
?>

Aug 3, 2010

PHP - print array

I you want to print an array values you can use next PHP function:

print_r();

Ex:
<?php
$a[] = "0";
$a[] = "5";
$a[] = "mmm';

print_r($a); //this will return function values...
?>

Aug 2, 2010

PHP start


Here we will write our first PHP code. And, after that some phrases about PHP variables.


Before you can work with PHP you need to install PHP on your computer if you haven’t installed PHP yet, now is a good time to install PHP.

First we will make a simple HTML page




Welcome to our first PHP tutorial.
 


Okay the above HTML page doesn't do anything special but just outputs Welcome to PHP tutorial on the browser, now lets add some PHP tags to it.

Note: All PHP code is written between  and ?> tags, now lets write "Welcome to our first PHP tutorial" using PHP.







   echo "Welcome to PHP tutorial";

?>



Okay the above PHP script will output Welcome to PHP tutorial note that we use the echo construct of PHP, the echo function simply outputs the content to the browser.

So if we wanted to write "Welcome" we would write echo "Welcome";

Note Have you noticed the ; at the end of the statment, Each PHP instruction must end with a semicolon.


Introduction to Variables
Let me introduce you to PHP variables, variables help you store and retrive data.

  • All variables start with a dollar sign $


  • The name of the variable can consist of letters and numbers, but must begin with a letter. It can also contain special characters like underscore '_', see some examples below

    $site = 'phpbuddy.com' // valid variable
    $4site = 'not yet'; // invalid variable starts with a number
    $_4site = 'not yet'; // valid variable starts with an underscore 

    Some more examples

    $testvariable = 1 + 1; // Assigns a value of 2.
    $testvariable = 1 – 1; // Assigns a value of 0.
    $testvariable = 2 * 2; // Assigns a value of 4.
    $testvariable = 2 / 2; // Assigns a value of 1. 

    Okay to make things easier I will show you an example here we will create a variables $a, $b and multiply them and store the value in $c, just see it's so simple
    
    
    
    $a = 5;  //we created a variable a and assigned it a value of 5
    
    $b = 2;  //we created a variable b and assigned it a value of 2
    
    
    
    $c = $a * $b;  //we multiply varaible a and b and store the value in c
    
    echo $c;  //we print the content of variable c which is 10
    
    ?>
    


    PHP variables can hold strings, dynamic data, PHP variables are case sensitive $a is not the same as $A

    
    
    
    $a = "Welcome to PHP ";  //$a holds the string Welcome to PHP
    
    $A = 4;  //$A holds the value 4
    
    
    
    echo "Variable a conatains: $a";
    
    echo "Variable A contains: $A";
    
    
    
    echo "$a $A";  //outputs both variables $a and $A
    
    ?>