Monday, August 01, 2011

Online PHP Tutorials: W3Schools PHP tutorial

Online PHP Tutorials: W3Schools PHP tutorial

Saturday, July 30, 2011

Easy PHP Date Picker

There are many fancy javascript calendars for selecting dates - for example the one that comes as a jQuery plugin is really cool. There are however some disadvantages to using such calendars:

  • If you only need a date picker, it's not worth to include all these Javascript libraries and overload.
  • These javascript calendars are hard to use from people who don't see well or can't use a mouse
  • In admin screens etc., where you may need to manage many dates in rows of records, clicking on the calendars can be much slower than picking dates from dropdown.


In cases like these and maybe more, it's better to create a simple dropdown date picker that will allow the user to select year, month and day (in fact this will be 3 dropdowns).

Let's build such a function:

First we'll build an array of months:

$months=array('','January','February','March','April','May','June','July','August',
'September','October','November','December');


Note that I inserted the first element of the array as empty because I want the month numbers to start from 1 (for January).

Then we'll construct the three dropdowns:

$html="<select name=\"".$name."month\">";
 for($i=1;$i<=12;$i++)
 {
    $html.="<option value='$i'>$months[$i]</option>";
 }
$html.="</select> ";


This was the months dropdown. Did you notice the "name" variable? We will pass it as argument to the function so we can control the name of the dropdowns and have many of them in a page. In very similar way you can create the days dropdown - from 1st to 31st.


$html.="<select name=\"".$name."day\">";
 for($i=1;$i<=31;$i++)
 {
    $html.="<option value='$i'>$i</option>";
 }
 $html.="</select> ";


The years dropdown is just as simple. The only question in it is in what year to start and when to end. Your function can accept this as arguments or you can dynamically create start and end year accordingly to the current date. For example:


$startyear = date("Y")-100;
$endyear= date("Y")+50;

 $html.="<select name=\"".$name."year\">";
 for($i=$startyear;$i<=$endyear;$i++)
 {
   $chooser.="<option value='$i'>$i</option>";
 }
 $html.="</select> "; 


You can add some javascript to increase/reduce the number of days accordingly to the month, but this can be needlessly complicated. It's easier to solve this problem by javascript validation at the time when the form is submitted.

So Here Is The Full Code (For Those Who Don't Get It):



Then put all this code into a function which accepts the argument $name:


function date_picker($name, $startyear=NULL, $endyear=NULL)
{
    if($startyear==NULL) $startyear = date("Y")-100;
    if($endyear==NULL) $endyear=date("Y")+50; 

    $months=array('','January','February','March','April','May',
    'June','July','August', 'September','October','November','December');

    // Month dropdown
    $html="<select name=\"".$name."month\">";

    for($i=1;$i<=12;$i++)
    {
       $html.="<option value='$i'>$months[$i]</option>";
    }
    $html.="</select> ";
   
    // Day dropdown
    $html.="<select name=\"".$name."day\">";
    for($i=1;$i<=31;$i++)
    {
       $html.="<option $selected value='$i'>$i</option>";
    }
    $html.="</select> ";

    // Year dropdown
    $html.="<select name=\"".$name."year\">";

    for($i=$startyear;$i<=$endyear;$i++)
    {      
      $html.="<option value='$i'>$i</option>";
    }
    $html.="</select> ";

    return $html;
}


And use the function as echo date_picker("registration") (for example - "registration" is just a name you choose). The result that will come in $_POST after submitting such form will be in 3 variables:
$_POST['registrationmonth'], $_POST['registrationday'] and $_POST['registrationyear'].

You can easily construct a MySQL date from these variables.

Now think how you can make this dropdown read stored data and pre-select its values accordingly to it (for "Edit record" forms).

Retrieving an RSS Feed in PHP

RSS Feeds are widely used throughout the internet today and on all kinds of websites. From websites like Digg to most blogs. If you want to display an RSS feed on your website its probably easier than you think.
For this example I'm going to show you how to display the RSS feed for The Tutorial Blog using PHP.

The Code

The first two lines of code that we write are going to be what retrieve the RSS feed.

$file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);

Now the next thing we do is use the foreach function so for each item found do something with it
foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}

What are code will do is simply echo the titles of all the items found within the feeds. If you also want to include a link to the feed you can do this by printing to screen $feed->link. All the code together should look something like this.

<?php $file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);
foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}
?>
Thanks for taking the time to read this tutorial. I hope you have learned something.

A Basic PHP Statistics Script

In this tutorial you will learn about writing information to a text file and then retrieving the information you wrote to the text file. Retrieving the files that are in a directory and about arrays.
This is a quite basic script and there isn't much to write about it so if there is something that you don't understand look the function up within the PHP manual online.

Step 1

In the first step we are going to get the current page that we are at and store it within a variable. The information in that variable will then be wrote to a file called stats.txt.
Include the following code in the pages that you want the number of visits to be counted for. If you have a file such as a header file than put this code in there.
<?php
 
// write current page to stats file
$cur_page = $_SERVER['REQUEST_URI'];
if(empty($cur_page)) {
 $cur_page = 'index.php';
}
$file = fopen("stats.txt", "a+");
fwrite($file, $cur_page . "\n");
fclose($file);
 
?>

Step 2

