Tuesday, June 24, 2008

The future of PHP 6

<div style="text-align: center; font-weight: bold; font-family: arial;">Know what changes are in store for PHP V6 and how your scripts will change
<div style="text-align: left;">
PHP's next edition, V6, includes new features and syntax improvements that will make it easier to use from an object-oriented standpoint. Other important features, such as Unicode support in many of the core functions, mean that PHP V6 is positioned for better international support and robustness.

PHP is already popular, used in millions of domains (according to Netcraft), supported by most ISPs and used by household-name Web companies like Yahoo! The upcoming versions of PHP aim to add to this success by introducing new features that make PHP more usable in some cases and more secure in others. Are you ready for PHP V6? If you were upgrading tomorrow, would your scripts execute just fine or would you have work to do? This article focuses on the changes for PHP V6 — some of them back-ported to versions PHP V5.x — that could require some tweaks to your current scripts.

If you're not using PHP yet and have been thinking about it, take a look at its latest features. These features, from Unicode to core support for XML, make it even easier for you to write feature-filled PHP applications.

New PHP V6 features

PHP V6 is currently available as a developer snapshot, so you can download and try out many of the features and changes listed in this article. For features that have been implemented in the current snapshot

Improved Unicode support

Much improved for PHP V6 is support for Unicode strings in many of the core functions. This new feature has a big impact because it will allow PHP to support a broader set of characters for international support. So, if you're a developer or architect using a different language, such as the Java™ programming language, because it has better internationalization (i18n) support than PHP, it'll be time to take another look at PHP when the support improves.

Because you can download and use a developer's version of PHP V6 today, you will see some functions already supporting Unicode strings. For a list of functions that have been tested and verified to handle Unicode

Namespaces

Namespaces are a way of avoiding name collisions between functions and classes without using prefixes in naming conventions that make the names of your methods and classes unreadable. So by using namespaces, you can have class names that someone else might use, but now you don't have to worry about running into any problems. Listing 1 provides an example of a namespace in PHP.

You won't have to update or change anything in your code because any PHP code you write that doesn't include namespaces will run just fine. Because the namespaces feature appears to be back-ported to V5.3 of PHP, when it becomes available, you can start to introduce namespaces into your own PHP applications.

Example of a namespace


// I'm not sure why I would implement my own XMLWriter, but at least
// the name of this one won't collide with the one built in to PHP
namespace NathanAGood;
class XMLWriter
{
// Implementation here...
}

$writer = new NathanAGood::XMLWriter();

?>


Web 2.0 features

Depending on how you use PHP and what your scripts look like now, the language and syntax differences in PHP V6 may or may not affect you as much as the next features, which are those that directly allow you to introduce Web 2.0 features into your PHP application.

SOAP

SOAP is one of the protocols that Web services "speak" and is supported in quite a few other languages, such as the Java programming language and Microsoft® .NET. Although there are other ways to consume and expose Web services, such as Representational State Transfer (REST), SOAP remains a common way of allowing different platforms to have interoperability. In addition to SOAP modules in the PHP Extension and Application Repository (PEAR) library, a SOAP extension to PHP was introduced in V5. This extension wasn't enabled by default, so you have to enable the extension or hope your ISP did. In addition, PEAR packages are available that allow you to build SOAP clients and servers, such as the SOAP package.

Unless you change the default, the SOAP extension will be enabled for you in V6. These extensions provide an easy way to implement SOAP clients and SOAP servers, allowing you to build PHP applications that consume and provide Web services.

If SOAP extensions are on by default, that means you won't have to configure them in PHP. If you develop PHP applications and publish them to an ISP, you may need to check with your ISP to verify that SOAP extensions will be enabled for you when they upgrade.

XML

As of PHP V5.1, XMLReader and XMLWriter have been part of the core of PHP, which makes it easier for you to work with XML in your PHP applications. Like the SOAP extensions, this can be good news if you use SOAP or XML because PHP V6 will be a better fit for you than V4 out of the box.

