The legal tricks-Learn Your Self

Latest gadgets,softwares,hardware,reviews,programming and campuses, game cheats ext......

Creating a menu system - PHP tutorials

In this tutorial I will show you how to create a simple menu system with 2 levels. You can easy integrate it into your site to get a nice and easy editable site navigation system.

Step 1.

To make a menu system easy changeable and easy readable we will separate the code into more parts. A basic realization contains 3 files which are the following:
menuStruct.php: Contains only the navigation structure. It will be used by the handler function.

menuHandler.php: This file contains the PHP code which generates the menus with corresponding submenus as well.

index.php: The main page which integrates the navigation system.

Step 2.

First let's design the menu system structure. To handle the menu element easy we will use a multi dimensional array. In the array the key will be the name of the menu and the value is the link for it. So we can define the main menu system as follows:

Code:
// Main menu items
$mainMenu['Home'] = 'link-1';
$mainMenu['About us'] = 'link-2';
$mainMenu['Projects'] = 'link-3';
$mainMenu['Contact'] = 'link-4';
$mainMenu['Others'] = 'link-5';
?>


Now we have all the main menu items defined. However usually we need some submenus as well. To sore it in the array we will create a new array which stores the main menu - submenu relations. As you will see here we use a little bit more complex array to store information. You have to take care that the keys - key strings - in the main array and in the sub array must be identical. So the submenu array looks like this:

Code:
// Sub menu items
$subMenu['Projects']['SubMenu-1'] = 'sub-link-1';
$subMenu['Projects']['SubMenu-2'] = 'sub-link-2';
$subMenu['Projects']['SubMenu-3'] = 'sub-link-3';
$subMenu['Projects']['SubMenu-4'] = 'sub-link-4';

$subMenu['Others']['SubMenu-1'] = 'sub-link-11';
$subMenu['Others']['SubMenu-2'] = 'sub-link-12';
$subMenu['Others']['SubMenu-3'] = 'sub-link-13';
?>


At the end store this information in a file let's named it to menuStruct.php.

Step 3.

After you stored the menu structure in a file we can focus on the application logic. We will implement it in the second file
named menuHandler.php. In this file we will implement only one function called createMenu(). This function will have only one parameter which tells what is the actual page link. From this information the function will decide whether or not to display relevant submenus. So the final result is this:

Code:
function createMenu($actLink){

}
?>


Now let's start the most important part. First the function needs to include the menuStruct.php file to access the menu arrays. As second we open a table tag where we will display the menu elements as rows (tr tags).

As next step we check where the input parameter - which is the actual link - can be found in the arrays. It is important to know to decide which submenu the code should display. So the code is the following:

Code:
// Get actual Main menu
$actMenu='';
foreach ($mainMenu as $menu => $link) {
if ($link == $actLink) $actMenu = $menu;
if (isset($subMenu[$menu])){
foreach ($subMenu[$menu] as $menuSub => $linkSub) {
if ($linkSub == $actLink) $actMenu = $menu;
}
}
}
?>


After we got the actual menu we can begin with displaying the menu items row by row. We start it with the main menu items. In all steps we check whether the actually selected link in the array and the menu is the same or not. It is because if they are the same then we should display the relevant submenus before displaying the next main menu item. To make it more pretty we use other CSS class for the submenu rows as the main menu rows. The code looks like this:

Code:
foreach ($mainMenu as $menu => $link) {
echo ''.$menu.'';
if ( ($actMenu == $menu) && (isset($subMenu[$menu])) ){
foreach ($subMenu[$menu] as $menuSub => $linkSub) {
echo ''.$menuSub.'';
}
}
}
?>

Step 4.

The last step is a demonstration how to use it in the real life. To do this we will create a new file. Let's called it to index.php. This is quite straightforward. We include the menuHandler.php and create our HTML page as we want. Where you want to display the navigation block you only need to call our function with the actual link as

Code:

Formatting Dates in PHP