The next piece of code that we are going to write is going to retrieve the information in stats.txt and put it into an array. We then use the function array_count_values to see how many times the page url occurs. We also retrieve the files in the directory which this script is in to compare them with the files in stats.txt.
<?php
 
$file = fopen("stats.txt", "r");
$files = scandir('./');
$num_files = array();
while(!feof($file)){
 $line = fgets($file);
 $line = substr($line, 1, -1);
 $line = explode(",", $line);
 array_push($num_files, $line[0]);
}
 
 
$num_cv = array_count_values($num_files);
 
foreach($num_cv as $f => $c) {
 echo 'file: ' . $f . ' - ' . $c . '<br>';
}
 
?>
If you have any other alternatives or need any help then feel free to post a comment.

10 CakePHP Tutorials You Should Read

There are a number of frameworks available for PHP such as CodeIgnitor, Zend, Symfony, Kohana and many more. In this article you will find tutorials that I have found on the web that will help PHP programmers that are new to the MVC pattern or CakePHP. CakePHP is an amazing framework if you know how to use it, but the documentation for CakePHP is quite badly written and can cause confusion for new users. Here are a few links to try and make life easier for new and experienced CakePHP users.
  1. Validation with CakePHP
  2. Theming with CakePHP
  3. Getting started quickly with Scriptaculous effects
  4. Drag 'n drop tutorial with the CakePHP 1.2 Ajax helper, Prototype framework and Scriptaculous library
  5. Secure CakePHP via Sessions & Magic (Login / Logout)
  6. CakePHP ACL Tutorial
  7. CakePHP Bake - Baking Models, Controllers and Views the CakePHP 1.2 Way
  8. Cascading Dynamic Meta Tags and Page Titles in CakePHP 1.2
  9. jQuery image upload & crop
  10. Uploader - Plugin

PHP Class for Google Maps API

A few days ago I was developing a website for a client. They required that there be a map showing where addresses are that were retrieved from a database. I have never properly looked at the Google Maps API before because I have never needed to use it; so for the first time I looked at it and gave it a try. Then after playing around with it for a bit i realised that reverse geocoding was needed to convert the address into latitude and longitude figures.
Because I was programming this website in PHP I thought I would have a look around for a PHP class to see if there was a quicker way of doing this. Luckily enough I found a PHP class called PHP GoogleMapAPI. It took me a few minutes to read through the documentation for this class but it was so straight forward and simple. All in all it takes only 6 lines of code using this class to create a google map and locate it to an address; because it does all the other work for you that you don't need to know about if you're not going to be programming Google Maps every day of your life.

Implementing Google Maps on your website

The first thing you need to do is go to the website and download the class. Then copy it into the directory where you keep your classes stored on your server.
When you have downloaded the class, it then needs to be included in the file that we want to show the map in. At the top of your file insert the code below.
<?php
require('GoogleMapAPI.class.php');
$map = new GoogleMapAPI('map');
 
// enter YOUR Google Map Key
$map->setAPIKey('YOURGOOGLEMAPKEY');
 
$map->addMarkerByAddress('621 N 48th St # 6 Lincoln NE 68502','Our Address','<b>Our Address</b>');
 
<body onload="onLoad()">
 
    <?php $map->printMap(); ?>
 
</body>
What we are doing here is including the class with the require function in PHP. If the class fails to be included then the rest of the page will stop executing.
We then create a new instance of the class and then we insert.
If you have a Google Maps API key then insert it where it says 'YOURGOOGLEMAPKEY'. If you do not have one you can get one from here.
The function below adds a marker to the address you would like and centers it. This function takes 3 parameters; the address, a title and html.
$map->addMarkerByAddress();
We then need to include the onLoad function so that it knows to load the map on this page.
The last function that we add is
<?php $map->printMap(); ?>
Wherever you insert this function is where the map will be displayed on the page.

Let us know

I hope this tutorial has been useful and you have learned something new from it. Feel free to post a comment below and share your experience with this class or the Google Maps API.

Simple PHP Contact Form

Every website needs a way of contacting the people behind it and putting an email on a page is not such a good idea; because bots can easily pick up this email address and send spam to it. This is where a contact form comes in very useful because people can send you messages but do not get your email address.
For a contact form the first thing that we need to do is to create a form using HTML so that they can input their information and message that they are going to send.
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
When the press send it will then go to a page called send_message.php. This page will grab the information that they input and send it to an email address using the mail() function in PHP.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
mail($to, $subject, $message, "From: $email");
echo "Message sent";
?>
We need to check that the sender of the message is human so we will add a simple math question to the bottom of our form.
<?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
Don't forget to add
<?php
session_start();
?>
To the top of the page or we will get errors.
Now we check to see if they have entered information into every field and that the answer to the math question is correct, if it is the message will be sent otherwise an error will be returned.
All the code for the form is:
<?php
session_start();
?>
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
    <?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
All the code for error checking and sending the message is:
<?php
session_start();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$user_answer = $_POST['answer'];
$real_answer = $_SESSION['answer'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
if(empty($name) OR empty($email) OR empty($message)) {
 echo "Fill in all fields.";
} elseif($user_answer != $real_answer) {
 echo "Math question was incorrect, please try again";
} else {
 mail($to, $subject, $message, "From: $email");
 echo "Message sent";
}
?>
You can download the source code for this tutorial here.
Please leave your comments and suggestions below for this tutorial.