The XMLWriter and XMLReader are stream-based object-oriented classes that allow you to read and write XML without having to worry about the XML details.


Things removed

In addition to having new features, PHP V6 will not have some other functions and features that have been in previous versions. Most of these things, such as register_globals and safe_mode, are widely considered "broken" in current PHP, as they may expose security risks. In an effort to clean up PHP, the functions and features listed in the next section will be removed, or deprecated, from PHP. Opponents of this removal will most likely cite issues with existing scripts breaking after ISPs or enterprises upgrade to PHP V6, but proponents of this cleanup effort will be happy that the PHP team is sewing up some holes and providing a cleaner, safer implementation.

Features that will be removed from the PHP version include:

  • magic_quotes
  • register_globals
  • register_long_arrays
  • safe_mode

magic_quotes

Citing portability, performance, and inconvenience, the PHP documentation discourages the use of magic_quotes. It's so discouraged that it's being removed from PHP V6 altogether, so before upgrading to PHP V6, make sure that all your code avoids using magic_quotes. If you're using magic_quotes to escape strings for database calls, use your database implementation's parameterized queries, if they're supported. If not, use your database implementation's escape function, such as mysql_escape_string for MySQL or pg_escape_string for PostgreSQL. Listing 2 shows an example of magic_quotes use.

Using magic_quotes (discouraged)

// Assuming magic_quotes is on...
$sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username']";
?>

After preparing your PHP code for the new versions of PHP, your code should look like that in Listing 3.

Listing 3. Using parameterized queries (recommended)
// Using the proper parameterized query method for MySQL, as an example
$statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?");
$statement->execute(array($_GET['username']));
?>



Now that support for magic_quotes will be completely removed, the get_magic_quotes_gpc() function will no longer be available. This may affect some of the older PHP scripts, so before updating, make sure you fix any locations in which this functions exists.

register_globals

The register_globals configuration key was already defaulted to off in PHP V4.2, which was controversial at the time. When register_globals is turned on, it was easy to use variables that could be injected with values from HTML forms. These variables don't really require initialization in your scripts, so it's easy to write scripts with gaping security holes. The register_globals documentation provides much more information about register_globals. See Listing 4 for an example of using register_globals.

Using register_globals (discouraged)


// A security hole, because if register_globals is on, the value for user_authorized
// can be set by a user sending them on the query string
// (i.e., http://www.example.com/myscript.php?user_authorized=true)
if ($user_authorized) {
// Show them everyone's sensitive data...
}
?>


If your PHP code uses global variables, you should update it. If you don't update your code to get prepared for newer versions of PHP, consider updating it for security reasons. When you're finished, your code should look like Listing 5.

Listing 5. Being specific instead (recommended)
function is_authorized() {
if (isset($_SESSION['user'])) {
return true;
} else {
return false;
}
}

$user_authorized = is_authorized();
?>

register_long_arrays

The register_long_arrays setting, when turned on, registers the $HTTP_*_VARS predefined variables. If you're using the longer variables, update now to use the shorter variables. This setting was introduced in PHP V5 — presumably for backward-compatibility — and the PHP folks recommend turning it off for performance reasons. Listing 6 shows an example of register_long-arrays use.

Using deprecated registered arrays (discouraged)


   // Echo's the name of the user value given on the query string, like
// http://www.example.com/myscript.php?username=ngood
echo "Welcome, $HTTP_GET_VARS['username']!";
?>

If your PHP code looks like that shown in Listing 6, update it to look like that in
Listing 7. Shut off the register_long_arrays setting if
it's on and test your scripts again.


Using $_GET (recommended)
   // Using the supported $_GET array instead.
echo "Welcome, $_GET['username']!";
?>
safe_mode

