Feb 25, 2011

Advance PHP


This section will be focusing on some advanced PHP topics, which will empower the reader to create dynamic web pages.
Superglobals
In the previous chapters the concept of global variable was explained. A global variableis a variable declared at the top of the script outside the function. This variable is available to the complete script. Superglobal variables are arrays built into PHP. These superglobal variables are populated automatically with useful elements, and they are available in any scope. A superglobal array can be accessed within a function or a method without using the global keyword.
PHP Superglobals
  • $_COOKIE – It contains values provided to the script via HTTP cookies.
  • $_GET – It contains variables submitted to the script using HTTP get method.
  • $_POST – It contains variables submitted to the script using HTTP post method.
  • $_REQUEST – It is a combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays.
  • $_ENV – It contains keys and values set by the script’s shell.
  • $_FILES – It contains information about uploaded files.
  • $_SERVER – It contains variables made available by the server.
  • $GLOBALS – It contains all the global variables associated with the current script.
Instanceof Operator
The instanceof operator in PHP is used to determine whether a given object, the parents of that object, or its implemented interfaces are of a specified object class.
Example
<?php
class X { }
class Y { }
$thing = new X;
if ($thing instanceof X) {
echo 'X';
}
if ($thing instanceof Y) {
echo 'Y';
}
?>
 
Declare
The declare statement is used to set execution directives for a block of code. The syntax of the declare statement is similar to the syntax of other flow control statements.
Syntax
declare (directive)
statement
 
The directive section allows the behavior of the declare block to be set. In this only one directive is recognized, which is the ticks directive.
Ticks - A tick is an event that occurs for every N low level statements, which are executed within the declare block. The value of N is specified using the statement ticks = N in the directive section.]
The statement part of the declare block will be executed according to the directives set in the directive block.
Example
<?php
// how to use declare:
// the first way:
declare(ticks=1) {
// entire script here
}
// the second way:
declare(ticks=1);
// entire script here
?>

Require
The require() statement includes and evaluates a specific file. The require() and include() statements are similar in every way except how they handle errors. When there is an error the include() statement produces a warning but the require() statement results in a fatal error. The require statement is used when you want a missing file to halt the processing of the page. In this case, if include() is used even then the script will keep on running regardless of the missing file.
Example
<?php
require 'welcome.php';
require $welcomefile;
require ('welcomefile.txt');
?>
 
Include
The include() statement includes and evaluates a specified file. The include() statement works in the same way as the require() statement. The basic difference between them is that when an error occurs the include() statement gives a warning whereas the require() statement gives a fatal error.
Example
fruit.php
<?php
$color = 'red';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A red apple
?>
 
