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.

Uploading files to Rackspace Cloud (Mosso) using PHP API

Rackspace Cloud is a great VPS service, but when I recently done a project it needed the functionality of uploading directly from a website to the cloud. I did not find many tutorials on how to do this, so I thought I'd write a tutorial on it myself.

Step 1: Download the required files

The files you will need for this are located at the Rackspace Cloud website here. You can download the API for PHP, Java, Python, .NET and Ruby. But for this tutorial we will be using PHP.

Step 2: Setup

When the download of the PHP API has complete decompress the file and rename it to cloudfiles. Now place the folder named cloudfiles in the directory where the PHP files will be stored that will upload to the Rackspace Cloud.

Step 3: Create an upload form

For this tutorial we will only be creating a basic upload form, but I have planned for a more advanced uploader with a progress bar and multiple file uploads for a future tutorial, so be sure to check back for that.
<form action="upload.php" enctype="multipart/form-data" method="POST">
File: <input name="upload" type="file" /> 
 
<input name="submit" type="submit" value="Upload To Rackspace!" />
</form>
Name this file upload.html

Step 4: Uploading to Rackspace Cloud

So what we need to do to upload to the Rackspace cloud is to include the PHP API, connect to Rackspace, get the container we want to use, create an object and then upload the file to that object.
<?php
// include the API
require('cloudfiles/cloudfiles.php');
 
// cloud info
$username = ""; // username
$key = ""; // api key
 
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
 
// Get the container we want to use
$container = $conn->get_container('ContainerName');
 
// store file information
$localfile = $_FILES['upload']['tmp_name'];
$filename = $_FILES['upload']['name'];
 
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
?>
Name this file upload.php.

Download

You can download the source files from here

Post comment

Please post a comment and let us know if you have anything that you'd like to add to the tutorial or if you are having any problems.

Useful websites and resources for learning CodeIgniter

.htaccess file Functionality

.htaccess file uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule, to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.
This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput.
the following links are important for .htaccess functionality

Apache Module mod_rewrite Rules

5 useful url rewriting examples using .htaccess

more .htaccess tips and tricks..

Ajax and Jquery tutorial and examples

Ajax : You’ve probably heard about Ajax before, or at least used an Ajax-based application — Gmail, for instance. Quite simply, Ajax is a technique for handling external data through JavaScript asynchronously, without reloading the entire page.
jQuery : The jQuery library has a full suite of AJAX capabilities. The functions and methods therein allow us to load data from the server without a browser page refresh.
some ajax and Jquery tutorial and example site links are given below :

Ajax Tutorial : Ajax Help and Tutorials

Ajax rich tutorial and example works site

JQuery Tutorials and example

Visual Jquery rich tutorial site

Ajax and Jquery some exclusive works site free download

PHP tutorial and important site links

PHP (Hypertext Preprocessor) is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. If you are new to PHP and want to get some idea of how it works, try the introductory tutorial. After that, check out the online manual, and the example archive sites and some of the other resources available in those links.
* PHP stands for PHP: Hypertext Preprocessor
* PHP is a server-side scripting language, like ASP
* PHP scripts are executed on the server
* PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
* PHP is an open source software
* PHP is free to download and use
PHP tutorial and important site links are given belos :

all latest php update and rich tutorial site

php well arranged tutorial and example testing site

Latest relished php class publisher site

Some Useful Windows Run Commands

ADDUSERS Add or list users to/from a CSV file
ARP Address Resolution Protocol
ASSOC Change file extension associations
ASSOCIAT One step file association
AT Schedule a command to run at a later time
ATTRIB Change file attributes
BOOTCFG Edit Windows boot settings
BROWSTAT Get domain, browser and PDC info
CACLS Change file permissions
CALL Call one batch program from another
CD Change Directory – move to a specific Folder
CHANGE Change Terminal Server Session properties
CHKDSK Check Disk – check and repair disk problems
CHKNTFS Check the NTFS file system
CHOICE Accept keyboard input to a batch file
CIPHER Encrypt or Decrypt files/folders
CleanMgr Automated cleanup of Temp files, recycle bin
CLEARMEM Clear memory leaks
CLIP Copy STDIN to the Windows clipboard.
CLS Clear the screen
CLUSTER Windows Clustering
CMD Start a new CMD shell