The safe_mode configuration key, when turned on, ensures that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating in a shared server environment, like many ISPs would have. (For a link to a list of the functions affected by this safe_mode change, Your PHP code will be unaffected by this change, but it's good to be aware of it in case you're setting up PHP in the future or counting on safe_mode in your scripts.

PHP tags

Microsoft Active Server Pages (ASP)-style tags — the shorter version of the PHP tags — are no longer supported. To make sure this is not an issue for your scripts, verify that you aren't using the <% or %> tags in your PHP files. Replace them with and ?>.

FreeType 1 and GD 1

The PHP team is removing support for both FreeType 1 and GD 1, citing the age and lack of ongoing developments of both libraries as the reason. Newer versions of both of these libraries are available that provide better functionality. For more information about FreeType and GD

ereg

The ereg extension, which supports Portable Operating System Interface (POSIX) regular expressions, is being removed from core PHP support. If you are using any of the POSIX regex functions, this change will affect you unless you include the ereg functionality. If you're using POSIX regex today, consider taking the time to update your regex functions to use the Perl-Compatible Regular Expression (PCRE) functions because they give you more features and perform better. Table 1 provides a list of the POSIX regex functions that will not be available after ereg is removed. Their PCRE replacements are also shown.


Installing PHP6 (For beginners)

Installing PHP6 (For beginners)

Hello all, you might have read that PHP6 is under and has been under development for the past few months. Well after hacking around some code trying to get some DirectoryIterator unicoded and ready for php6, I have ran into the problem of compiling php6.. So I figured, might as well give an idea to anyone who feels like on how to install (compile) php6.

Notice that I will be using the command:

  • su -c "command"

Which is because some system do not have sudoers setup yet (yes it does still exist)

Ok, before reading this, here's a couple usefull links:

http://php.net/
http://php.net/anoncvs.php (Most used here)
http://snaps.php.net/
http://cvs.php.net/
http://site.n.ml.org/info/flex/
http://icu.sourceforge.net/download/3.6.html


Hello all, you might have read that PHP6 is under and has been under development for the past few months. Well after hacking around some code trying to get some DirectoryIterator unicoded and ready for php6, I have ran into the problem of compiling php6.. So I figured, might as well give an idea to anyone who feels like on how to install (compile) php6.


There is also a numerous amount of tools you'll have to install before you might become able to try to compile PHP6.

  • autoconf: 2.13
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • bison: 1.28, 1.35, 1.75, 2.0 or higher
  • flex: 2.5.4
  • re2c: 0.9.11+


Of course, all this information can be found on the php's page (http://php.net/anoncvs.php )

Also, the coolest part of this (The heart of php6 imho - else than andrei and sara (joking))) is that package you'll have to install:
http://icu.sourceforge.net/download/3.6.html

You can start by executing the following commans:

  • mkdir ~/development; cd ~/development
  • wget ftp://ftp.software.ibm.com/software/globalization/icu/3.6/icu4c-3_6-src.tgz

+ ^ This is for linux of course

  • tar -xzvf icu4c-3_6-src.tgz
  • cd icu; cd source
  • su -c "mkdir /usr/local/icu"
  • ./configure --prefix=/usr/local/icu && make && make install

^ You might get an error related to zlib (Version to low, I strongly suggest to update it if
you get the error)

So what? You are done with ICU compiling ? Let's move on shall we ?

So before installing php6, you have to download it. You can choose from various places, first
you can simply look at http://snaps.php.net (Which are frequent snapshots of the cvs repository) and get the latest php6 snap or you can simply make an anonymous checkout (for those who dont' have a username here's how to do that)

It is also recommended that you put these configurations into your ~/.cvsrc file:

  • cvs -z3
  • update -d -P
  • checkout -P
  • diff -u


Then you are ready to go for your anonymous cvs checkout

(Username: "cvsread" and password "phpfi")

  • cvs -d :pserver:cvsread@cvs.php.net:/repository login
  • cvs -d :pserver:cvsread@cvs.php.net:/repository checkout php6


The previous commands will execute a cvs checkout (Get the code) and store it into ~/development/php6

Once you have installed all the tools stated above, did your checkout, and all is square here comes the second part.

