Saturday, January 24, 2009

Php - Calculating Price Ranges Dynamicaly if minimum and maximum values are given.

Calculating Price Ranges Dynamicaly if minimum and maximum values are given.
In these example display 5 types of ranges


<?php
//Find Minimum and Maximum Values
$min = 20.55;//Minimum Price
$max = 10000.89;//Maximum Price
$numofRanges = 5;
//Split the numbers in to 5 price ranges
/*For eg
Price 20$ -----------200$
200$-----------400$
400$-----------600$
*/
$value = (float)($max/$numofRanges);
//Find the value to increment
$range = array();
$min_temp = $min;
for(
$i=1;$i<=$numofRanges;$i++)
{
$temp = $min + $value;
if(
$temp > $max)
{
$temp = $max;
}
if(
$min_temp != $min)
{
$min_temp = round($min_temp);
}
if(
$temp != $max)
{
$temp = round($temp);
}
$range["$min_temp"] = $temp;
$min_temp = $temp;
$min_temp += 1;
$min = $temp;
}
$str = '';
foreach(
$range as $min=>$max)
{
$str .= $min."\$--------------".$max."\$";
$str .= "<br/>";
}
echo
"<h3>Price Ranges</h3>";
echo
$str;

?>

Thursday, January 22, 2009

Php - how to switch css style sheet of a web page

Php - how to switch css style sheet of a web page

<?php
session_start();
$all_css = array();

$all_css['yellow']['file'] = "home_geel.css";
$all_css['blue']['file'] = "home_blauw.css";
$all_css['modern']['file'] = "home_modern.css"; // default

$all_css['yellow']['label'] = "Yellow!";
$all_css['blue']['label'] = "Deep blue";
$all_css['modern']['label'] = "Final..."; // default

$default_value = "modern"; // set the default value here

if (isset($_GET['change_css']) && $_GET['change_css'] != "") {
    $_SESSION['css'] = $_GET['change_css'];
} else {
    $_SESSION['css'] = (!isset($_SESSION['css'])) ? $default_value : $_SESSION['css'];
}
switch ($_SESSION['css']) {
    case "yellow":
    $css_file = "home_geel.css";
    break;
    case "blue":
    $css_file = "home_blauw.css";
    break;
    default:
    $css_file = "home_modern.css";
}
function style_switcher() {
    global $all_css;
    $style_links = "Style switch:&nbsp;\n";
    foreach ($all_css as $key => $val) {
        if ($_SESSION['css'] != $key) {
            $style_links .= "<a href=\"".$_SERVER['PHP_SELF']."?change_css=".$key."\">";
            $style_links .= "<b>".$val['label']."</b></a>&nbsp;&nbsp;\n";
        } else {
            $style_links .= "<b>".$val['label']."</b>&nbsp;&nbsp;\n";
        }
    }
    return $style_links;
}
?>
<!-- EXAMPLE: place this inside your html header -->
<link href="/includes/<?php echo $css_file; ?>" rel="stylesheet" type="text/css">
<!-- place this code inside the body where you want to show the links -->
<?php echo style_switcher(); ?>

Php - how to verify email address entered by user

Php - how to verify email address entered by user

Call the function like this check_email("INFO@google.co.uk"); to do server email validation using PHP

By calling this, function validate the email against the regular expression

<?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("INFO@google.co.uk");
?>

Saturday, January 17, 2009

Php - Working with checkboxes and a database

Introduction

Over in the php help forum, the question of how to deal with checkboxes arises pretty often. Usually, people want to be able to select which rows of a database to update/delete/throw out the window.

The concept is actually pretty simple. It involves naming your checkbox as an array and the use of the IN mysql clause. This tutorial aims to give a simple example in the hope that, next time someone asks, I can point them to a tutorial rather than explaining all over again.

Right, on with the show.

The Database

Seeing as we're going to be updating a database, we'll be needing a table and some data. Here's a table I made earlier:

  1. CREATE TABLE `tutorial_users` (

  2. `id` INT( 10 ) NOT NULL AUTO_INCREMENT ,

  3. `username` VARCHAR( 50 ) NOT NULL ,

  4. `admin` TINYINT( 1 ) NOT NULL DEFAULT '0',

  5. PRIMARY KEY ( `id` )

  6. ) ENGINE = MYISAM