Ok, so how do you format dates in PHP so it outputs the date format you want? Well thanks to PHP’s date() and strtotime() function, we can do all that! To kick off, lets take the most common date format ‘YYYY-MM-DD HH:II:SS‘. This date format seems to be most favoured as it increments in such a way that allows you to query a database that has multiple records in a useful way, such as:

Code:
SELECT * FROM dates WHERE date > '2006-03-05 11:00:00';


Whereas if you were to use a different date format, such as ‘DD-MM-YYYY HH:II:SS‘ the incrementation wouldn’t work after each month as the starting value (the DD - Day) will start from 01 again. If you don’t get me, it doesn’t matter because we’re just making dates look nice in this post anyway.

Human Readable

When I say ‘Human Readable’ I don’t mean that the particular date (for example) ‘2006-03-05 11:00:00′ isn’t readable, but you wouldn’t necessarily read it out as ‘two-zero-zero-six zero-three zero-five one-one zero-zero zero-zero’ would you? A human readable version of this date would be something like Sunday, 05 March, 2006 @ 11:00:00. So how do we convert from one format to the next? Easy! Like this:

Code:
$sNewDate = date("D, d F, Y @ H:i:s", strtotime('2006-03-05 11:00:00'));


Now if we output the value of the new date variable ‘$sNewDate’:

Code:
print $sNewDate;



We get:

Sun, 05 March, 2006 @ 11:00:00

We could of course use:

Quote:
date("D, d F, Y @ H:i:s")


Which would output a nicely formatted date for the current date and time. You can also use other time strings for the second parameter, as long as you use strtotime() to format it into a nice UNIX timestamp for the date() function to process.

The Magic

So how did I make PHP output the particular parts of the date with extras like commas (,) and the at sign (@)? Let’s look at PHP’s date() function, which takes 2 arguments:
string formatThe format that date() should output
int timestamp (optional)The timestamp for date to format the date. If this is left blank, it will default to the current date and time.

The string format takes preset PHP characters, and will allow other characters provided they’re not in the ‘preset’ list, and if they are they must be escaped. Taking our example into account, lets see what characters we used:

Quote:
"D, d F, Y @ H:i:s"


We used:
D - A textual representation of a day, three letters
d - Day of the month, 2 digits with leading zeros
F - A full textual representation of a month, such as January or March
Y - A full numeric representation of a year, 4 digits
H - 24-hour format of an hour with leading zeros
i - Minutes with leading zeros
s - Seconds, with leading zeros

View the full list of characters to learn more about PHP’s date() function. Now how did we get the commas and @ signs in there? Simple, you can just add these anywhere you like within the ‘format string’ as I did above. If you wanted to actually output text within the formatted string, you could do something like this:

Quote:
"\D\a\\t\e\: D, d F, Y @ H:i:s"


Notice how we ‘escape’ each literal character with a backslash (\), and how we had to ‘double-escape’ the ‘t’ as ‘\t‘ sends a TAB to the page, so if we want a ‘t’ we must use ‘\\t‘. The above outputs:

Date: Sun, 05 March, 2006 @ 11:00:00

I hope this has given you some insight on how easy it is to format dates using PHP.

Simple PHP Class Tutorial

I’m not sure how to start this one… It can be quite difficult to understand PHP classes at first, but hopefully I’ll make everything seem easy!

The two files used can be found below:
time.php
class.Time.php

Right here we go…

Brief overview…

Ok so you’re actually reading this brief overview? You must be serious…

PHP classes can be used to group together a set of ‘like’ functions used within a bigger application. Their main advantage is the fact that you can edit the particular class function, or functions and make a site-wide change. Classes also help give you a more structured approach to programming, and those that like to hack with some GPL released web applications will have a much better understanding of the workings of them.

This may not be the best example of explaining why to use classes in PHP, but it’s an example of how to use them.

Let’s get stuck in

Let’s start by creating a new file called time.php. Within this file, let’s add some code:

File: time.php