Variable Functions
There is a concept of variable functions in PHP. The concept of variable function is that if a variable name has parentheses appended to it, then PHP will look for the function with the same name as the variable and will try to execute it. This can be used to implement callbacks and function tables.
Example
<?php
function fun() {
echo "In fun()<br />\n";
}
function abc
($arg = '')
{
echo "In abc(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'fun';
$func(); // This calls fun()
$func = 'abc';
$func('test'); // This calls abc()
$func = 'echoit';
$func('test'); // This calls echoit()
?>

Feb 24, 2011

Artificial Intelligence with PHP Can PHP respond to users like a human?


Humans have long been fascinated with Artificial Intelligence. Online artificial intelligence, often called bots, are all measured against the mother of all online intelligence, A.L.I.C.E. Standing for "Artificial Linguistic Internet Computer Entity," A.L.I.C.E is a chat bot developed in the mid 90s that is capable of holding intelligent conversation, and giving relevant answers.
A.L.I.C.E. and variations of her, respond to the language AIML (Artificial Intelligence Markup Language) to get instruction about how to "think." There are several implementations of this in languages such as Java, Ruby, Perl, Python, etc, including one in PHP called Program E.

If you are looking for a phpBB forum artificial intelligence, There is a  Forum AI , and have had a lot of success with it.

These PHP interfaces give PHP users a familiar platform from which to jump into AIML, and develop their own brand of AI.

Feb 23, 2011

How to Create a Random Date in PHP?



While browsing some forums the other day, I came across this question – “How do I find a random date in PHP?”
This is a pretty simple operation, if we make use of a few built-in PHP functions – time(), strtotime(), and date(). In this article, we’ll see how these three can work together to find a random date within a given range.

The PHP time() Function and Timestamps
The PHP time() function is very simple. It returns the current time.
It helps us understand something else though – Unix timestamps. The time() function, along with all of PHP’s time/date functions, deals with Unix timestamps. This is an integer which represents the number of seconds that have elapsed since Jan 1, 1970 (considered the beginning of the “Unix epoch”).
For example, the current timestamp for Thursday, Feb. 7 9:57 PM is 1202439456. You can do the math if you want. I’ll trust PHP.
This allows us to do a lot of simple operations with time, however. We know that a timestamp deals with seconds – so we can add/subtract a certain number of seconds to modify the time by minutes, hours, or days.
$time = time();  //  Current time
$time = time() - 60;  //  One minute ago
$time = time() + 120;  //  Two minutes in the future
$time = time() - 3600;  //  One hour ago
PHP’s date() Function – Formatted Dates
The time() function and timestamps become really powerful when you understand how to use the date() function.
This takes two parameters – a date format string and a timestamp. It then takes the timestamp and outputs the given time in the given format. You can find a list of date format characters at php.net. Here are a few examples, though…
$now = time();
 
$x = date("m-d-Y", $now);  //  02-07-2008
$y = date("M d Y", $now);  // Feb 07 2008
$z = date("F d, Y", $now);  // February 07, 2008
Notice that the letters (mMFdY) represent the actual dates, while the spacing and punctuation is just used for formatting.
Getting Custom Timestamps with strtotime()
The last function to look at is strtotime(). This takes a formatted date string (like “Feb 07 2008″ or “1 day ago”) and returns the appropriate Unix timestamp.
This allows you to fetch a timestamp for pretty much any date you want and then manipulate it in other ways – using the date() function or your own mathematical functions.
This is also going to help us find a random date in between two given dates.
Finding a Random Date
In order to find a random date, we need three things. The rand() function – to get a random number or timestamp. A start date. An end date.
In this simple example, we’ll find a random time between the start of the Unix epoch (timestamp = 0) and the current time. Then we’ll format it in the m-d-Y format for easy readability.
$time = rand( 0, time() );
echo date("m-d-Y", $time);
Run that, and you’ll find a random date between “Jan 1 1970″ and whatever your current date is – “Feb 7 2008″ for me.
We can make this a little better by using strtotime to set the min and max value for rand(). In this example, we’ll find a date in 2007 – between “Jan 01 2007″ and “Dec 31 2007″.
$time = rand( strtotime("Jan 01 2007"), strtotime("Dec 31 2007") );
echo date("m-d-Y", $time);
And there you go. Replace the strtotime() calls that I used, and you can find a random date within any given daterange.
However, take note that there are limitations to the extent of the Unix timestamp. By using a negative number, the earliest date you can get with date() is around 1901. The latest date you’ll be able to work with is around 2025. This is a limitation based on the size of integers in PHP – the Unix timestamp just can’t get any bigger in its basic form.

Feb 22, 2011

Working with someone else's code

Often it is easier to work with a preexisting PHP program than to sit down and write your own from scratch. Sometimes these programs come close to doing what you want, but don't do exactly what you want. In these cases you may want to go into the existing code and modify it for your needs. When doing this, here are some things to keep in mind.
Difficulty: Easy
Time Required: Varies
Here's How:
  1. Look at the license of the program. Does it allow you to make changes for your own use? Does it allow you to distribute the changes once they are made? Are you allowed to use the program for personal or commercial use? Never work with someone else's code if you don't have permission to do so!
  2. Always keep a backup of the original files! We all have "broke" programs at some point in time. Make sure you keep a copy of all the original files on hand for when this inevitably happens to you, so you can successfully backtrack and see where you went wrong.
  3. Leave lots of comments! If you leave notes to yourself or other programmers about what and why you have changed the original code, it makes future edits and easier.
  4. Give the original author credit. Whether you plan to redistribute the code with your changes, or you're just running it on your personal website, make sure all author lines are left intact. By all means add your own information as well, but always continue to give credit to the original author.

Execute PHP from a .html File


How can I execute PHP code on my existing myfile.html page?:
When a web page is accessed, the server checks the extension to know how to handle the page. Generally speaking if it sees a .htm or .html file, it sends it right to the browser because it doesn't have anything to process on the server. If it sees a .php extension (or .shtml, or .asp, etc), it knows that it needs to execute the appropriate code before passing it along to the browser.
Here is the problem: You find the perfect script, and you want to run it on your site, but you need to included PHP on your page for it to work. You could just rename your pages to yourpage.php instead of yourpage.html, but you already have incoming links or search engine ranking so you don't want to change the file name. What can you do?
First let me preface this by saying that if you are creating a new file anyway, you may as well use .php. This is to help people who have existing .html pages they need to execute PHP on.
The way to execute PHP on a .html page is to modify your .htaccess file. This file may be hidden, so depending upon your FTP program you may have to modify some settings to see it. Then you just need to add this line for .html:
AddType application/x-httpd-php .html
Or for .htm
AddType application/x-httpd-php .htm
If you only plan on including the PHP on one page, it is better to setup this way:
<Files yourpage.html>
AddType application/x-httpd-php .html
</Files>
This code will only make the PHP executable on the yourpage.html file, and not on all of your html pages.
Things to watch out for:
  • If you have an existing .htaccess file, add this to it, do not overwrite it or other settings may stop working! Always be very careful with your .htaccess file and ask your host if you need help
  • Anything in your .html files that starts with <? will now be executed as PHP, so if it's in your file for some other reason (an XML tag for example) you will need to echo these lines to prevent errors. For example:
    <?php echo '<?xml version="1.0" encoding="IUTF-8"?>'; ?>

Feb 3, 2011

PHP cookies


Cookies allow the webmaster to store information about the site visitor on their computer to be accessed again the next time they visit. One common use of cookies is to store your username and password on your computer so you don't need to login again each time you visit a website. Cookies can also store other things such as your name, last visit, shopping cart contents, etc.
The main difference between a cookie and a session is that a cookie is stored on your computer, and a session is not. Although cookies have been around for many years and most people do have them enabled, there are some who do not. Cookies can also be removed by the user at any time, so don't use them to store anything too important.
A cookie is set with the following code:setcookie(name, value, expiration)
 <?php 
 $Month = 2592000 + time(); 
 //this adds 30 days to the current time 
 setcookie(AboutVisit, date("F jS - g:i a"), $Month);
 ?> 
The above code sets a cookie in the visitor's browser called "AboutVisit". The cookie sets the value to the current date, and set's the expiration to be be in 30 days (2592000 = 60 seconds * 60 mins * 24 hours * 30 days.)
Now let's retrieve the cookie.
 <?php 
 if(isset($_COOKIE['AboutVisit']))
 { 
 $last = $_COOKIE['AboutVisit']; 
 echo "Welcome back! <br> You last visited on ". $last; 
 } 
 else 
 { 
 echo "Welcome to our site!"; 
 } 
 ?>
This code first checks if the cookie exists. If it does, it welcomes the user back and tells them when they last visited. If they are new, it skips this and prints a generic welcome message.
TIP: If you are calling a cooking on the same page you plan to set one - be sure you retrieve it first, before you overwrite it!
To destroy the cookie, simply use setcookie again, only set the expiration date to be in the past. This is often done when you 'logout' of a site. Here is an example:
 <?php 
 $past = time() - 10; 
 //this makes the time 10 seconds ago 
 setcookie(AboutVisit, date("F jS - g:i a"), $past);
 ?> 
REMEMBER:Cookies need to be set in the header. This means they must be sent beforeany HTML is set to the page, or they will not work

PHP mail function


Many websites offer a way for you to send them an email from a simple form on their site. Providing the form as opposed to simply listing your email address not only looks nicer but also serves two purposes.
  1. First, the form lets the website owner decide what information it is important to collect and prompts the users to fill in the answers to each of their questions. This way the user doesn't forget to include important information.
  2. Second, if you list your email directly on your site it can be picked up by bots designed to 'farm' email addresses. What that means for you is SPAM. Nobody likes to have their inbox flooded with SPAM, and using a form can help prevent that.
The mail function is phrased as: mail (to, subject, body, headers)
An example is:
 mail ( "me@mysite.com", "Contact Us Form", "This is an email from your site", "From: you@yoursite.com" )