You'll have to execute the following commands (Using apache2 for this example):

  1. cd php6
  2. ./buildconf
  3. sudo "mkdir /usr/local/php6"
  4. ./configure --prefix=/usr/local/php6 --with-icu-dir=/usr/local/icu --with-apxs2=/usr/bin/apxs2

(Just using apxs2 as an example)
^ You can of course add more options as such as --with-mysql=/usr/bin (if mysql is in bin)
--with-phar --with-bz2. Just see the command "./configure --help" for a list of options.

^ Also, if the make is dying because of some flex problems, you can use the command
"apt-get install flex-old" or simply get the source at: http://site.n.ml.org/download/20030401085856/flex/flex-2.5.4a.tar.gz

  1. then ,if it all went well of course, you type:
  2. make && su -c "make install"

If it all went well, then you should have the php6 files all ready to be used in /usr/local/php6
Just give a look at it to see if you have new directories, etc.

If you used the --with-apxs(2) options, you should already be set with the apache load_modules et all. You might notice that it said LoadModule php5 well don't worry that's all good you'll just need your libphp6.so which is usually well placed when using --with-apxs.

If you are not sure, just look at your /etc/apache2/httpd.conf and /etc/apache2/mods-enabled/php5.load files to see if you have it pointing to libphp6.so (Which it probably is)

So are you ready ? Last command line command:
- su -c "apache2ctl restart"

If you do not get an error, you should be able to go to your web directory
(Here I am using /var/www on my development box) and add a file with this content:

phpinfo();
?>

If you are lucky and it all went well, then you will see "PHP Version 6.0.0-dev" with probably a million warnings. Well it is installed, you can start fiddling around and testing.

Hope this helps a couple people (Even though a lot of you probably gave me hints during this crusade)

PHP Paging Code: Break up records into pages

<!--
============= Connection.php =================
//-->
<?
$server = "localhost";
$user = "root";
$pass = "";


$OpSe = mysql_connect($server, $user, $pass ) or die(mysql_error()):
$OpDb = mysql_select_db("DATABASE_NAME",$OpSe) or die(mysql_error());
?>





<!--
============= Paging.php =================
//-->
<style type="text/css">
a.spage:link{
border: 1px solid #000000;font-family:verdana; font-size:10px;padding-top:1px; padding-bottom:2px;padding-left:4px;padding-right:4px;color:white;font-weight:bold;text-decoration:none;background-color:#ffffff; color:#000000;
}


a.lspage:link{
border: 1px solid #000000;font-family:verdana; font-size:10px;padding-top:1px; padding-bottom:2px;padding-left:4px;padding-right:4px;color:white;font-weight:bold;text-decoration:none; color:#000000;
}
</style>
<?
// set record display per page....
$PP = 10;
//---------------
isset($_GET["st"]) && $_GET["st"]!="" ? $st=$_GET["st"] : $st=0;
?>
<table border="1">
<tr bgcolor="#999999">
<td><b>Field1 Date</b></td>
<td><b>Field2 Date</b></td>
<td><b>Field3 Date</b></td>
<td><b>Field4 Date</b></td>
</tr>
<?
$query ="SELECT field1, field2, field3, field4 FROM TABLE_NAME LIMIT ".$st.",".$PP;
$rs = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($rs)){
?>
<tr bgcolor="#CCCCCC">
<td><?=$row["field1"]?></td>
<td><?=$row["field2"]?></td>
<td><?=$row["field3"]?></td>
<td><?=$row["field4"]?></td>
</tr>
<?
}
?>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="99%" align="center">
<tr>
<td width="1%">
<? if($st>=$PP){?>
<a href="?st=<?=$st-$PP?>">Pre</a>
<? }?>
</td>
<td align="center">
<?
// Do not change below this line-----------------------------------------
$total--;
$pgv = $total/$PP;

if($pgv>1)
$pg_a = explode(".",$pgv);
else
$pg_a = $pgv;

if($pg_a[1]>0)
$pg = $pg_a[0]+1;
else
$pg = 0;