And some data to work with. No prizes for guessing what I was just watching on TV:

  1. INSERT INTO `tutorial_users` (

  2. `id` ,

  3. `username` ,

  4. `admin`

  5. )

  6. VALUES (

  7. NULL , 'Stewie', '0'

  8. ), (

  9. NULL , 'Peter', '0'

  10. ), (

  11. NULL , 'Brian', '0'

  12. ), (

  13. NULL , 'Meg', '0'

  14. ), (

  15. NULL , 'Lois', '0'

  16. ), (

  17. NULL , 'Chris', '0'

  18. ), (

  19. NULL , 'Greased Up Deaf Guy', '0'

  20. ), (

  21. NULL , 'Quagmire', '0'

  22. );

It's a simple setup. A user's table with a field called admin, which is the field we'll be updating.

If you're the kind of guy (or gal; we're all for equal opportunities here) who likes a quick fix – the full code is on the next page. Otherwise, we'll be breaking it down on pages 4 and 5.

The Code

  1. include("connect.php");
  2. $updated = FALSE;
  3. if(count($_POST) > 0){
  4. $admin = $_POST['admin'];
  5. array_map('intval',$admin);
  6. $admin = implode(',',$admin);
  7. mysql_query("UPDATE tutorial_users SET admin=0") or trigger_error(mysql_error(),E_USER_ERROR);
  8. mysql_query("UPDATE tutorial_users SET admin=1 WHERE id IN ($admin)") or trigger_error(mysql_error(),E_USER_ERROR);
  9. $updated=TRUE;
  10. }
  11. ?>
  12. phpfreaks checkbox tutorial
  13. " method="post">
  14. if($updated===TRUE){
  15. echo '
    Privileges Updated!
    ';
  16. }
  17. ?>
  18. $sql = "SELECT id,username,admin FROM tutorial_users ORDER by id ASC";
  19. $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
  20. while(list($id,$username,$admin)=mysql_fetch_row($result)){
  21. $checked = ($admin==1) ? 'checked="checked"' : '';
  22. echo '
  23. '."\n";
  24. }
  25. ?>
  26. UsernameAdmin Privileges
    '.$username.'

Interlude

Thanks for sticking around. Before we take a closer look at that code, I just want to mention a little about checkboxes and how they work.

You're probably aware that with a lot of other form elements, such as text fields, if you leave them blank they'll still appear in the $_POST/$_GET array – just with a blank value.

On the other hand, checkboxes behave a bit more like buttons. If you don't check them, they wont appear in the array. Assuming you do tick them, they'll take the value you give them or 'on' by default. Bear that in mind, it'll be important later.

Breaking it down

I'm going to start the breakdown a little way through the code from the opening form tag, seeing as you'll have to fill in that form before you can process it.

  1. " method="post">
  2. if($updated===TRUE){
  3. echo '
    Privileges Updated!
    ';
  4. }

