Date file last modified
Posted On at by milanDate file last modified
Description
Outputs the date and time that a file was last modified. Can be formatted however you wish.
The code
// Change to the name of the file
$last_modified = filemtime("thisfile.php");
// Display the results
// eg. Last modified Monday, 27th October, 2003 @ 02:59pm
print "Last modified " . date("l, dS F, Y @ h:ia", $last_modified);
?>
Visitor information from php
Posted On at by milanVisitor information
Description
Displays information about a visitor to a web page. Shows IP address, referrer and browser type.
The code
/**
* Add this line of code in your page:
*
*/
// Display IP address
echo "
IP Address: " . $_SERVER['REMOTE_ADDR'] . "
";// Display the referrer
echo "
Referrer: " . $_SERVER['HTTP_REFERER'] . "
";// Display browser type
echo "
Browser: " . $_SERVER['HTTP_USER_AGENT'] . "
";?>
Page load time in php
Posted On at by milanPage load time
Description
Outputs the time in seconds that it takes for a PHP page to load.
The code
// Insert this block of code at the very top of your page:
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time;
// Place this part at the very end of your page
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
printf ("This page took %f seconds to load.", $totaltime);
?>
Php Page redirect
Posted On at by milanPage redirect
Description
If you want a PHP redirect script that redirects visitors from a page to a specific URL then this is it. It sends the user from one web page to a different web page address. It is a good alternative to using the meta tag http-equiv option.
The code
/**
* Place in a blank PHP page
*/
// Change to the URL you want to redirect to
$URL="http://www.example.com";
header ("Location: $URL");
?>
Php Word wrap
Posted On at by milanWord wrap
Description
A function that takes a string of text and wraps it into lines of a length that you determine. Can be useful for guestbooks, news posting scripts etc. to prevent the layout breaking.
The code
/**
* Example usage:
*
* // Your text
* $text = "This is a sentence which contains some words.";
*
* // Or from a database result
* $text = $row['text'];
*
* // Then put it into the function
* $text = word_wrap($text);
*
* // Output the result
* echo $text;
*/
function word_wrap($text) {
// Define the characters to display per row
$chars = "10";
$text = wordwrap($text, $chars, "
", 1);
return $text;
}
?>
Server information from php
Posted On at by milanServer information
Description
A useful built-in PHP function that displays information about the PHP installation on your server, including version number, available libraries etc.
The code
/**
* View this file in your browser.
*/
phpinfo();
?>
Php Shorten a text string
Posted On at by milanShorten a text string
Submitted by Totally PHP, 9th February 2004
Description
Function to shorten / truncate a string of text into a specific number of characters and add three dots (...) to the end. This will also round the text to the nearest whole word instead of cutting off part way through a word.
The code
/**
* Add this to your page:
*
* include "shorten_a_text_string.php";
* echo ShortenText($text);
* ?>
* where $text is the text you want to shorten.
*
* Example
* Test it using this in a PHP page:
*
* include "shortentext.php";
* $text = "The rain in Spain falls mainly on the plain.";
* echo ShortenText($text);
* ?>
*/
function ShortenText($text) {
// Change to the number of characters you want to display
$chars = 25;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
?>
Validate an email address using regular expressions
Posted On at by milanValidate an email address using regular expressions
Description
If you want a PHP script to verify an email address then use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address.
The code
$email = "someone@example.com";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
echo "Valid email address.";
}
else {
echo "Invalid email address.";
}
?>
Add data to a MySQL database
Posted On at by milanAdd data to a MySQL database
Description
How to insert and save information into a MySQL database table using PHP.
The code
/**
* Change the first line to whatever
* you use to connect to the database.
*
* We're using two values, title and
* text. Replace these with whatever
* you want to add to the database.
*
* Finally, change tablename to the
* name of your table.
*/
// Your database connection code
db_connect();
$query = "INSERT INTO tablename(title, text) VALUES('$title','$text')";
$result = mysql_query($query);
echo "The data has been added to the database.";
?>
Delete data from a MySQL database
Posted On at by milanDelete data from a MySQL database
Description
How to remove and erase stored information from a MySQL database table.
The code
/*
* Change the first line to whatever
* you use to connect to the database.
*
* Change tablename to the name of your
* database table.
*
* This example would delete a row from
* a table based on the id of the row.
* You can change this to whatever you
* want.
*/
// Your database connection code
db_connect();
$query = "DELETE FROM tablename WHERE id = ('$id')";
$result = mysql_query($query);
echo "The data has been deleted.";
?>
Send email using the PHP mail() function
Posted On at by milanSend email using the PHP mail() function
Description
How to send an email from within a PHP page using the built in mail() function.
The code
// Your email address
$email = "you@example.com";
// The subject
$subject = "Enter your subject here";
// The message
$message = "Enter your message here";
mail($email, $subject, $message, "From: $email");
echo "The email has been sent.";
?>
Write data to a text file in php
Posted On at by milanWrite data to a text file
Description
This will open a plain text file (.txt) and save information to it.
The code
$your_data = "This is the data to be stored in the text file.";
// Open the file and erase the contents if any
$fp = fopen("textfile_name.txt", "w");
// Write the data to the file
fwrite($fp, $your_data);
// Close the file
fclose($fp);
?>
Create a random password
Posted On at by milanCreate a random password
Description
Nice little function that will generate a completely random password.
The code
/**
* The letter l (lowercase L) and the number 1
* have been removed, as they can be mistaken
* for each other.
*/
function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
// Usage
$password = createRandomPassword();
echo "Your random password is: $password";
?>
Convert links into clickable hyperlinks
Posted On at by milanConvert links into clickable hyperlinks
Description
A function to change an email address or URL into a clickable HTML hyperlink using eregi_replace.
The code
function makeClickableLinks($text) {
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1\\2', $text);
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
'\\1', $text);
return $text;
}
// Usage
// Email address example
$text = "you@example.com";
echo makeClickableLinks($text);
echo "
";
// URL example
$text = "http://www.example.com";
echo makeClickableLinks($text);
echo "
";
// FTP URL example
$text = "ftp://ftp.example.com";
echo makeClickableLinks($text);
?>
Number of days between now and a day in the future
Posted On at by milanNumber of days between now and a day in the future
Description
This will calculate and show how many days there are from the current date to a date in the future that you define.
The code
// Change this to the day in the future
$day = 10;
// Change this to the month in the future
$month = 12;
// Change this to the year in the future
$year = 2003;
// You do not need to edit below this line
// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
echo "There are $days days until $day/$month/$year";
?>
Limit the length of a text string being entered into a database
Posted On at by milanLimit the length of a text string being entered into a database
Description
This can be used if you want to limit a string, for example if you want to limit the length of user inputted text that is being saved to a database.
The code
if (strlen($text) > "255") {
exit("The text you entered is too long.");
}
?>
Count number of words in a text string
Posted On at by milanCount number of words in a text string
Description
This will count through the sentences in a section of text and show how many words are contained within it.
The code
$text = "This is some text.";
$count = count(explode(" ", $text));
echo "$text contains $count words";
?>
Check that characters in a variable are alpha numeric using ereg
Posted On at by milanDescription
This verifies if a PHP variable string contains characters other than letters or numbers using the PHP function ereg. This PHP code snippet can be useful for form input where you only want users to input alpha numeric characters.
The code
// Example 1
$text = "onlyalphanumericcharacters012345";
if (ereg('[^A-Za-z0-9]', $text)) {
echo "This contains characters other than letters and numbers";
}
else {
echo "This contains only letters and numbers";
}
// Example 2
$text = "mixedcharacters012345&../@";
if (ereg('[^A-Za-z0-9]', $text)) {
echo "This contains characters other than letters and numbers";
}
else {
echo "This contains only letters and numbers";
}
?>
Calculate VAT on a price and round to two decimal places
Posted On at by milanCalculate VAT on a price and round to two decimal places
Description
This function is a simple PHP VAT calculator. It will calculate the 17.5% UK sales VAT (Value Added Tax) on an amount and then round the price to two (2) decimal places. For example, £5.95 would be £6.99125 with VAT added, which would be rounded to £6.99. The amount of vat can be altered to any amount of sales tax, so you can calculate a new price for any string using any percentage. This could come in useful if you needed to calculate the tax on a product in a shopping cart script.
The code
/*
Usage:
You want to calculate 17.5% VAT on a price of £4.67
$price_without_vat = 4.67
echo vat($price_without_vat);
This would return the new amount with 17.5% added, and would be rounded to 2 decimal places
*/
function vat($price_without_vat) {
$vat = 17.5; // define what % vat is
$price_with_vat = $price_without_vat + ($vat*($price_without_vat/100)); // work out the amount of vat
$price_with_vat = round($price, 2); // round to 2 decimal places
return $price_with_vat;
}
?>
Get the code
Download the file to your computer: Click here to get the file
free javascript
Posted On at by milanFree Java applets provided by
JavaScript
Kit
Remove all characters except letters and numbers from a string
Posted On at by milanRemove all characters except letters and numbers from a string
Description
If you want to strip a string of all symbols and characters other than alphanumeric letters and numbers then use this. It will take a string and erase / delete any non-alphanumeric characters, and then output a clean version without the unwanted characters.
The code
$string = "This is some text and numbers 12345 and symbols !£$%^&";
$new_string = ereg_replace("[^A-Za-z0-9]", "", $string);
echo $new_string
?>
Add numbers to MySQL database results
Posted On at by milanAdd numbers to MySQL database results
Description
Puts numbers in front of each result obtained from a MySQL database. Each item in the array has a number added in front of it.
The code
/*
This will add a number in front of each row
eg.
1 - John
2 - Paul
3 - Michael
4 - Susan
*/
$sql = "SELECT name FROM people";
$result = mysql_query($sql);
$thenumber = 1;
while ($row = mysql_fetch_array ($result)) {
echo $thenumber . ' - ' . $row['name'];
$thenumber++;
}
?>
Unlock Nokia mobiles
Posted On at by milanUnlock Nokia 3120 (Vodafone, Spain)
#pw+008923325642375+7#
Unlock Nokia 6101 (T-Mobile, USA)
#pw+110464135761655+1#
Unlock Nokia 6230 (Vodafone, UK)
#pw+737190152533105+7#
Unlock Nokia 7600 (3 Network, UK)
#pw+448917267516205+1#
Unlock Nokia 6010 (T-Mobile, USA)
Posted On at by milanUnlock Nokia 6010 (T-Mobile, USA)
#pw+748900573631603+1#
Unlock Nokia 6102b (Cingular, USA)
Posted On at by milanUnlock Nokia 6102b (Cingular, USA)
#pw+324556243142742+1#
Unlock Nokia 6820b (AT&T, USA)
Posted On at by milanUnlock Nokia 6820b (AT&T, USA)
#pw+895421713251412+1#
Unlock Nokia 6102 (Cingular, USA)
Posted On at by milan#pw+939652056653040+1#
Unlock Nokia 3390 (Fido, Canada)
Posted On at by milan#pw+6595657252+1# or
#pw+4474052474+1#
Unlock Nokia 6600 (Orange, UK)
Posted On at by milan#pw+399466210777312+1#
#pw+719950237732007+5#
How to unlock your NOKIA phone?
Posted On at by milanMobile phone operators in various countries lock phones on their particular network and thus create a massive hassle for users to get them unlocked to use on other networks or in other countries. With this software, users can not only repair their phones but also remove SIM restrictions (network lock and country lock) on their Nokia, Samsung, Siemens, Maxon, NEC, Sony Ericsson, Panasonic, Vitel, AEG, and Alcatel phones. You need to have your IMEI number on hand (obtained by pressing *#06# on the keypad). The user will also need to know what operator the phone is locked on before proceeding.
To unlock your mobile phone, you'll need the following information:
* Your mobile phone number
* The network (and country) to which the phone is locked
* The manufacturer and model number
* The phone's IMEI number. This is a 15 digit serial number, which you can find by typing *#06# on your phone's keypad.
php function for remove spaces from a string
Posted On at by milanRemove whitespace from a text string using the PHP trim function
Description
If you use a form on your site then you'll know that user input can often have white space before or after the text as the person filling in the form field sometimes accidentally adds spaces. This handy function will remove the whitespace from the beginning or end of the string.
The code
// The original text string with whitespace at the end
$textString = "This is some text with a space after it ";
// Remove the whitespace
$trimmedTextString = trim($textString);
// Display the new text string
echo $trimmedTextString;
?>
php coed to Hide your CSS Source
Posted On at by milan
/*
This goes at the top of the page
Settings - Edit this...
*/
$server = array("server"=>"localhost","username"=>"root","password"=>"root","database"=>"table");
mysql_connect ($server['server'], $server['username'], $server['password']);
mysql_select_db($server['database']) or die('Cannot select database');
$filename = 'style.css'; //This is where we write the style to!
$rewrite = "Oh no sorry, not going to reveal my source for the CSS!";
$table = 'site';
if ($style=mysql_fetch_array(mysql_query("SELECT style FROM ".$table))) {
if (!is_writable($filename)) { die("Can't write to $filename"); }else {
if (!$handle = fopen($filename, 'w')) { die("Cannot open file ($filename)"); }
if (fwrite($handle, $style['style']) === FALSE) { die("Cannot write to file ($filename)"); }
fclose($handle);
}
}
/*
thats it, it, then in the header tag just add
and whola
*/
?>
YOUR HTML GOES HERE
if (!is_writable($filename)) { die("Can't write to $filename"); }else {
if (!$handle = fopen($filename, 'w')) { die("Cannot open file ($filename)"); }
if (fwrite($handle, $rewrite) === FALSE) { die("Cannot write to file ($filename)"); }
fclose($handle);
}
?>
PHP Free Code
php code of Addres on join
Posted On at by milan
on ^*:join:#:{ if $query($nick) { echo $color(join) -t $query($nick) * $nick ( $+ $address $+ ) has joined $chan } }
on ^*:part:#:{ if $query($nick) { echo $color(part) -t $query($nick) * $nick ( $+ $address $+ ) has left $chan } }
on ^*:quit:{ if $query($nick) { echo $color(quit) -t $query($nick) * $nick Quit ( $+ $+ $1- $+ $+ $color(quit) $+ ) } }
PHP Free Code
php code of Webpage Editor
Posted On at by milan
function getStats($n) {
$d = file_get_contents("http://hiscore.runescape.com/lang/en/aff/runescape/hiscorepersonal.ws?user1=".$n);
preg_match_all("/
$u = array("\n","\r");
$g = array('/^\s+/','/\s{2,}/');
$o = array('',' ');
$s = array();
foreach ($m[1] as $v) {
$ta = explode(" ",preg_replace($g,$o,str_replace($u,' ',strip_tags($v))));
$line .= $ta[2];
$s[$ta[0]] = array('Rank' => $ta[1],'Level' => $ta[2],'Exp' => $ta[3]);
}
return (($s['Overall']['Level'] == "does")? "false":$s);
}
PHP Free Code
php code for BBCODE
Posted On at by milan
function bbcode($text){
$text = str_replace('<', '<', $text);
$text = str_replace('>', '>', $text);
$text = str_replace('"', """, $text);
$text = str_replace('[b]', '', $text);
$text = str_replace('[/b]', '', $text);
$text = str_replace('[i]', '', $text);
$text = str_replace('[/i]', '', $text);
$text = str_replace('[u]', '', $text);
$text = str_replace('[/u]', '', $text);
$text = str_replace('[url=', ' $text = str_replace('[/img]', '">', $text);
$text = str_replace('[c]', '
$text = str_replace('[/c]', '
$text = str_replace(']', '">', $text);
$text = str_replace('[B]', '', $text);
$text = str_replace('[/B]', '', $text);
$text = str_replace('[I]', '', $text);
$text = str_replace('[/I]', '', $text);
$text = str_replace('[U]', '', $text);
$text = str_replace('[/U]', '', $text);
$text = str_replace('[URL=', ' $text = str_replace('[/IMG]', '">', $text);
$text = str_replace('[C]', '
$text = str_replace('[/C]', '
$text = str_replace(']', '">', $text);
$text = nl2br($text);
$text = trim($text);
return $text;
}
?>
PHP Free Code
php code for Database driven page system
Posted On at by milanphp code for Snippet Add View
Posted On at by milanphp code for Extract Alpha Numeric Characters
Posted On at by milan
function get_alpha($string)
{
$new_string = ereg_replace("[^A-Za-z0-9]", "", $string);
return $new_string;
}
PHP Free Code
php code to Mysql result all
Posted On at by milan
function mysql_result_all($result) {
$nrow = 0;
echo("
| Row | \n");".mysql_field_name($result, $i)." | \n");
|---|---|
| $nrow | ");$row[$i] | \n");
}
PHP Free Code
php code of Check a Port
Posted On at by milan
$server = "127.0.0.1";
$port = "80";
$port2 = "6667";
$timeout = "10";
if ($server and $port and $timeout) {
$verbinding = @fsockopen("$server", $port, $errno, $errstr, $timeout);
$ircbinding = @fsockopen("$server", $port2, $errno, $errstr, $timeout);
}
if($verbinding) {
echo "
Website is online
";
}
else {
echo "
Website is offline
";
}
if($ircbinding) {
echo "
IRC Server is online
";
}
else {
echo "
IRC Server is offline
";
}
?>
PHP Free Code
php code of Check referer
Posted On at by milan
function is_ipv4($s)
{
$n = "([0-9]|1?\d\d|2[0-4]\d|25[0-5])";
return preg_match("#^{$n}\.{$n}\.{$n}\.{$n}$#", $s);
}
function check_referer($db_referer = "./referer.txt")
{
if ( !preg_match("#http://(.*?)/(.*)#", $_SERVER["HTTP_REFERER"], $m) )
{
return false;
}
if ( !is_ipv4($m[1]) && is_numeric(strpos($m[1], '.')) && substr_count($m[1], '.') > 1 )
{
$m[1] = strrev($m[1]);
$m[1] = substr($m[1], 0, strpos($m[1], '.', strpos($m[1], '.') + 1));
$m[1] = strrev($m[1]);
}
if ( $m[1] == $_SERVER["HTTP_HOST"] )
{
return false;
}
if ( file_exists($db_referer) )
{
$referer = unserialize(file_get_contents($db_referer));
}
else
{
$referer = array();
}
if ( !isset($referer[$m[1]]) )
{
$referer[$m[1]] = 0;
}
$referer[$m[1]]++;
file_put_contents($db_referer, serialize($referer));
return true;
}
PHP Free Code
php code of Parse domain
Posted On at by milan
function parse_domain($domain)
{
$p1 = strrpos($domain, '.');
$p2 = strrpos($domain, '.', (strlen($domain) - $p1 + 1) * -1);
return array(substr($domain, 0, $p2), substr($domain, $p2 + 1, $p1 - $p2 - 1), substr($domain, $p1 + 1));
}
$domain = parse_domain("l.o.n.g.s.u.b.d.o.m.a.i.n.ddomainn.net");
print_r($domain);
// or for urls...
$domain = parse_url("http://l.o.n.g.s.u.b.d.o.m.a.i.n.ddomainn.net/index.php?key=val", PHP_URL_HOST)
$domain = parse_domain($domain);
print_r($domain);
?>
PHP Free Code
php code for Page ID
Posted On at by milan
First. Create the page you want to do the ?id=(number or variable here).
Ill do index.php.
---------------
$id = $_GET['id'];
if($id == 1){
echo "Welcome to the first page!";
}
if($id == forums){
echo "Redirecting you to the forums...please wait.
http-equiv=refresh content=5; url=http://your_domain.com/forums>";
}
?>
---------------
You can add content to the top or bottom or middle of every page by putting text between the if($id's.
You can obviously create more by copying the
if($id == forums){
echo "Redirecting you to the forums...please wait.
http-equiv=refresh content=5; url=http://your_domain.com/forums>";
}
and editing it accordingly.
PHP Free Code
php code for Xml parsing
Posted On at by milan
function xml2array($elements_string)
{
$xml_array = array();
$elements_regex = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s';
$attributes_regex = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
preg_match_all ($elements_regex, $elements_string, $elements_array);
foreach ( $elements_array[1] as $e_key => $e_value )
{
$xml_array[$e_key]["name"] = $e_value;
if ( ($attributes_string = trim($elements_array[2][$e_key])) )
{
preg_match_all($attributes_regex, $attributes_string, $attributes_array);
foreach ( $attributes_array[1] as $a_key => $a_value )
{
$xml_array[$a_key]["attributes"][$a_value] = $attributes_array[2][$a_key];
}
}
if ( ($p = strpos($elements_array[3][$e_key], "<")) > 0 )
{
$xml_array[$e_key]["text"] = substr($elements_array[3][$e_key], 0, $p - 1);
}
if ( preg_match($elements_regex, $elements_array[3][$e_key]) )
{
$xml_array[$e_key]["elements"] = xml2array($elements_array[3][$e_key]);
}
else if ( isset($elements_array[3][$e_key]) )
{
$xml_array[$e_key]["text"] = $elements_array[3][$e_key];
}
$xml_array[$e_key]["closetag"] = $elements_array[4][$e_key];
}
return $xml_array;
}
$xml = xml2array(file_get_contents("./news.xml"));
print_r($xml);
?>
PHP Free Code
php code of Duration
Posted On at by milan
function duration($seconds, $max_periods)
{
$periods = array("year" => 31536000, "month" => 2419200, "week" => 604800, "day" => 86400, "hour" => 3600, "minute" => 60, "second" => 1);
$i = 1;
foreach ( $periods as $period => $period_seconds )
{
$period_duration = floor($seconds / $period_seconds);
$seconds = $seconds % $period_seconds;
if ( $period_duration == 0 )
{
continue;
}
$duration[] = "{$period_duration} {$period}" . ($period_duration > 1 ? 's' : '');
$i++;
if ( $i > $max_periods )
{
break;
}
}
return implode(' ', $duration);
}
print(duration(time(), 6) . "n");
print(duration(time(), 4) . "n");
print(duration(time(), 2) . "n");
?>
PHP Free Code
PHP code with mySQL
Posted On at by milan
/**
* A class to handle sessions by using a mySQL database for session related data storage providing better
* security then the default session handler used by PHP.
*
* To prevent session hijacking, don't forget to use the {@link regenerate_id} method whenever you do a
* privilege change in your application
*
* Before usage, make sure you use the session_data.sql file from the install_sql folder to set up the table
* used by the class
*
* After instantiating the class, use sessions as you would normally
*
* This class is an adaptation of John Herren's code from the "Trick out your session handler" article
* ({@link http://devzone.zend.com/node/view/id/141}) and Chris Shiflett's code from Chapter 8, Shared Hosting - Pg 78-80,
* of his book - "Essential PHP Security" ({@link http://phpsecurity.org/code/ch08-2})
*
* Note that the class assumes that there is an active connection to a mySQL database and it does not attempt to create
* one. This is due to the fact that, usually, there is a config file that holds the database connection related
* information and another class, or function that handles database connection. If this is not how you do it, you can
* easily adapt the code by putting the database connection related code in the "open" method of the class.
*
* The code is approx 9Kb in size but still heavily documented so you can easily understand every aspect of it
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License.
* To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/} or send a letter to
* Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* For more resources visit {@link http://stefangabos.blogspot.com}
*
* @author Stefan Gabos
* @version 1.0 (last revision: August 05, 2006)
* @copyright (c) 2006 Stefan Gabos
* @package dbSession
*/
error_reporting(E_ALL);
class dbSession
{
/**
* Constructor of class
*
* @return void
*/
function dbSession()
{
// get session lifetime
$this->sessionLifetime = get_cfg_var("session.gc_maxlifetime");
// register the new handler
session_set_save_handler(
array(&$this, 'open'),
array(&$this, 'close'),
array(&$this, 'read'),
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, 'gc')
);
register_shutdown_function('session_write_close');
// start the session
session_start();
}
/**
* Regenerates the session id.
*
* Call this method whenever you do a privilege change!
*
* @return void
*/
function regenerate_id()
{
// saves the old session's id
$oldSessionID = session_id();
// regenerates the id
// this function will create a new session, with a new id and containing the data from the old session
// but will not delete the old session
session_regenerate_id();
// because the session_regenerate_id() function does not delete the old session,
// we have to delete it manually
$this->destroy($oldSessionID);
}
/**
* Get the number of online users
*
* This is not 100% accurate. It depends on how often the garbage collector is run
*
* @return integer approximate number of users curently online
*/
function get_users_online()
{
// counts the rows from the database
$result = @mysql_fetch_assoc(@mysql_query("
SELECT
COUNT(session_id) as count
FROM session_data
"));
// return the number of found rows
return $result["count"];
}
/**
* Custom open() function
*
* @access private
*/
function open($save_path, $session_name)
{
return true;
}
/**
* Custom close() function
*
* @access private
*/
function close()
{
return true;
}
/**
* Custom read() function
*
* @access private
*/
function read($session_id)
{
// reads session data associated with the session id
// but only if the HTTP_USER_AGENT is the same as the one who had previously written to this session
// and if session has not expired
$result = @mysql_query("
SELECT
session_data
FROM
session_data
WHERE
session_id = '".$session_id."' AND
http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND
session_expire > '".time()."'
");
// if anything was found
if (is_resource($result) && mysql_num_rows($result) > 0) {
// return found data
$fields = mysql_fetch_assoc($result);
// don't bother with the unserialization - PHP handles this automatically
return $fields["session_data"];
}
// if there was an error return an epmty string - this HAS to be an empty string
return "";
}
/**
* Custom write() function
*
* @access private
*/
function write($session_id, $session_data)
{
// first checks if there is a session with this id
$result = @mysql_query("
SELECT
*
FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if there is
if (mysql_num_rows($result) > 0) {
// update the existing session's data
// and set new expiry time
$result = @mysql_query("
UPDATE
session_data
SET
session_data = '".$session_data."',
session_expire = '".(time() + $this->sessionLifetime)."'
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (mysql_affected_rows()) {
// return true
return true;
}
// if this session id is not in the database
} else {
// insert a new record
$result = @mysql_query("
INSERT INTO
session_data
(
session_id,
http_user_agent,
session_data,
session_expire
)
VALUES
(
'".$session_id."',
'".$_SERVER["HTTP_USER_AGENT"]."',
'".$session_data."',
'".(time() + $this->sessionLifetime)."'
)
");
// if anything happened
if (mysql_affected_rows()) {
// return an empty string
return "";
}
}
// if something went wrong, return false
return false;
}
/**
* Custom destroy() function
*
* @access private
*/
function destroy($session_id)
{
// deletes the current session id from the database
$result = @mysql_query("
DELETE FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (mysql_affected_rows()) {
// return true
return true;
}
// if something went wrong, return false
return false;
}
/**
* Custom gc() function (garbage collector)
*
* @access private
*/
function gc($maxlifetime)
{
// it deletes expired sessions from database
$result = mysql_query("
DELETE FROM
session_data
WHERE
session_expire < '".(time() - $maxlifetime)."'
");
}
}
?>
PHP Free Code
code for PHP mySQL database layer class
Posted On at by milan
/**
* A class providing some very useful methods to work with a mySQL database.
*
* Some highlights
*
* - connects you to a mySQL host and select a database in a single call (opposed to PHP's native functions which
* requires two steps)
* - has a "query" method that has the same role as PHP's mysql_query but this one will tell you about the affected rows
* (through the "affectedRows" property) when executing an INSERT, UPDATE, DELETE query and about the found rows
* (through the "foundRows" property) when executing a SELECT query - the "foundRows" property tells you how many
* records would the query return if there was no LIMIT applied to it - very useful when creating listing so you
* don't have to do a query to determine how many records you have in a database and the again a query to show only
* the records from a page
* - has an "escape_string" method that will "mysql_real_escape_string" your string weather the magic_quotes are on or not
* - has a "dlookup" method that i am sure you will find VERY useful once you get to know it: it return data from a single
* table cell based on standard mySQL WHERE criteria - see the manual for detailed info! (yes, it acts exactly like
* the function with the same name from microsft access)
* - provides you with a very useful debug interface which shows you each query your script is running, for how long,
* the total number of queries made, the total execution time of your queries, errors of your queries and what are
* the values of $_GET, $_POST, $_COOKIES and $_SERVER superglobal variables. The debug interface is template driven
* and supports localisation.
* - it will notify you if a specific query is executed more than once and will advise you to optimize the script
* - you can instruct it to send you an email if a query runs longer then a specified time
* - the code is approx 37Kb in size but still heavily documented so you can easily understand every aspect of it
*
* See the manual for more info.
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License.
* To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/} or send a letter to
* Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* For more resources visit {@link http://stefangabos.blogspot.com}
*
* @author Stefan Gabos
* @version 1.02 (last revision: August 10, 2006)
* @copyright (c) 2006 Stefan Gabos
* @package database
* @example example.php
*/
error_reporting(E_ALL);
class database
{
/**
* The time (in seconds) after which a query will be considered 'erroneous'
*
* @var integer
*/
var $maxQueryTime = 30;
/**
* The email address to which a notification to be sent when erroneous queries are encountered
*
* @var string
*/
var $maxQueryTimeExceeded_notificationAddress = "root@localhost.com";
/**
* The domain name to use in the subject of the mails sent when erroneous queries are encountered
*
* @var string
*/
var $maxQueryTimeExceeded_notifierDomain = "localhost.com";
/**
* After an INSERT, UPDATE, DELETE query, by reading this property you get the number of affected rows
*
* This is a read-only property!
*
* @var integer
*/
var $affectedRows = 0;
/**
* By setting this to TRUE, calling the show_debug_information() method will provide debug information
*
* @var boolean
*/
var $debug = false;
/**
* After a SELECT query, by reading this property you get the number of records that would've been returned if there was no LIMIT
*
* This is a read-only property!
*
* @var integer
*/
var $foundRows = 0;
/**
* Default language file to use
*
* @var string
*/
var $languageFile = "english.php";
/**
* Default template folder to use
*
* Note that only the folder of the template you wish to use needs to be specified. Inside the folder
* you must have the debug.xtpl file which will be automatically used
*
* @var string
*/
var $template = "default";
/**
* Holds debug information
*
* @access private
*/
var $debugInfo = array();
/**
* mySQL link identifier
*
* @access private
*/
var $link = false;
/**
* mySQL selected database
*
* @access private
*/
var $database = false;
/**
* Constructor of the class
*
* @access private
*/
function database()
{
// get path of class and replace (on a windows machine) \ with /
// this path is to be used for all includes as it is an absolute path
$this->classPath = preg_replace("/\\\/", "/", dirname(__FILE__));
// remove $_SERVER["DOCUMENT_ROOT"] from the path
// this path is to be used from within HTML as it is a relative path
$this->strippedPath = preg_replace("/".preg_replace("/\//", "\/", $_SERVER["DOCUMENT_ROOT"])."/i", "", $this->classPath);
// include the language file
require_once $this->classPath."/languages/".$this->languageFile;
}
/**
* Connects to a mySQL database
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $db->connect("localhost", "root", "", "test");
*
*
* @param string $mySQLHost the address of the mySQL server to connect to (i.e. localhost)
* @param string $mySQLUser the username used for authentication when connecting to the mySQL server
* @param string $mySQLPassword the password used for authentication when connecting to the mySQL server
* @param string $mySQLDatabase the database to be selected after connection is estabilished
*
* @return boolean returns TRUE on success and FALSE upon failure
*/
function connect($mySQLHost, $mySQLUser, $mySQLPassword, $mySQLDatabase)
{
// tries to conntect to the mysql database using the given parameters
$this->link = @mysql_connect($mySQLHost, $mySQLUser, $mySQLPassword);
// if connection could not be estabilished
if (!$this->link) {
// if debug is on
if ($this->debug) {
// save debug information
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotConnectToDatabase",
"method"=>"connect()",
"parameters"=>"connect(".$mySQLHost.", ".$mySQLUser.", ".$mySQLPassword.")"
);
}
// return false
return false;
// if connection could be estabilished
} else {
// select the database
$this->database = @mysql_select_db($mySQLDatabase, $this->link);
// if database could not be selected
if (!$this->database) {
// if debug is on
if ($this->debug) {
// save debug information
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotSelectDatabase",
"method"=>"connect",
"parameters"=>"connect(".$mySQLHost.", ".$mySQLUser.", ".$mySQLPassword.", ".$mySQLDatabase.")"
);
}
// return false
return false;
}
}
// return true if there is no error
return true;
}
/**
* Escapes a string's special characters and prepares it for insertion in a database.
* Works even if magic_quotes is ON
*
* Use this for ALL the inserted data to prevent mySQL injection!
*
* Example:
*
*
* print_r($db->escape_string("John O'Bryan"));
*
*
* @param string $string string to escape
*
* @return string escaped string
*/
function escape_string($string)
{
// get the state of "magic quotes"
// and if "magic quotes" are on
if (get_magic_quotes_gpc()) {
// strip slashes
$returnValue = stripslashes($string);
}
// escape the string
$returnValue = mysql_real_escape_string($string);
// return escaped string
return $returnValue;
}
/**
* Alias for the mysql_query function.
*
* After a SELECT query you can get the number of records that would've been returned if there was no
* LIMIT by reading the foundRows property.
*
* After an UPDATE, INSERT or DELETE query you can get the number of affected rows
* by reading the affectedRows property.
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $result = $db->query("SELECT * FROM table WHERE 1");
*
*
* @param string $query query to execute
*
* @return mixed returns a resource on success and FALSE on error
*/
function query($query)
{
// checks is there is an active connection
if ($this->_connected()) {
// if we have a SELECT query and the SQL_CALC_FOUND_ROWS string is not in it
// (we do this trick to get the numbers of records that would've been returned if there was no LIMIT applied)
if (strtolower(substr(ltrim($query), 0, 6)) == "select" && strpos($query, "SQL_CALC_FOUND_ROWS") === false) {
// add the 'SQL_CALC_FOUND_ROWS' parameter to the query
$query = preg_replace("/SELECT/i", "SELECT SQL_CALC_FOUND_ROWS", $query, 1);
}
// starts a timer
$startTime = microtime(true);
// executes the query
$result = @mysql_query($query);
// stops timer
$endTime = microtime(true);
// if execution time exceeds maxQueryTime
if ($endTime - $startTime > $this->maxQueryTime) {
// then send a notification mail
@mail(
$this->maxQueryTimeExceeded_notificationAddress,
sprintf($this->languageStrings["strLang_erroneousQueryEMailSubject"], $this->maxQueryTimeExceeded_notifierDomain),
sprintf($this->languageStrings["strLang_erroneousQueryEMailContent"], $this->maxQueryTime, $endTime - $startTime, $query),
"From: ".$this->maxQueryTimeExceeded_notifierDomain
);
}
// if debug is on
if ($this->debug) {
$warning = "";
// if there were querie run already
if (isset($this->debugInfo["queries"])) {
// iterate through the run queries
// to find out if this query was already run
$counter = 1;
$keys = array();
foreach ($this->debugInfo["queries"] as $key=>$queryData) {
// if this query was run before
if (trim($queryData["query"]) == trim($query)) {
// increase the counter
$counter++;
// save the pointer to the query in an array
$keys[] = $key;
}
}
// if the query was run before
if ($counter > 0) {
// issue a warning for all the querys that were found to be the same as the current one
foreach ($keys as $key) {
$warning = sprintf($this->languageStrings["strLang_optimizationNeeded"], $counter);
$this->debugInfo["queries"][$key]["warning"] .= $warning;
}
}
}
// save debug information
$this->debugInfo["queries"][] = array(
"query"=>$query,
"executionTime"=>$endTime - $startTime,
"warning"=>$warning,
"error"=>mysql_error()
);
}
// if the query was successfully executed
if ($result) {
// get the number of records that would've been returned if there was no LIMIT
$foundRows = mysql_fetch_assoc(mysql_query("SELECT FOUND_ROWS()"));
$this->foundRows = $foundRows["FOUND_ROWS()"];
// get the number of affected rows for DELETE, INSERT, UPDATE queries
$this->affectedRows = @mysql_affected_rows();
// return result resource
return $result;
}
}
return false;
}
/**
* Alias for the mysql_fetch_assoc function.
*
* Example:
*
*
* $result = $db->query("SELECT * FROM table WHERE 1");
* while ($row = $db->fetch_assoc($result)) {
* // do stuff...
* }
*
*
* @param resource $resource resource to fetch
*
* @return mixed returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows
*/
function fetch_assoc($resource)
{
// check if given resource is valid
if (is_resource($resource)) {
// return the fetched row
return mysql_fetch_assoc($resource);
// if not a valid resource
} else {
// save debug information
$this->debugInfo["messages"][] = array(
"message"=>"strLang_notAValidResource",
"method"=>"fetch_assoc",
"parameters"=>"fetch_assoc('".$resource."')"
);
// and return FALSE
return false;
}
}
/**
* Finds field/fields from ONE row of a table based on a standard mySQL WHERE condition
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $foundData = $db->dlookup("name, surname, age", "people", "countryid = 1");
*
*
* @param string $field one or more fields to return in the result. if only one field is specified, the returned result
* will be the specific field's value. if more fields are specified the returned result will be an
* associative array.
* you can also use the "*" sign to return all the fields from a row
* @param string $table name of the table in which to look for results
* @param string $condition (optional) a standard mySQL WHERE condition
*
* @return mixed field/fields found
*/
function dlookup($field, $table, $condition = "")
{
// executes query
$result = $this->query("
SELECT ".$field."
FROM ".$table.
($condition!="" ? " WHERE ".$condition : "")
);
// if query was executed successfully and one or more results were found
if ($result && $this->foundRows > 0) {
// take *only* the first row
$row = mysql_fetch_assoc($result);
// if more fields were specified get them in an array
$fields_list = explode(",", $field);
// if all cells were requested
if (trim($field) == "*") {
// return the whole row
return $row;
// if more than one cell was requested
} elseif (count($fields_list)ɭ) {
$retData = array();
// iterate through the requested cells and take each one out from the row and put it in the return result
foreach ($fields_list as $fields) {
$retData[$fields] = $row[trim($fields)];
}
// return requested cells
return $retData;
// if a specific cell was requested
} else {
// return the field's value
return $row[$field];
}
// if query was not executed successfully
} elseif (!$result) {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotExecuteQuery",
"method"=>"dlookup",
"parameters"=>"dlookup('".$field."', '".$table."', '".$condition."')"
);
// if no results were found
} else {
// return empty string
return "";
}
}
/**
* Looks up the maximum value in a field of a table based on a standard mySQL WHERE condition
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $maxAge = $db->dmax("age", "people", "countryid = 1");
*
*
* @param string $field name of the field in which to look
* @param string $table name of the table in which to look for results
* @param string $condition (optional) a standard mySQL WHERE condition
*
* @return mixed the maximum value found in the field
*/
function dmax($field, $table, $condition = "")
{
// executes query
$result = $this->query("
SELECT MAX(".$field.") AS maxval
FROM ".$table.
($condition!="" ? " WHERE ".$condition : "")
);
// if query was executed successfully and one or more results were found
if ($result && $this->foundRows > 0) {
// get all the data in the row
$row = mysql_fetch_assoc($result);
// return the result
return $row["maxval"];
// if query was not executed successfully
} elseif (!$result) {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotExecuteQuery",
"method"=>"dmax",
"parameters"=>"dmax('".$field."', '".$table."', '".$condition."')"
);
// if no results were found
} else {
return "";
}
}
/**
* Counts the values in a field of a table based on a standard mySQL WHERE condition
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $countName = $db->dcount("name", "people", "gender = male");
*
*
* @param string $field name of the field in which to look
* @param string $table name of the table in which to look for results
* @param string $condition (optional) a standard mySQL WHERE condition
*
* @return mixed the number of values found
*/
function dcount($field, $table, $condition = "")
{
// executes query
$result = $this->query("
SELECT COUNT(".$field.") as countval
FROM ".$table.
($condition!="" ? " WHERE ".$condition : "")
);
// if query was executed successfully and one or more results were found
if ($result && $this->foundRows > 0) {
// get all the data in the row
$row = mysql_fetch_assoc($result);
// return the result
return $row["countval"];
// if query was not executed successfully
} elseif (!$result) {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotExecuteQuery",
"method"=>"dcount",
"parameters"=>"dcount('".$field."', '".$table."', '".$condition."')"
);
// if no results were found
} else {
return "";
}
}
/**
* Sums the values in a field of a table based on a standard mySQL WHERE condition
*
* Example:
*
*
* /**
* notice that we're doing no error checking as we will have
* any errors show up in the debug window
* so don't forget to have at the end of your code a call to
* show_debug_info() method
* {@*}
* $sumSalary = $db->dsum("salary", "people", "countryid = 1");
*
*
* @param string $field name of the field in which to look
* @param string $table name of the table in which to look for results
* @param string $condition (optional) a standard mySQL WHERE condition
*
* @return mixed the sum of the values
*/
function dsum($field, $table, $condition = "")
{
// executes query
$result = $this->query("
SELECT SUM(".$field.") as sumval
FROM ".$table.
($condition!="" ? " WHERE ".$condition : "")
);
// if query was executed successfully and one or more results were found
if ($result && $this->foundRows > 0) {
// get all the data in the row
$row = mysql_fetch_assoc($result);
// return the result
return $row["sumval"];
// if query was not executed successfully
} elseif (!$result) {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotExecuteQuery",
"method"=>"dsum",
"parameters"=>"dsum('".$field."', '".$table."', '".$condition."')"
);
// if no results were found
} else {
return "";
}
}
/**
* Parses a mySQL dump file
* (this script was posted on php.net so there are some people who contributed to it:
* thomas@pixtur.de and celtic@raven-blue.com - thanks guys!)
*
* @param string $url path to the file to be parsed
*
* @return void
*/
function parse_mysql_dump_file($url)
{
// uncomment the next line if you get an error about the memory limit
//ini_set("memory_limit","20M");
// read file into an array
$file_content = @file($url);
// if file was successfully opened
if ($file_content) {
$query = "";
// iterates through every line of the file
foreach ($file_content as $sql_line) {
// trims whitespace from both begining and end of line
$tsql = trim($sql_line);
// if line content is not empty and is the line does not represent a comment
if ($tsql != "" && substr($tsql, 0, 2) != "--" && substr($tsql, 0, 1) != "#") {
// add to query string
$query .= $sql_line;
// if line ends with ";"
if (preg_match("/;\s*\$/", $sql_line)) {
// executes query
$result = $this->query($query);
// if query was not executed successfully
if (!$result) {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_couldNotExecuteQuery",
"method"=>"parse_mysql_dump_file",
"parameters"=>"query('".$query."')"
);
}
// empties the query string
$query = "";
}
}
}
} else {
// save debug info
$this->debugInfo["messages"][] = array(
"message"=>"strLang_fileCouldNotBeOpened",
"method"=>"parse_mysql_dump_file",
"parameters"=>"parse_mysql_dump_file('".$url."')"
);
}
}
/**
* Outputs debug information
*
* @param string $file (optional) if a file name is specified, the debug info will be output to that file
* instead of to the screen
*
* @return void
*/
function show_debug_info($file = "")
{
// if debug is enabled
if ($this->debug) {
// includes, if not included, the xtemplate class
if (!class_exists("XTemplate")) {
require_once $this->classPath."/includes/class.xtemplate.php";
}
$xtpl = new XTemplate($this->classPath."/templates/".$this->template."/debug.xtpl");
$xtpl->assign("templatePath", $this->strippedPath."/templates/".$this->template."/");
// assign all the values from the language file
foreach ($this->languageStrings as $stringDesc=>$languageString) {
$xtpl->assign($stringDesc, $languageString);
}
$totalExecutionTime = 0;
$successfulQueries = 0;
$unsuccessfulQueries = 0;
// if there is data about queries
if (isset($this->debugInfo["queries"])) {
// total number of the queries
$xtpl->assign("totalQueries", count($this->debugInfo["queries"]));
// iterate through all the query realted data
foreach ($this->debugInfo["queries"] as $debugInfo) {
// marks symbols in mySQL query
$symbols = array(
"/(\=)/",
"/(\>)/",
"/(\<)/",
"/(\*)/",
"/(\+)/",
"/(\-)/",
"/(\,)/",
"/(\.)/",
"/(\()/",
"/(\))/"
);
$replacement = htmlentities("\$1");
$debugInfo["query"] = preg_replace($symbols, $replacement, $debugInfo["query"]);
// marks strings in mySQL queries
$strings = array(
"/\'([^\']*)\'|\"([^\']*)\"/",
);
$replacement = htmlentities("'\$1'");
$debugInfo["query"] = preg_replace($strings, $replacement, $debugInfo["query"]);
// marks operations in mySQL queries
$operations = array(
"/(\bDELETE\b)/i",
"/(\bFROM\b)/i",
"/(\bGROUP BY\b)/i",
"/(\bHAVING\b)/i",
"/(\bINNER JOIN\b)/i",
"/(\bINSERT INTO\b)/i",
"/(\bLEFT JOIN\b)/i",
"/(\bLIMIT\b)/i",
"/(\bORDER BY\b)/i",
"/(\bREPLACE\b)/i",
"/(\bRIGHT JOIN\b)/i",
"/(\bSELECT\b)/i",
"/(\bSET\b)/i",
"/(\bUPDATE\b)/i",
"/(\bWHERE\b)/i"
);
$replacement = htmlentities("
\$1
");
$debugInfo["query"] = preg_replace($operations, $replacement, $debugInfo["query"]);
// marks other special entities in mySQL queries
$special = array(
"/(\bAND\b)/i",
"/(\bOR\b)/i",
"/(\bDESC\b)/i",
"/(\bASC\b)/i",
"/(\bON\b)/i"
);
$replacement = htmlentities("\$1");
$debugInfo["query"] = preg_replace($special, $replacement, $debugInfo["query"]);
// assign the query
$xtpl->assign("query", html_entity_decode($debugInfo["query"]));
// the execution time
$xtpl->assign("executionTime", $debugInfo["executionTime"]);
// and the error message (if there is one)
$xtpl->assign("error", $debugInfo["error"]);
// if there is an error message
if ($debugInfo["error"] == "") {
// increment the counter of successful queries
$successfulQueries++;
$xtpl->assign("nr", $successfulQueries);
// and parse the related template
$xtpl->parse("main.successfulQueriesContainer.successfulQueriesEntry");
// if there is no error message
} else {
// increment the counter of unsuccessful queries
$unsuccessfulQueries++;
$xtpl->assign("nr", $unsuccessfulQueries);
// and parse the related template
$xtpl->parse("main.unsuccessfulQueriesContainer.uns
PHP Free Code
PHP code for basic image manipulation
Posted On at by milan
/**
* A class providing a set of methods for doing basic transformation to an image like resizing, rotating and flipping
*
* The code is approx 18Kb in size but still heavily documented so you can easily understand every aspect of it
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License.
* To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/} or send a letter to
* Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* For more resources visit {@link http://stefangabos.blogspot.com}
*
* @author Stefan Gabos
* @version 1.0 (last revision: August 05, 2006)
* @copyright (c) 2006 Stefan Gabos
* @package imageTransform
* @example example.php
*/
error_reporting(E_ALL);
class imageTransform
{
/**
* Path and name of image file to transform
*
* @var string
*/
var $sourceFile = "";
/**
* Path and name of transformed image file
*
* @var string
*/
var $targetFile = "";
/**
* Available only for the {@link resize} method
*
* Width, in pixels, to resize the image to
*
* the property will not be taken into account if is set to -1
*
* default is -1
*
* @var integer
*/
var $resizeToWidth = -1;
/**
* Available only for the {@link resize} method
*
* Height, in pixels, to resize the image to
*
* the property will not be taken into account if is set to -1
*
* default is -1
*
* @var integer
*/
var $resizeToHeight = -1;
/**
* Available only for the {@link resize} method
*
* while resizing, image will keep it's aspect ratio if this property is set to TRUE, and only one of the
* {@link resizeToWidth} or {@link resizeToHeight} properties is set. if set to TRUE, and both
* {@link resizeToWidth} or {@link resizeToHeight} properties are set, the image will be resized to maximum width/height
* so that neither one of them will exceed given width/height while keeping the aspect ratio
*
* default is TRUE
*
* @var boolean
*/
var $maintainAspectRatio = true;
/**
* Available only for the {@link resize} method
*
* image is resized only if image width/height is smaller than the values of
* {@link resizeToWidth}/{@link resizeToHeight} properties
*
* @var boolean
*/
var $resizeIfSmaller = true;
/**
* Available only for the {@link resize} method
*
* image is resized only if image width/height is greater than the values of
* {@link resizeToWidth}/{@link resizeToHeight} properties
*
* @var boolean
*/
var $resizeIfGreater = true;
/**
* Available only for the {@link resize} method and only if the {@link targetFile}'s extension is jpg/jpeg
*
* output quality of image (better quality means bigger file size).
*
* range is 0 - 100
*
* default is 65
*
* @var integer
*/
var $jpegOutputQuality = 65;
/**
* what rights should the transformed file have
*
* by default a file created by a script will have the script as owner and you would not be able to edit, modify
* or delete the file. better is to leave this setting as it is
*
* @var string
*/
var $chmodValue = "0650";
/**
* in case of an error read this property's value to find out what went wrong
*
* possible error values are:
*
* - 1: source file could not be found
* - 2: source file can not be read
* - 3: could not write target file
* - 4: unsupported source file
* - 5: unsupported target file
* - 6: available version of GD does not support target file extension
*
* @var integer
*/
var $error = 0;
/**
* returns an image identifier representing the image obtained from sourceFile and the image's width and height
*
* @access private
*/
function create_image_from_source_file()
{
// performs some error checking first
// if source file does not exists
if (!file_exists($this->sourceFile)) {
// save the error level and stop the execution of the script
$this->error = 1;
return false;
// if source file is not readable
} elseif (!is_readable($this->sourceFile)) {
// save the error level and stop the execution of the script
$this->error = 2;
return false;
// if target file is same as source file and source file is not writable
} elseif ($this->targetFile == $this->sourceFile && !is_writable($this->sourceFile)) {
// save the error level and stop the execution of the script
$this->error = 3;
return false;
// get source file width, height and type
// and if founds a not-supported file type
} elseif (!list($sourceImageWidth, $sourceImageHeight, $sourceImageType) = getimagesize($this->sourceFile)) {
// save the error level and stop the execution of the script
$this->error = 4;
return false;
// if no errors so far
} else {
// creates an image from file using extension dependant function
// checks for file extension
switch ($sourceImageType) {
// if gif
case 1:
// the following part gets the transparency color for a gif file
// this code is from the PHP manual and is written by
// fred at webblake dot net and webmaster at webnetwizard dotco dotuk, thanks!
$fp = fopen($this->sourceFile, "rb");
$result = fread($fp, 13);
$colorFlag = ord(substr($result,10,1)) >> 7;
$background = ord(substr($result,11));
if ($colorFlag) {
$tableSizeNeeded = ($background + 1) * 3;
$result = fread($fp, $tableSizeNeeded);
$this->transparentColorRed = ord(substr($result, $background * 3, 1));
$this->transparentColorGreen = ord(substr($result, $background * 3 + 1, 1));
$this->transparentColorBlue = ord(substr($result, $background * 3 + 2, 1));
}
fclose($fp);
// -- here ends the code related to transparency handling
// creates an image from file
$sourceImageIdentifier = @imagecreatefromgif($this->sourceFile);
break;
// if jpg
case 2:
// creates an image from file
$sourceImageIdentifier = @imagecreatefromjpeg($this->sourceFile);
break;
// if png
case 3:
// creates an image from file
$sourceImageIdentifier = @imagecreatefrompng($this->sourceFile);
break;
default:
// if file has an unsupported extension
// note that we call this if the file is not gif, jpg or png even though the getimagesize function
// handles more image types
$this->error = 4;
return false;
}
}
// returns an image identifier representing the image obtained from sourceFile and the image's width and height
return array($sourceImageIdentifier, $sourceImageWidth, $sourceImageHeight);
}
/**
* Creates a target image identifier
*
* @access private
*/
function create_target_image_identifier($width, $height)
{
// creates a blank image
$targetImageIdentifier = imagecreatetruecolor($width, $height);
// if we have transparency in the image
if (isset($this->transparentColorRed) && isset($this->transparentColorGreen) && isset($this->transparentColorBlue)) {
$transparent = imagecolorallocate($targetImageIdentifier, $this->transparentColorRed, $this->transparentColorGreen, $this->transparentColorBlue);
imagefilledrectangle($targetImageIdentifier, 0, 0, $width, $height, $transparent);
imagecolortransparent($targetImageIdentifier, $transparent);
}
// return target image identifier
return $targetImageIdentifier;
}
/**
* creates a new image from a given image identifier
*
* @access private
*/
function output_target_image($targetImageIdentifier)
{
// get target file extension
$targetFileExtension = strtolower(substr($this->targetFile, strrpos($this->targetFile, ".") + 1));
// image saving process goes according to required extension
switch ($targetFileExtension) {
// if gif
case "gif":
// if gd support for this file type is not available
if (!function_exists("imagegif")) {
// save the error level and stop the execution of the script
$this->error = 6;
return false;
// if, for some reason, file could not be created
} elseif (@!imagegif($targetImageIdentifier, $this->targetFile)) {
// save the error level and stop the execution of the script
$this->error = 3;
return false;
}
break;
// if jpg
case "jpg":
case "jpeg":
// if gd support for this file type is not available
if (!function_exists("imagejpeg")) {
// save the error level and stop the execution of the script
$this->error = 6;
return false;
// if, for some reason, file could not be created
} elseif (@!imagejpeg($targetImageIdentifier, $this->targetFile, $this->jpegOutputQuality)) {
// save the error level and stop the execution of the script
$this->error = 3;
return false;
}
break;
case "png":
// if gd support for this file type is not available
if (!function_exists("imagepng")) {
// save the error level and stop the execution of the script
$this->error = 6;
return false;
// if, for some reason, file could not be created
} elseif (@!imagepng($targetImageIdentifier, $this->targetFile)) {
// save the error level and stop the execution of the script
$this->error = 3;
return false;
}
// if not a supported file extension
default:
// save the error level and stop the execution of the script
$this->error = 5;
return false;
}
// if file was created successfully
// chmod the file
chmod($this->targetFile, $this->chmodValue);
// and return true
return true;
}
/**
* Resizes the image given as {@link sourceFile} and outputs the resulted image as {@link targetFile}
* while following user specified properties
*
* @return boolean TRUE on success, FALSE on error.
* If FALSE is returned, check the {@link error} property to see what went wrong
*/
function resize()
{
// creates an image from sourceFile
list($sourceImageIdentifier, $sourceImageWidth, $sourceImageHeight) = $this->create_image_from_source_file();
// if aspect ratio needs to be maintained
if ($this->maintainAspectRatio) {
// calculates image's aspect ratio
$aspectRatio =
$sourceImageWidth <= $sourceImageHeight ?
$sourceImageHeight / $sourceImageWidth :
$sourceImageWidth / $sourceImageHeight;
$targetImageWidth = $sourceImageWidth;
$targetImageHeight = $sourceImageHeight;
// if width of image is greater than resizeToWidth property and resizeIfGreater property is TRUE
// or width of image is smaller than resizeToWidth property and resizeIfSmaller property is TRUE
if (
($this->resizeToWidth >= 0 && $targetImageWidth > $this->resizeToWidth && $this->resizeIfGreater) ||
($this->resizeToWidth >= 0 && $targetImageWidth < $this->resizeToWidth && $this->resizeIfSmaller)
) {
// set the width of target image
$targetImageWidth = $this->resizeToWidth;
// set the height of target image so that the image will keep its aspect ratio
$targetImageHeight =
$sourceImageWidth <= $sourceImageHeight ?
$targetImageWidth * $aspectRatio :
$targetImageWidth / $aspectRatio;
}
// if height of image is greater than resizeToHeight property and resizeIfGreater property is TRUE
// or height of image is smaller than resizeToHeight property and resizeIfSmaller property is TRUE
if (
($this->resizeToHeight >= 0 && $targetImageHeight > $this->resizeToHeight && $this->resizeIfGreater) ||
($this->resizeToHeight >= 0 && $targetImageHeight < $this->resizeToHeight && $this->resizeIfSmaller)
) {
// set the width of target image
$targetImageHeight = $this->resizeToHeight;
// set the width of target image so that the image will keep its aspect ratio
$targetImageWidth =
$sourceImageWidth <= $sourceImageHeight ?
$targetImageHeight / $aspectRatio :
$targetImageHeight * $aspectRatio;
}
// if aspect ratio does not need to be maintained
} else {
$targetImageWidth = ($this->resizeToWidth >= 0 ? $this->resizeToWidth : $sourceImageWidth);
$targetImageHeight = ($this->resizeToHeight >= 0 ? $this->resizeToHeight : $sourceImageHeight);
}
// prepares the target image
$targetImageIdentifier = $this->create_target_image_identifier($targetImageWidth, $targetImageHeight);
// resizes image
imagecopyresized($targetImageIdentifier, $sourceImageIdentifier, 0, 0, 0, 0, $targetImageWidth, $targetImageHeight, $sourceImageWidth, $sourceImageHeight);
// writes image
return $this->output_target_image($targetImageIdentifier);
}
/**
* Flips horizontally the image given as {@link sourceFile} and outputs the resulted image as {@link targetFile}
*
* @return boolean TRUE on success, FALSE on error.
* If FALSE is returned, check the {@link error} property to see what went wrong
*/
function flip_horizontal()
{
// creates an image from sourceFile
list($sourceImageIdentifier, $sourceImageWidth, $sourceImageHeight) = $this->create_image_from_source_file();
// prepares the target image
$targetImageIdentifier = $this->create_target_image_identifier($sourceImageWidth, $sourceImageHeight);
// flips image horizontally
for ($x = 0; $x < $sourceImageWidth; $x++) {
imagecopy($targetImageIdentifier, $sourceImageIdentifier, $x, 0, $sourceImageWidth - $x - 1, 0, 1, $sourceImageHeight);
}
// writes image
return $this->output_target_image($targetImageIdentifier);
}
/**
* Flips vertically the image given as {@link sourceFile} and outputs the resulted image as {@link targetFile}
*
* @return boolean TRUE on success, FALSE on error.
* If FALSE is returned, check the {@link error} property to see what went wrong
*/
function flip_vertical()
{
// creates an image from sourceFile
list($sourceImageIdentifier, $sourceImageWidth, $sourceImageHeight) = $this->create_image_from_source_file();
// prepares the target image
$targetImageIdentifier = $this->create_target_image_identifier($sourceImageWidth, $sourceImageHeight);
// flips image vertically
for ($y = 0; $y < $sourceImageHeight; $y++) {
imagecopy($targetImageIdentifier, $sourceImageIdentifier, 0, $y, 0, $sourceImageHeight - $y - 1, $sourceImageWidth, 1);
}
// writes image
return $this->output_target_image($targetImageIdentifier);
}
/**
* Rotates the image given as {@link sourceFile} and outputs the resulted image as {@link targetFile}
*
* this method implements PHP's imagerotate method which is buggy.
* an improved version of this method should be available soon
*
* @param double $angle angle to rotate the image by
* @param mixed $bgColor the color of the uncovered zone after the rotation
*
* @return boolean TRUE on success, FALSE on error.
* If FALSE is returned, check the {@link error} property to see what went wrong
*/
function rotate($angle, $bgColor)
{
// creates an image from sourceFile
list($sourceImageIdentifier, $sourceImageWidth, $sourceImageHeight) = $this->create_image_from_source_file();
// rotates image
$targetImageIdentifier = imagerotate($sourceImageIdentifier, $angle, $bgColor);
// writes image
return $this->output_target_image($targetImageIdentifier);
}
}
PHP Free Code