if($pg=="")$pg = $pgv;
$selpage = $st / $PP;
$selpage++;
$selpage = (int) $selpage;
for($ploop=1,$stl=1 ;$ploop<=$pg;$ploop++,$stl+=$PP){
echo ' <a href="?st='.$stl.'" class="';
echo $ploop==$selpage ? "spage" : "lspage";
echo '">'.$ploop.'</a> ';
}
// Do not change above this line-----------------------------------------
?>
</td>
<td align="right" width="1%">
<? if($st<$total-$PP){?>
<a href="?st=<?=$st+$PP?>">Next</a>
<? }?>
</td>
</tr>
</table>

Saturday, June 21, 2008

Wednesday, June 18, 2008

Bandwidth Test, Speed Test

<?php


/*** Bandwidth Tester 0.92 ***/
/* Please wait for 1.0 patiently! */



// How many bytes to test with. Mimimum=70. 128KB=131072. 1MB=1048576
$testsize = 1048576;



header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// always modified
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Pragma: no-cache"); // HTTP/1.0
header ("X-Notice: ");
header ("X-Notice: Bandwidth-Tester is freeware.");
header ("X-Notice: You may use it freely on your site.");
header ("X-Notice: Just don't remove this notice.");
header ("X-Notice: To get the source code, run this script ");
header ("X-Notice: with downloadme=1 in the query string.");




/* How does it work? The script generates a variable amount of random data
* sends it to the client and measures the time taken for transmission. The
* bandwidth is then calculated from the time using a simple algorithm.
*
* WARNING: This script can bog down your server - as absolutely NO
* optimization was used.
*
*
* This script is best run on the Zend PHP Engine, with Zend Optimizer.
* Any improvement in performance is not guaranteed with other
* PHP Engines.
*
* History:
* 0.9 - First public release
* 0.91 - Reduced the size of the timing code
* 0.92 - Reduced the size of the timing code even more
* Forecast:
* 0.921a - Adding a smaller test before the main to make results more accurate and to adjust test data according to first results
* 1.0 - Looking to adding optimization code
* 1.1 - Adding template support
* 1.2 - Adding web-based administration
*/