We have a standard form with a post method, and an action of the same page. We're also going to display a message if the database was updated – because we're nice like that.

  1. We're going to setup a table with the username and privilege listed in it. If you don't like tables, tough luck.

    1. $sql = "SELECT id,username,admin FROM tutorial_users ORDER by id ASC";
    2. $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);

    We select the fields we need from the database (not forgetting the id, as we'll use this to identify each row) and execute the query with a little error checking.

    1. while(list($id,$username,$admin)=mysql_fetch_row($result)){

    If you're not familiar with the list() construct, it allows us to assign lots of variables from a numerically indexed array in one go. I get bored of using $row all the time, so it makes a change. It's important to use mysql_fetch_row() so that you get a numerically indexed array (as opposed to an associative one) and that you create the variables with the same order you selected them in your query. See the manual page for a bit more.

    1. $checked = ($admin==1) ? 'checked="checked"' : '';
    2. echo '
    '."\n";

    Inside that loop, we first work out if the checkbox should be ticked to start with. That is, if the user currently has admin privileges. Use of the ternary operator keeps this short and sweet. We then echo out a row for each user.

    Notice that we name the checkbox admin[]. This means that $_POST['admin'] is going to be an array. An array of all the ticked boxes in fact. Also notice that we set the value to the id of the user.

  2. UsernameAdmin Privileges
    '.$username.'

Finally, we make a submit button and finish off our html. I don't know about you, but I find forms without a submit button a little unsatisfactory.

On the next page, we'll take a look at the processing.

Processing the form

  1. include("connect.php");
  2. $updated = FALSE;

First, we include a file that's going to connect us to our database. I would show you that file, but personally I prefer to keep my username and password to myself. We also create a variable that says we haven't updated the database...yet.

  1. if(count($_POST) > 0){
  2. $admin = $_POST['admin'];
  3. array_map('intval',$admin);

Our if statement ensures that this code only runs if the form has been submitted. We create a local variable from the $_POST array. We then do a little bit of validation. We don't want any nasty users modifying any of those values in our form to do some SQL injection, so we make sure every value in that array is an integer with the array_map function. Again, see the manual page if you're not too sure how this function works.

"What if I don't have integers as my values?" Good question. You might like to use mysql_real_escape_string(), like so:

  1. array_map('mysql_real_escape_string',$admin);

Or you might write your own function to make sure the values are the sort of thing you expect.

  1. $admin = implode(',',$admin);

Next, we use the implode() function to turn our array into a string. We separate each value with a comma. This will allow us to use the IN clause in a moment. If your values aren't integers, you'll have to do something different. I'll cover that in a minute.

  1. mysql_query("UPDATE users SET admin=0") or trigger_error(mysql_error(),E_USER_ERROR);
  2. mysql_query("UPDATE users SET admin=1 WHERE id IN ($admin)") or trigger_error(mysql_error(),E_USER_ERROR);
  3. $updated=TRUE;

Before we update the new users who have admin privileges, we first update the database so no-one does. Why? Well, our comma-delimited list contains just those people who we do want to have admin rights. So we better make sure no-one else does. Our second query makes use of that IN clause – it allows us to provide a comma-separate list of values that id can be.

Note: An alternative to updating every row to 0 would be to use the NOT IN clause.

Using strings

If your values are strings, you'll need to be a little more careful with your implode and query. Don't forget that all strings in your SQL must be inside quotes. It's a pretty simple adjustment, but it'll cause you an error if you forget. Make your implode look like this:

  1. $admin = implode("','",$admin);

And your query like this:

  1. mysql_query("UPDATE users SET admin=1 WHERE id IN ('$admin')") or trigger_error(mysql_error(),E_USER_ERROR);

Note the extra quotes – after we've imploded our values, they might look a little like this:

one','two','three','four

So we need to add the quote to the front and back.

We'll sum up on the last page

Summary

So there we have it. The form gets processed and reloaded with the users having the new privileges. I hope that was easy to follow and worth the effort. Next time you work with checkboxes, it should be a little easier – there's really not much more to it.

Remember to name your checkbox as an array and set its value to something that uniquely identifies the row. If that's a string, take care when you implode the data. And don't forget to validate those values too. Most users are evil. Alright, maybe not. But if you think like that, you'll save yourself more than a few headaches.

Lastly, don't forget, you can name other pieces of your form so that they are arrays. Again, this is useful for updating an unknown, large amount of data simultaneously.

Php - Object Oriented Templating using PHP

This is the templating system that I currently use on my site. Ofcourse, I make small changes to make it suit my sites.

Save as class.template.php

<?php

class Template{
    private
$cache = false;
    private
$cacheKey = NULL;
    private
$cachePeriod = 3600;
    private
$cachePath = NULL;
    private
$tplFile = NULL;
   
    function
enableCaching($key = NULL, $ttl = 3600){
       
$this->cache = true;
        if(!
is_null($key)){
           
$this->cacheKey = $key;
        }
       
$this->cachePeriod = $ttl;
    }
   
    function
disableCaching(){
       
$this->cache = false;   
    }
   
    function
setCachePath($path){
       
$this->cachePath = $path;   
    }
   
    function
getCacheFile(){
        if(
is_null($this->cachePath) || !file_exists($this->cachePath)){
           
$this->error('Invalid Cache Path.');   
        }
       
$cacheKey = is_null($this->cacheKey) ? md5($this->tplFile) : $this->cacheKey;
        return
$this->cachePath . '/' . $cacheKey;
    }
   
    function
cacheExist(){
       
$cacheFile = $this->getCacheFile();
        if(
file_exists($cacheFile) && filemtime($cacheFile) > time() - $this->cachePeriod){
            return
true;
        }else{
            return
false;
        }
    }
   
    function
getCache(){
        if(
$this->cache && $this->cacheExist()){
            echo
file_get_contents($this->getCacheFile());
            return
true;
        }else{
            return
false;
        }
    }
   
    function
setTemplate($tpl){
       
$this->tplFile = $tpl;
    }
   
    function
generate(){
        if(!
file_exists($this->tplFile)){
           
$this->error("Template File <i>$this->tplFile</i> not found.");
        }
       
extract(get_object_vars($this), EXTR_REFS | EXTR_PREFIX_ALL, 't');
        if(
$this->cache){
           
$cacheFile = $this->getCacheFile();
           
ob_start();
            include
$this->tplFile;
           
$output = ob_get_clean();
           
file_put_contents($cacheFile, $output);
            echo
$output;
        }else{
            include
$this->tplFile;
        }

    }
    function
error($message = ''){
        if(empty(
$message))$message = 'A fatal error occured. Unable to continue.';
        die(
"<b>Error</b> : $message");
    }
   
}
?>



Run the following query using phpMyAdmin to setup the database for the example script

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(5) unsigned NOT NULL auto_increment,
  `name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Lord Beckett', 'lord@beckett.com'),
(2, 'Davy Jones', 'davy@jones.com'),
(3, 'Jack Sparrow', 'jack@sparrow.com'),
(4, 'Will Turner', 'will@turner.com');



Example template file. Save as template.tpl.php. It is better to make sure that the filename ends in .php, so that it can make use of opcode caches like eaccelerator.

<html>
<head>
<title><?=$t_title?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1><?=$t_h1?></h1>
<table border="1">
<tr><td>ID</td><td>Name</td><td>Email</td></tr>
<?php foreach($t_users as $user):?>
<tr><td><?=$user['id']?></td><td><?=$user['name']?></td><td><?=$user['email']?></td></tr>
<?php endforeach;?>
</table>
</body>
</html>



Example script. Save as example.php in the same directory as the class.template.php

<?php
include 'class.template.php';
$tpl = new Template;
$tpl->setTemplate('template.tpl.php');
$tpl->enableCaching();
// Change the path to your cache path
$tpl->setCachePath('/var/www/vhosts/mysite.com/httpdocs/cache/');

if(
$tpl->getCache()){
    echo
'This was loaded from cache.';
}else{
    if(
mysql_connect('localhost', 'root', '')){
       
// Add variables to the template object as you like.
        // You can access these variables in the template file by prefixing it with t_. For example $tpl->h1 becomes $t_h1, $tpl->users becomes $t_users.
       
$tpl->title = 'My Template Example';
       
$tpl->h1 = 'Example';
       
mysql_select_db('test');
       
$result = mysql_query("SELECT * FROM `users`");
        while(
$row = mysql_fetch_assoc($result)){
           
$tpl->users[] = $row;   
        }
    }else{
       
$tpl->error('Could not connect to mysql');   
    }
   
$tpl->generate();
    echo
'This content will be saved to cache';
}

?>


Php - Embed Youtube , Metacafe Videos in your website using Php

To embed a YouTube or MetaCafe video in your webpage by providing the url of the video page. It uses regular expression to get the id of the youtube video and id and name of the Metacafe video, which is used to generate the code for embedding the video. The generated code is compatible with the code provided by Youtube and metacafe.

To embed a video, pass the url of video page to the function embedVideo.


<?php
function embedVideo($url){
    if(
preg_match("#http://(.*)\.youtube\.com/watch\?v=(.*)(&(.*))?#", $url, $matches)){
       
?>
        <object width="425" height="344">
        <param name="movie" value="http://www.youtube.com/v/<?php echo $matches[2];?>&hl=en&fs=1"></param>
        <param name="allowFullScreen" value="true"></param>
        <param name="allowscriptaccess" value="always"></param>
        <embed src="http://www.youtube.com/v/<?php echo $matches[2];?>&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>
           </object>
       <?php
   
}elseif(preg_match("#http://www\.metacafe\.com/watch/(([^/].*)/([^/].*))/?#", $url, $matches)){
       
?>
        <embed flashVars="playerVars=showStats=no|autoPlay=no|videoTitle="  src="http://www.metacafe.com/fplayer/<?php echo $matches[1];?>.swf" width="400" height="348" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed>
       <?php
   
}
}
$youtubeVideo1 = 'http://in.youtube.com/watch?v=Km7PcdMzaN4';
$youtubeVideo2 = 'http://in.youtube.com/watch?v=xNi7QwAL3XY&feature=dir';
$metacafeVideo1 = 'http://www.metacafe.com/watch/2215104/amazing_video/';
$metacafeVideo2 = 'http://www.metacafe.com/watch/2204556/sensational_cars_of_the_future/';

embedVideo($youtubeVideo1);
embedVideo($youtubeVideo2);
embedVideo($metacafeVideo1);
embedVideo($metacafeVideo2);
?>

Tuesday, January 13, 2009

Php - Making Search Engine friendly 404 Error Page

Create Custom Error Page

The default 404 error page shown by Apache is not at all helpful for a user. Fortunately, apache allows us to use our own custom 404 error pages. Some people use this feature to redirect 404 errors to their site's homepage. But this is also not useful for a user or a search engine. Some provide custom error pages that are useful for their users, but does not provide the required 404 header which can make the search engines penalize you for duplicate content. Here is a 404 custom 404 error page that will satisfy both your users and search engines. It also includes Google's custom 404 search box code.

Save the following as 404.php in your document root


<?php
// Change this to your site url
$homeUrl = 'http://www.weberdev.com/';

// Add the 404 header to not confuse search engines
header("HTTP/1.0 404 Not Found");
$arPath = explode('/', $_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>404 Error - Page not found</title>
<meta http-equiv="refresh" content="10;url=<?php echo $homeUrl;?>" />
<style type="text/css">
*{margin:0px;padding:0px;}
body{background-color:#F9F9F9;color:#111;font: normal 95%/130% "Trebuchet MS", Verdana, Arial, sans-serif;margin:0px;padding:20px 0px;}
a {color:#6699CC;text-decoration:none;border-bottom: 1px solid #EEE;}
h1{color:#333;font:normal 1.7em Georgia, "Times New Roman", Times, serif;margin:0px;padding:0px;}
h2,h3{color: #6699cc;font: normal 1.25em Georgia, "Times New Roman", Times, serif;margin: 20px 0px;padding: 0px;}
ul{margin:10px 20px;}
li{list-style:disc;}
#wrapper{background-color:#FFFFFF;border:1px solid #DDDDDD;margin:auto;width:40em;}
#header {background:#D5D5D5;border-bottom:1px solid #DDD;color:#888;font-size:85%;margin:0px;padding:3px 10px;}
#body{padding:10px;}
#goog-wm { }
#goog-wm h3.closest-match { }
#goog-wm h3.closest-match a { }
#goog-wm h3.other-things { }
#goog-wm ul li { }
#goog-wm li.search-goog { display: block; }

.comment{color:#999;}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<a style="text-transform:uppercase;" href="<?php echo $homeUrl;?>"><?php echo str_replace(array('http://', 'www.', '/'), '', $homeUrl);?></a> → Page not found</div>
<div id="body">
<h1>[404] Page not found</h1>
<p> </p>
<p>Sorry, the file <code class="comment"><?php echo $_SERVER['REQUEST_URI'];?></code> was not found on this server.</p>
<p>Please ensure that you have entered the url correctly. If you did so, then probably the file was removed from the server.</p>
<p>Please choose one of the actions from below, or you will be redirected to our homepage in 10 seconds.</p>
<ul>
<li><a href="<?php echo $homeUrl;?>">Click here to go to the homepage.</a></li>
<li><a href="javascript:history.back();">Click here to go back.</a></li>
<li><a href="<?php echo $homeUrl;?>/contact.php">Click here to contact us.</a></li>
</ul>
<div id="leftContent">
<script type="text/javascript">
  var GOOG_FIXURL_LANG = 'en';
  var GOOG_FIXURL_SITE = '<?php echo $homeUrl;?>';
</script>
<script type="text/javascript"
    src="http://linkhelp.clients.google.com/tbproxy/lh/wm/fixurl.js"></script>
</div>
</div>
</div>
</body>
</html>



Create a file .htaccess in your document root (if one does not already exist). Add the following line to the end of the file


ErrorDocument 404 /404.php



That is it. Now you have a search engine friendly and at the same time user friendly 404 error page.