Code:
$sTime = gmdate("d-m-Y H:i:s");
print 'The time is: ' . $sTime;
?>


This will simply assign the current date and time to the variable $sTime and then print the string ‘The time is ‘ with the variable value at the end (i.e. The time is: 09-02-2007 21:42:28)

How would we do this, using a class? Well there’s many ways, however I would recommend using the class file to generate the time, then use the acutal ‘action page’ (time.php) to output the time. Let’s create our class file!

Get in class!

Create a new file (keep it in the same directory for this tutorial). Let’s call it class.Time.php. Add the following code:

File: class.Time.php

Code:
class Time {
function GenerateCurrentTime(){
$sTime = gmdate("d-m-Y H:i:s");
return $sTime;
}
}
?>


Lets do this line by line… The first line, class Time {,declares the class as open (exactly the same as a function in PHP, but without the brackets in this case). The next line declares a new function. The difference here is that it exists ONLY within the scope of the class (i.e. it’s built WITHIN the class). We then generate the time as we did before, assigning it to the variable $sTime and then return the value of this variable. The function then closes, followed by the class closure (the squiggly brackets ‘}’). Note that our class needs to also be wrapped in php tags ().

Now open the original file, time.php, and change the code to match the following:

File: time.php

Code:
include ('class.Time.php');
$oTime = new Time;
$sTime = $oTime->GenerateCurrentTime();
print 'The time is: ' . $sTime;
?>


Now, the first line here includes the time class file (include ('class.Time.php');). We must include all the class files we wish to take advantage of, otherwise how the hell would PHP know about these files?

The next line, $oTime = new Time, creates the class object and stores it in the variable $oTime. Notice, to store the class in an object variable, we use VARIABLE = NEW CLASSNAME. VARIABLE can be anything, then there must be an equals sign ‘=’. NEW must use ‘new’ or ‘&new’, and the CLASSNAME must match the name of the class. In this case, the name of the class is Time (case sensitive - as PHP is throughout). The class name is ‘Time’ because we created the class using:

Quote:
class Time {


If we had used:

Quote:
class HelloWorld {


As you can guess, the class name would be ‘HelloWorld’.

Anyway… now we’ve created our class, we have also included it within the page we want to make use of it. Not only that, we have ALSO initalised our class by defining it in an object variable - $oTime.

So, the next line:

Quote:
$sTime = $oTime->GenerateCurrentTime();


This simply assings the variable $sTime with the result of the function GenerateCurrentTime() within the Time class. How does it do this? Simple… We want to use the function GenerateCurrentTime() within the class $oTime so we simply us:

Quote:
$oTime->GenerateCurrentTime()


This tells PHP exactly what we want to do. The ‘->’ explains to PHP that the prefix (in this case $oTime, which we know holds the class object) is the parent of the latter (again, in this case the latter is GenerateCurrentTime()). So it basically means, run GenerateCurrentTime() within the $oTime class. Thus assigning whatever is returned by the function GenerateCurrentTime() to the variable $sTime.

The last line does what we did from scratch… print out the results with the prefixed string ‘The time is ‘.

Xbox 360 for Rs. 15,000

Image
Expected to be officially announced soon; an Xbox 360 Arcade bundle is expected to sell for Rs. 14,990 this Diwali season. The bundle will get you the core console, a 20GB hard drive, a controller and a game.
Could this finally be a reflection of the console's international price drops, or is it merely stock clearance on Microsoft's part? Whatever the reason, at least one HD-console is now within budget of most Indian gamers. Happy Diwali shopping!

HCL MiLeap MH04 Netbook

HCL, which entered the UMPC and Netbook market with the MiLeap series, had its lower end model compete with the first Eee PC and later came the semi-premium class UMPC. However, both these models were soon outdated by other manufacturers who came up with newer Netbooks. These Netbooks predominantly had larger screens and Intel's Atom processor along with evolutionary hardware upgrades.
Thus it was time for HCL to keep up with the current generation. When their latest MiLeap MH04 model arrived at the Test labs, I had this weird sense of deja vu. I was pretty sure I had used a Netbook that was unmistakably similar to this one. And I was right! Read on to find out.
The bundle includes the Netbook, AC charger, instruction manual, Windows XP Home Edition CD, driver and application CD/DVDs and a protective cloth for the screen.
It was good to see the Windows CD along with the package, as most Netbooks I've seen till now have it simply pre-installed. This would prove to be useful should a need arise to install it at a later time.


Specifications Sheet
Image
Design and Construction
So, as I was said earlier, the physical appearance of the MiLeap MH04 was similar to a Netbook I had reviewed some time back. Here's a clue; it was, at that time, one of the best Netbooks around. Can't guess? Check out the comparative pic below.

Image
Yes my friends, the HCL MH04 is a repackaged MSI Wind. I'll just quickly reiterate the physical aspects of this device and point out some of the differences between the two. Looks wise, it isn't really a stunner but its appearance is rather decent in the black outfit. Since this model is fitted with a 3-cell battery (the Wind had a 6-cell), it feels pretty light for a 10-inch Netbook; definitely lighter than the 1.5 kg Eee PC 1000H. I had complained about the MSI Wind's lack of sturdiness.

After handling the HCL MiLeap MH04, I felt that the build quality had been slightly upped. But the screen hinge still needs a bit of reinforcement. The 10-inch screen offers good clarity, readability and is sufficiently bright as well. The webcam placed atop the screen delivers decent output in brightly lit environments but becomes pretty grainy under moderate lighting.

Image
The keyboard is pretty comfortable to type on, just like the MSI Wind. The touchpad also offers decent sensitivity and accuracy. The left/right click buttons were a little hard to click. But the big downer for me was that it did not support scrolling by swiping the finger at the corner of the touchpad. Despite my repeated attempts to get it working, it simply didn't happen.

I called their helpline to ask for a solution and was told that the MH04 does not support side scrolling. This is weird since the MSI Wind supported horizontal as well as vertical scrolling. Now that almost all the laptops available today support this feature, it was pretty irritating to get back to using the scrollbar or use the page up, page down buttons.

Image
Battery Life



Test 1: In this test, the screen brightness is set to 75 percent. Wi-fi and Bluetooth are switched off. Music is played via wired earphones. This is multitasked with reading a webpage offline and using a word processor. Here, I got just a little over 2 hours of battery life.

Test 2: Using the Battery Pro 05 application (which puts intensive work on the system resources) and with screen brightness turned to max, the machine belted out a run-time of around 1 hour and 40 minutes.

Under power saving mode and performing just basic functions like word processing, the maximum time that this Netbook can stretch up to is 2.5 hours. But heavy usage like watching videos or using Wi-fi extensively is going to hamper this run-time drastically.

Overall, I can say that the battery life was just about average. Netbooks are meant to give the user a longer uptime since they are meant to be carried around all the time. Thus a 2.5-plus hour battery life is pretty much expected from each one of them.

The Netbook ran pretty coolly. Operating noise and vibrations were barely noticeable.

Conclusion

The HCL MiLeap 04 sells for Rs. 25,990, which is cheaper than the Rs. 27,500 tag that we discovered on the MSI Wind recently (check last para of the MSI Wind review). We checked whether they have a 6-cell option but found that they don't.

This will prove to be a bummer for people who want a 4+ hour battery life from their Netbook. Comparatively speaking, the Eee PC 1000H's price has dropped to 25,500 bucks. At that price, with the kind of features the Eee has to offer, I have chosen to give the 'My favorite Netbook' crown to the Eee PC 1000H.

Although I prefer the Eee PC 1000H, I can say that the HCL MiLeap MH04 Netbook is a decent alternative. It can cater to people who want to do basic tasks like internet browsing, media playback and office productivity. But people who want a complete road warrior Netbook (i.e. with respect to build quality and battery life) would rather want to go for the Eee PC 1000H instead.

Duke Nukem Forever Spotted

Does more need to be said? Ok, how about Duke Nukem sure took Forever to get here... or how's this for fresh material -- We wonder if Guns 'n Roses are doing the DNF soundtrack?

Yeah, enough lame attempts at Duke Nukem Forever jokes. Here are the screens; if you are wondering, they were within the Xbox 360 release of Duke Nukem 3D (XBLA), available only upon earning all of the game's achievements.

Image
Image

For more info click here

PHP Security: Sending an email

In this tutorial we'll speak about the dangers mail() brings with it.

You probably wouldn't expect it, but the well known function mail() is a often a goldmine for spammers. In this tutorial we'll talk about the danger of using mail() in your PHP powered website.

Much websites have sorts of email forms. But what much of the webmasters don't know, is that with some code you can turn that simple form into a spammers base! When you have a field that should contain the email address of the sender, or receiver. The spammer could send additional data in the email, because the sender and receiver are stored into the header of an email. Basically what this means is that the spammer could change the email into an email that is send to numerous people, and contains spam!

I will cut the example because you need to understand some email protocol. (or API whatever you want to call it)

The remedy

The remedy is again very easy. The only thing you should do is check if the user has added a newline (\n) or carriage return (\r) into one of the email addresses.

The way most people do it is like this:
Code:
if (eregi("\r",$to)OR eregi("\n",$to))
{
echo �No valid email address';
}
if (eregi("\r",$from) OR eregi("\n",$from))
{
echo �No valid email address';
}
?>


Some other way people do it:
Code:
$to = str_replace( array( chr(12), chr(15) ), �', $to);
$from = str_replace( array( chr(12), chr(15) ), �', $from);
?>


The function chr() returns a string value from the ascii number in the function argument. Ascii number 12 is newline (\n) and 15 is carriage return (\r). So these few lines replaces the 2 unwanted ascii values into.. Nothing..

A very small but again very dangerous PHP Security flaw.

PHP Security: GET - include

You often find websites with serious but simple to fix security flaws. In this series we will talk about this. This time about GET - include problems.

In this tutorial we will talk about a very common security flaw.

I will explain how to make a GET -> Include system. In other words, think about an url like: index.php?page=links. The GET variable, in this case "page" will contain the string "links". And after people got this value, they write this kind of line into their page:
Code:

include $_GET['page'].'php';

?>


Or something similar. But in the end, they include the page without checking if it exists or any other safety check.

Much people out there use this, while this is very dangerous for your website. I saw many websites on the web that were hacked because of this system. (or cracked, whatever you want to call it)

Now you want to know why this is dangerous right? Well, it is very dangerous because php can include pages from another server! So php could also include a page from lets say, google.com. And if it will find a php source, it will execute it.

Now don't think everybody can steal your php code, no thats not true. Php can only read other code that's visible for the visitors. Take the following example.

PHP:


Open the source of this website, and you will notice that there is php code you can read.

So lets say, i have a dangerous php script. And i know a website which can read my code? The following url could read it: index.php?page=http://aserver.com/dangerous. (i didnt placed .php behind it, because as you can see in the first php example code, the script pops .php to the end)

My page would be generated by that server, and you can imagine what that could do to a server right?

The remedy!

There are quite a few things that could help destroying this security flaw on your server. I will handle three of them.

First is "allow_url_fopen". This is something you set in your php configuration file. When this is set on, php will be able to read scripts from another server. When it's off, php can only read files from the server it's installed on. This is a nice remedy for the problem, but i do it a bit different. What if you got a script that needs information from another server, and you need to include it? (doesn't happen often, but still keep it in mind)

Second in my list is "file_exists". You will use this in combination with an "if" statement. This will check if the file exists on the local server. It is not able to check if files from another server exists. So this could be quite a good remedy! I will show you an example below:
Code:

// get the name of the file the user wants to read.
$file = $_GET['page'].'.php';

// check if the file exists.
if (file_exists($file)) {

// it exists!
include $file;

} else {

echo'This page doesn\'t exist. Please try again.
';

}

?>


This is already a far better solution in my opinion.

But on this way people can open all the php documents in the folder. You may dislike this, so lets do it again a bit different.

A very simple, but also very effective way is to use an if statement. There is not much to discuss about, so lets see an example:
php

Code:

// check if the page is links?
if ($_GET['page'] == 'links') {

include 'links.php';

// check if the page is aboutMe?
} elseif ($_GET['page'] == 'aboutMe') {

include 'aboutme.php';

// could not find any of the pages?
} else {

echo 'This page doesn\'t exist. Please try again.
';

}

?>


This may not be the most pretty way to solve the problem. But it is very effective, and everyone with basic knowledge of php understands this.

Introduction to OOP

First things first, OOP stands for Object Oriented Programming.
A class is a group of functions and variables.
Lets create a class.
In the example's below we are going to create a class which will allow us to display what our favourite movie is.
Code:
class yourclass{

}


This is how we name our class and open it.

Now lets create a variable and function.
Code:
class movie{ //name the class
var $movie = 'none';
function movie($moviename){ //name the function
$this->movie = $moviename; //sets the var movie to the value of moviename
}
}


Now we have our function done. This will set the value of $moviename to $movie, next we will create a function to show it.

Code:
class movie{ //name the class
var $movie = 'none';
function movie($moviename){ //name the function
$this->movie = $moviename; //sets the var movie to the value of moviename
}
function showmovie(){ //name the function
return $this->movie; //return the movie var
}
}


This function will show the contents of the $movie variable.

We have still to create the bit that will call our class and then use the functions.

Code:
class movie{ //name the class
var $movie = 'none';
function movie($moviename){ //name the function
$this->movie = $moviename; //sets the var movie to the value of moviename
}
function showmovie(){ //name the function
return $this->movie; //return the movie var
}
}
$mov = new movie;
$mov->movie('Movie name!');
echo $mov->showmovie();


And we are done! You have created you're first class which will spectify your favourite movie and return it.

If you would like more help with this tutorial please register and visit the forum.

Creating a guestbook

In this tutorial I will show you how to create a simple guestbook where your visitors can leave messages which are stored in a MySQL database. It contains the basic functions and security settings.

After this short summary let’s see the steps how to realize it.

Step 1.
First of all try to think about what we need in this project. The most important is the main page where we can see the massages ordered by date. I personally like the newest on the top, but you can of course change it to the opposite order. So the main page contains the messages with the name of the writer and the datum when the message was submitted. The second most important functionality is to add new messages to the list. On the add page a visitor fill out a form with his/her name and the message and submit it. In this phase our script needs to do some input validations and security checks. As we want to store the messages in a database we need a connection to a MySQL server. As we need this connection in various files it makes sense to implement it in a separate file.

So at the end we need 3 files as follows:

1. index.php : This is the main page with the list of messages.
2. add.php: This script adds new messages to the list.
3. db.php: This script contains the database connection information and code.

Let’s start with the implementation in opposite order.

Step 2.
Before implementing our database connection script we need to design our database structure.

We want to store in this tutorial the following data:

* Visitor name
* Message
* Date and time when the message was added to the guestbook.
* ID to uniquely identify a message.

As result the sql code to realize this looks like this:

`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`text` text,
`insertdate` datetime default NULL,
PRIMARY KEY (`id`)
)


Step 3.
So as we have the database table let’s try to connect to it. As this tutorial is not focusing on database issues so here I don’t make any long explanation. The db.php script just contains the important connection information than try to make a connection to the given MySQL server with the given user name and password. As next step it selects the right database. That’s all. All the other database queries will be implemented in the index.php and add.php scripts.

At the end our db.php script looks like
$serverhost = "localhost";
$serveruser = "username";
$serverpwd = "password";
$dbname = "test";

$connection = mysql_connect($serverhost,$serveruser,$serverpwd);
mysql_select_db($dbname,$connection);

?>