if($downloadme==1){
echo "<html><body>";
show_source($SCRIPT_FILENAME);
echo "</body></html>";
}
else {


// First, initialize the test comment


// seed random
srand ((double) microtime() * 1000000);



if($testsize<70) {die("<script>alert('The test string size is less than 70. Cannot test.')</script>");
}
$realtestsize = $testsize - 70;
function GetTestString($drealtestsize){
$duhteststring = "<!"."--";
for($i=0;$i<$drealtestsize; $i++){
$duhteststring .= generatekeycode();
}
$duhteststring .= "-"."->";
return $duhteststring;
}
function CalculateBandwidth($Ditt,$Dott){
$Datasize=$Dott;
$LS=$Datasize/$Ditt;
$kbps=(($LS*8)*10*1.02)/10;
$mbps=$kbps/1024;
if($mbps>=1){$speed=$mbps." Mbps aka ".$kbps." Kbps";}
else {$speed=$kbps." Kbps aka ".$mbps." Mbps";}
$speed .="<br>Time taken to test connection: ".(($Ditt*1024)/1000)." Seconds <br>A number used to determine your speed: ".$LS."<br>Another number used to determine your speed: ".$Ditt."<br>Tested your connection with ".$Datasize."Bytes/".($Datasize/1024)."KB/".($Datasize/1048576)."MB of random data<br>";
return $speed;
}


function generatekeycode(){
// srand ((double) microtime() * 1000000);


// Made the randomizer a little more "random"! :)
srand ((double) microtime() * rand(100000,1000000) / rand(1,15));
$tester = rand(33,255);
if($tester==45)return generatekeycode();
return chr($tester);
}
?><html>
<head><title>Bandwidth Tester</title></head>
<body><?php
if($HTTP_SERVER_VARS["REQUEST_METHOD"]=="GET" && $HTTP_GET_VARS["execute"]!="1"){
echo('<form action="'.$HTTP_SERVER_VARS["SCRIPT_NAME"].'" method="GET">
<input type="submit" value="Click Here To Begin Testing" onClick="this.value="Please wait while your request is being processed, it may take a while">
<input type="hidden" name="execute" value="1">
<input type="hidden" name="DO.NOT.CACHE" value="'.rand(255,65536).'">
</form>');}
elseif($HTTP_GET_VARS["execute"]=="1"){
$teststring=GetTestString($realtestsize);echo('<form method="POST" action="'.$HTTP_SERVER_VARS["SCRIPT_NAME"].'">
<input type="hidden" name="td" value="No Test">
<input type="button" value="Please wait while your request is being processed, it may take a while">
</form>
<script language="JavaScript">
var Hi = new Date();
</script>'.$teststring.'<script language="JavaScript">
var Bye = new Date();
var NiHao = new Array(Hi.getTime(),Bye.getTime());
var Factor=1024;
if(NiHao[1]==NiHao[0])
Ditt=0;
else
Ditt=(NiHao[1]-NiHao[0])/Factor;
document.forms[0].elements[0].value=Ditt;
document.forms[0].submit();
</script><p>Tested. Now processing your request....</p>');}
elseif($HTTP_SERVER_VARS["REQUEST_METHOD"]=="POST"&&$HTTP_POST_VARS["td"]>0){
echo('<p>We have tested your Internet connection.<br>
The speed to which you connected to us is '.CalculateBandwidth($HTTP_POST_VARS["td"],$testsize).'
Thank you!<br>
</p>');}
elseif($HTTP_SERVER_VARS["REQUEST_METHOD"]=="POST"&&$HTTP_POST_VARS["td"]==0){
echo('<p>We were unable to test your connection speed.<br>It was too fast to measure.<br>
<a href="'.$HTTP_SERVER_VARS["SCRIPT_NAME"].'?execute=1&DO.NOT.CACHE='.rand(255,65536).'" onClick="this.innerText=\'The system is now generating the random test data to benchmark your connection speed. It will take a while.\'">If you would like to try testing again, click here.</a></p>
<p>'.CalculateBandwidth($HTTP_POST_VARS["td"],$testsize).'</p>');
}
?>
</body>
</html><?php } ?>



for more details visit:
http://www.yourip.zxq.net

Number of days between two dates

Get Number of Days between two difference dates

<?php
// Set the default timezone to US/Eastern
date_default_timezone_set('US/Eastern');


// Will return the number of days between the two dates passed in
function count_days($a, $b) {
// First we need to break these dates into their constituent parts:
$a_parts = getdate($a);
$b_parts = getdate($b);


// Now recreate these timestamps, based upon noon on each day
// The specific time doesn't matter but it must be the same each day
$a_new = mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
$b_new = mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);


// Subtract these two numbers and divide by the number of seconds in a
// day. Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round(abs($a_new - $b_new) / 86400);
}


// Prepare a few dates
$date1 = strtotime('12/3/1973 8:13am');
$date2 = strtotime('1/15/1974 10:15pm');
$date3 = strtotime('2/14/2005 1:32pm');


// Calculate the differences, they should be 43 & 11353
echo "<p>There are ", count_days($date1, $date2), " days.</p>";
echo "<p>There are ", count_days($date2, $date3), " days.</p>";
?>

Calculate date or time difference.

Function to calculate date or time difference.

<?php
/**
* Function to calculate date or time difference. Returns an array or
* false on error.
*
* @author MFJ <faisal.hexa@gmail.com>
* @copyright Copyright &copy; 2007, MFJ
* @link http://www.gidnetwork.com/b-16.html Get the date / time difference with PHP
* @param string $start
* @param string $end
* @return array
*/
function get_time_difference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
}
}
else
{
trigger_error( "Invalid date/time data detected", E_USER_WARNING );
}
return( false );
}
?>

Email address Validation Script

<?php
function check_email($mail_address) {
$pattern = "/^[\w-]+(\.[\w-]+)*@";
$pattern .= "([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
if (preg_match($pattern, $mail_address)) {
$parts = explode("@", $mail_address);
if (checkdnsrr($parts[1], "MX")){
echo "The e-mail address is valid.";
// return true;
} else {
echo "The e-mail host is not valid.";
// return false;
}
} else {
echo "The e-mail address contains invalid charcters.";
// return false;
}
}
check_email("admin@karachicorner.com");
?>


Empty Cashe - Remove Temp Cache

<?
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
?>

Rating, Ranking Code

Reader Rated Most Useful Entries

<HTML>
<HEAD>
<title>Reader Rated Most Useful Entries</title>
</HEAD>
<BODY>
<table border="0" width="100%">
<tr>
<td width="6%" bgcolor="#00FFFF"><p align="center"><small><font face="Verdana">Rank</font></small></td>
<td width="7%" bgcolor="#00FFFF"><p align="center"><small><font face="Verdana">Rating</font></small></td>
<td width="11%" bgcolor="#00FFFF"><p align="center"><small><font face="Verdana">Diary Date</font></small></td>
<td width="76%" bgcolor="#00FFFF"><p align="left"><small><font face="Verdana">Description
of Diary Page</font></small>
</td>
<script language="php">
$db = "DATABASE NAME";
$admin = "MYSQL USER NAME";
$adpass = "MYSQL PASSWORD";
$mysql_link = mysql_connect("localhost", $admin, $adpass);
mysql_select_db($db, $mysql_link);


$query = "SELECT * FROM avg_tally ORDER BY average DESC";
$result = mysql_query($query, $mysql_link);
if(mysql_num_rows($result)) {
$rank = 1;
while($row = mysql_fetch_row($result))
{
print("</tr><tr>");
if($color == "#D8DBFE") {
$color = "#A6ACFD";
} else {
$color = "#D8DBFE";
}
print("<td width=\"6%\" bgcolor=\"$color\"><center><small>");
print("<font face=\"Verdana\">$rank</font></small></center></td>");
print("<td width=\"7%\" bgcolor=\"$color\"><center><small>");
print("<font face=\"Verdana\"><strong>$row[1]</strong></font></small></center></td>");
print("<td width=\"11%\" bgcolor=\"$color\"><center><small>");
$url = $row[2] . ".php3";
if(!file_exists($url)) { $url = $row[2] . ".html"; }
print("<font face=\"Verdana\"><a href=\"$url\">$row[2]</a></font></small></center></td>");
print("<td width=\"76%\" bgcolor=\"$color\"><left><small>");
print("<font face=\"Verdana\">$row[3]</font></small></left></td>");
$rank++;
}
}
</script>
</table>
</BODY>
</HTML>

Hide Meta Tags

<HTML>

<BODY>

<?

$all_meta = get_meta_tags("meta_tags.php");

print($all_meta["description"]);

print("<br>");

print($all_meta["keywords"]);

?>

</BODY>

</HTML>

Random URL

Display random url with Title and Description of URL

<?

$random_url = array("http://www.apniphp.blogspot.com/",

"http://www.worldit-news.blogspot.com/",

"http://www.funzclub.blogspot.com/",

"http://www.karachicorner.blogspot.com/",

"http://www.islamic-information.blogspot.com/",

"http://www.smspk.zxq.com/",

"http://www.jokes.zxq.com/");


$url_title = array("Free PHP Scrips",

"World Information Technology News",

"Fun 4 Every 1",

"Get Inforamtion about Karachi, Pakistan",

"About ISLAM",

"SMS Collection",

"Jokes Collection");

$url_desc = array("- A complete solution of PHP Scripts",

"- Get the latest invention in Information Technology",

"- Funny Pictures, Cartoons and many more funny links",

"- About Karachi",

"- Islamic Infomation",

"- Send Free SMS to your Friends",

"- Submit your Jokes, Send jokes to your Friends");

srand(time());

$sizeof = count($random_url);

$random = (rand()%$sizeof);

print("<center><a href=\"$random_url[$random]\">$url_title[$random]</a> $url_desc[$random]</center>");

?>