الأربعاء، 21 سبتمبر 2011

Important PHP functions

 Functions

 

trim() Function

 The trim() function removes whitespaces and other predefined characters from both sides of a string.

Syntax

trim(string,charlist) ;

<?php
$string 
"        منتدى بي اتش بي                    ";
echo 
trim($string);// يتم طباعة منتدى بي اتش بي بدون فراغات قبلها وبعدها
$string2 "montadaphp";
echo 
trim($string2"map");// يتم طباعة ontdh
?>

 _________________________

 is_dir() function

The is_dir() function checks whether the specified file is a directory.
This function returns TRUE if the directory exists.

Syntax

is_dir(file)

Example

<?php
$file = "images";
if(is_dir($file))
  {
  echo ("$file is a directory");
  }
else
  {
  echo ("$file is not a directory");
  }
?>

 _________________________

header() Function

The header() function sends a raw HTTP header to a client.
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem):

<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>

Syntax

header(string,replace,http_response_code) 




Parameter Description
string Required. Specifies the header string to send
replace Optional. Indicates whether the header should replace previous or add a second header. Default is TRUE (will replace). FALSE (allows multiple headers of the same type)
http_response_code Optional. Forces the HTTP response code to the specified value (available in PHP 4.3 and higher)



Tips and Notes

Note: Since PHP 4.4 this function prevents more than one header to be sent at once. This is a protection against header injection attacks.

 Example 1

Prevent page caching:
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>

<html>
<body>

...
...
Note: There are options that users may set to change the browser's default caching settings. By sending the headers above, you should override any of those settings and force the browser to not cache!

Example 2

Let the user be prompted to save a generated PDF file (Content-Disposition header is used to supply a recommended filename and force the browser to display the save dialog box):
<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

<html>
<body>

...
...
Note: There is a bug in Microsoft IE 5.5 that prevents this from working. The bug can be resolved by upgrading to Service Pack 2 or later.

 _________________________

strtoupper() Function

Definition and Usage

The strtoupper() function converts a string to uppercase.

Syntax

strtoupper(string)

Example

<?php
echo strtoupper("Hello WORLD!");
?>
The output of the code above will be:
HELLO WORLD!

 _________________________

 

PHP end() Function

Definition and Usage

The end() function moves the internal pointer to, and outputs, the last element in the array.
This function returns the value of the last element in the array on success.

Syntax

end(array)

Parameter Description
array Required. Specifies the array to use

Example

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) . "<br />";
echo end($people);
?>
The output of the code above will be:
Peter
Cleveland

 _________________________

mysql_insert_id()

The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
This function returns 0 if the previous operation does not generate an AUTO_INCREMENT ID, or FALSE on MySQL connection failure.

Syntax

mysql_insert_id(connection)

Parameter Description
connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

Tips and Notes

Note: Be sure to call mysql_insert_id() immediately after a query to get the correct value.

Example

<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("test_db",$con);

$sql = "INSERT INTO person VALUES ('Børge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();

mysql_close($con);
?>
The output of the code above could be:
ID of last inserted record is: 5

 _________________________


 Date() Function

The PHP date() function is used to format a time and/or date.

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.
Tip A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Syntax

date(format,timestamp)

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

PHP Date() - Format the Date

The required format parameter in the date() function specifies how to format the date/time.
Here are some characters that can be used:
  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
A list of all the characters that can be used in the format parameter, can be found in our PHP Date reference.
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:
<?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d");
?>
The output of the code above could be something like this:
2009/05/11
2009.05.11
2009-05-11

PHP Date() - Adding a Timestamp

The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used.
The mktime() function returns the Unix timestamp for a date.
The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Syntax for mktime()

mktime(hour,minute,second,month,day,year,is_dst)
To go one day in the future we simply add one to the day argument of mktime():
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
The output of the code above could be something like this:
Tomorrow is 2009/05/12

 _________________________

الثلاثاء، 20 سبتمبر 2011

Important JavaScript functions

Important JavaScript functions and their use:


In Javascript Array class can be turned into Stack using push() & pop() method.
var objStack = []
objStack.push(2);
objStack.push(5);
objStack.push(8);
So here objStack will behave as a Stack object & it will follow FIFO (First-In First-Out) concept.
We can access the value of the object by -
objStack[1]; // It will give the 2nd element's value, i.e 5.
objStack.toString(); // It will give the values separated by comma, i.e 2,5,8.
objStack.pop(); // It will retrieve last inserted value, i.e 8. But that element (8) will be removed from the stack object.
Use of QUEUE [push() & shift()]


Similarly Array class can be used a Queue by using push() & shift() method.
var objQueue = [];
objQueue.push(4);
objQueue.push(8);
objQueue.push(12);
objQueue.shift(); // It will give the first inserted value, i.e 4. But that element (4) will be removed from the queue object.
Use of join() & split()


You can use join() methos to join the elements of the array & split() to do the reverse.
var arr = [1, 2, 3];
var outputStr = arr.join(' | ');
document.write(outputStr); // 1 | 2 | 3.
var str = '1 | 2 | 3';
var objString = str.split(' | ');
for (var counter = 0; counter < splitObj.length; counter++)
{
    document.write(objectString[counter]);
}
output: // 1, 2 ,3.
Use of sort()


Javascript provide sort() method for sorting elements of an Array. But by default the method sorts the elements in alphabetical order. So, non-string elements are converted into strings before sorting operation, then sorting operation is done. Which results unexpected outcome while dealing with number.
e.g : -
var arr = [9, 5, 10, 1];
arr.sort();
document.write(arr.toString());
The output will be "1, 10, 5, 9" which is wrong. So to avoid these kind of thing we can use a function for comparing the number and use it while sorting. That means we can write something like this -
// This function will return 0 if two numbers are equal else it will return either positive or negative number.
function compareNum(num1, num2)
{
    return num1 - num2;
}
We can use the user-defined compareNum() method while sorting numric array elements.
var arr = [9, 5, 10, 1];
arr.sort(compareNum); // We are passing the user-defined function name as parameter to the sort function.
document.write(arr.toString());
Now it will give the output as "1, 5, 9, 10".

الأحد، 11 سبتمبر 2011

Create an Advanced PHP Membership System

Introduction.

In this tutorial I will be showing you how to create an advanced PHP/MySQL membership system for you’re website.  We are going to create the simple forms, and create the back end to allow users to login, register, and logout of you’re website.
This “Advanced” membership system is actually quite simple, what makes it advanced is the object oriented user that will allow for a very extendable membership system.  This makes the membership system very versatile and usable on many different kinds of website.
You will need:
  • A little bit of PHP knowledge.
    We will be using some object oriented programming along with the basic required PHP for the membership system.
  • HTML Knowledge.
    I am just going to give code for basic forms just to make the scripts work.
  • A Text Editor or IDE.
    You will obviously need some sort of editor to edit your files in.
  • A testing server.
    You will need somewhere to test your project, we will be using PHP and MySQL so ensure that you’re testing server has these services available.
Create the basic files.
We are just going to create the HTML forms and files that we are going to use to access the membership system.  We need to make one for existing users to login, that one will be simple because it is just 3 elements. Email/Username, Password, and Submit.  We also will need to make a register form to allow new users to register on your website.
The files we will need in the root directory will be:
  • index.php
    The main page that the users will access.  Will also include the Login form.
  • register.php
    The form for users to register into the website, if this is something that you want.
  • handlers/login_handler.php
    Will handle a login request by the user, check it against the database, and authorize or deny the login request.
  • handlers/register_handler.php
    Will handle a request by the user to register to the website.
  • handlers/user_handler.php
    Will be included in the beginning of all of your pages to load the users settings.  Will also check the page permissions against the users permissions.
  • handlers/User.class.php
    This is the actual user class.  This will hold all of the users information and provide different functions relating to the membership system.

Create the forms.

The forms you will want to customize to match you’re websites theme.  I am just going to give you basic forms to get the tutorial running, and the HTML isn’t what this tutorial is really about so we are just going to skip over the HTML basics there.
Login Form (plus some php code for later):

<?php
require("handlers/user_handler.php");
 
if($user_data['loggedIn'] == 1)
{
 $string = "Logged in as: ";
 $string .= $User->get_info("email");
 $string .= " <a href=?logout>Logout</a>";
 echo $string;
}
if(isset($_GET['error']) && $_GET['error'] == 1)
{
 echo "<span style=color:red>There was an error logging in!</span>";
}
 
?>
 
<form id="login" method="POST" action="handlers/login_handler.php">
 Email: <input type="text" name="email" /><br />
 Password: <input type="password" name="password" /><br />
 <input type="submit" name="submit" value="Login!" />
</form>

Put this code into your “index.php” file.  This will act as the login form.
Next paste this form (or create you’re own) in “register.php“:

<?php
if(isset($_GET['error']) && $_GET['error'] > 0)
{
 echo "<span style=color:red>There was an error registering</span>";
 
}
?>
 
<form id="register" method="POST" action="handlers/register_handler.php">
 First Name: <input type="text" name="first_name" /><br />
 Last Name: <input type="text" name="last_name" /><br />
 <br />
 Email: <input type="text" name="email" /><br />
 Password: <input type="password" name="password1" /><br />
 Verify Password: <input type="password" name="password2" /><br />
 <br />
 <input type="submit" name="submit" value="Register!" />
</form>

Now that the base pages are done (ugly, but done) we can start to get into the back end of the membership system.

Create the MySQL Database.

The database is going to be very simple.  A single table in the database will handle everything necessary for the entire membership system to work properly.  Like I said in the introduction the “advanced” membership system is actually quite simple.
Create a database:

CREATE  DATABASE  `database_name` ;
 
Obviously you need to replace “database_name” with the name of the database you are creating,  If you’re website is already using a database you can skip that part and just add the table to the database.
Add the table to the database:

CREATE  TABLE  `database_name`.`users` (
`id` INT( 10  )  NOT  NULL  AUTO_INCREMENT  PRIMARY  KEY ,
`first_name` VARCHAR( 255  )  NOT  NULL ,
`last_name` VARCHAR( 255  )  NOT  NULL ,
`email` VARCHAR( 255  )  NOT  NULL ,
`password` VARCHAR( 32  )  NOT  NULL
) ENGINE  = InnoDB;
 
Once again ensure to change “database_name” with the name of the database that you created before (or your existing database).  Now that our table has been created we need to insert a default user into the database for testing.

 
INSERT  INTO  `database_name`.`users`
`id` ,
`first_name` ,
`last_name` ,
`email` ,
`password`
)
VALUES (
NULL 'Daniel''Henry''daniel@codedopen.com''aa47f8215c6f30a0dcdb2a36a9f4168e'
);


Now we have a single row in the database holding a user.  As of right now there is no user privileges or anything like that.  Just a few simple different entries that a website would commonly use.  We will get to adding user privileges and more fields later, but this should do for now.  Also I should note that the password entry is an Md5 hash.  I set the field “password” type to VARCHAR(32) to hold an Md5 hash perfectly, and the users password isn’t stored in plain text.

Starting the back end: User Handler and User Class.

The user handler will be included at the beginning of all of your pages and will determine if a user is logged in already, if not it will allow the user to log in.  Otherwise it will load the logged in user from the database, create the user object, and verify the user’s information.
First off lets create the actual user handler:

<!--?php //include this file at the beginning of every page. //set up mysql mysql_connect("localhost", "root", ""); mysql_select_db("database_name"); session_start(); if(!isset($_SESSION['user'])) {  //There is no user logged in    $user_data['loggedIn'] = 0; }else{  $user_data = $_SESSION['user'];     $user_data['loggedIn'] = 1;             //verify that the user data in the cookie   //is actually there     if($user_data['email'] == "" || $user_data['password'] == "")   {       unset($user_data); //clear the user data        unset($_SESSION['user']); //clear the damaged cookie        $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In"     }       //include the user class    require_once("handlers/User.class.php");    if(!$User = new User($user_data['email'], $user_data['password']))  {       //user information was invalid.  Log user out.      unset($user_data); //clear the user data        unset($_SESSION['user']); //clear the damaged cookie        $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In"     } } //check for the logout sequence if(isset($_GET['logout']) && $user_data['loggedIn'] == 1) {   unset($_SESSION['user']);   unset($user_data);  unset($User);   $user_data['loggedIn'] = 0; } ?--><?php
//include this file at the beginning of every page.
 
//set up mysql
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
 
session_start();
if(!isset($_SESSION['user']))
{
 //There is no user logged in
 $user_data['loggedIn'] = 0;
}else{
 $user_data = $_SESSION['user'];
 $user_data['loggedIn'] = 1;
 
 //verify that the user data in the cookie
 //is actually there
 if($user_data['email'] == "" || $user_data['password'] == "")
 {
 unset($user_data); //clear the user data
 unset($_SESSION['user']); //clear the damaged cookie
 $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In"
 }
 
 //include the user class
 require_once("handlers/User.class.php");
 if(!$User = new User($user_data['email'], $user_data['password']))
 {
 //user information was invalid.  Log user out.
 unset($user_data); //clear the user data
 unset($_SESSION['user']); //clear the damaged cookie
 $user_data['loggedIn'] = 0; //set the user data to read "Not Logged In"
 }
}
 
//check for the logout sequence
if(isset($_GET['logout']) && $user_data['loggedIn'] == 1)
{
 unset($_SESSION['user']);
 unset($user_data);
 unset($User);
 $user_data['loggedIn'] = 0;
}
 
?>


This file is included at the beginning of every page.  It pretty much handles everything user related.  First it checks to see if a user is already logged in.  If a user is already logged in it ensures verifies the information and creates the User object that allows the rest of the website to interact with the logged in user.
With the minimal settings that I have included in the tutorial so far there really isn’t much that you can do with the user but we will talk about expanding the membership system later.
Now the User class:

<?php
//the user class that will hold all of the users informaion
 
class User
{
 
 private $user_information; //create a private variable for the users informaion
 //that will be loaded from the database.
 
 public function __construct($email, $password)
 {
 //the constructor will check the username and password against the database
 //and return 1 on success as well as load up the user information.
 
 //create password hash.
 $password = md5($password);
 
 if(!$result = mysql_query("SELECT * FROM users WHERE email='{$email}' && password='{$password}'"))
 {
 //the user was uncessful with the login
 return 0;
 }
 
 //put the user information into the "user_information" variable.
 $this->user_informaion = mysql_fetch_assoc($result);
 }
 
 public function get_info($field)
 {
 //use this function to get a piece of information that is stored in the database
 if($field == "")
 {
 //there was no requested field
 return 0;
 }
 
 if(!key_exists($field, $this->user_informaion) || $field == "password")
 {
 //the requested information does not exist
 //or they are requesting the password key.
 return 0;
 }
 
 if(!$request = $this->user_informaion[$field])
 {
 //there was some sort of unexpected error.
 return 0;
 }
 
 //return the key
 return $request;
 }
 
}
 
?>

The User class is in my opinion what makes this membership system advanced.  If you were to copy paste this code, yeah, maybe it’s pretty simple.  But with some modifications to the code and some customizations to your website this code would allow you to just about anything without really changing too much on the back end of your website.
The class contains a function called get_info(). This function will allow you to grab and return any bit of information on the user except the password key.  This will make life much simpler when we get to adding new functionality to your code membership system.

Handling a Login Request.

We will need a file for the login form to direct to.  The action of the form that I created points to a file at handlers/login_handler.php.  You can put it wherever you want but for the sake of the tutorial we will use the one I listed above.  The login handler really doesn’t have to do that much.  All it has to do is verify the information and set the session variables.
Login Handler:

<?php
//set up mysql
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
session_start();
function clean($string)
{
 //function used for cleaning mysql injection garbage from strings   
 if (get_magic_quotes_gpc()) {
 $string = stripslashes($string);
 }
 return $string;
}
 
function go_home($error=0)
{
 //redirect to the form with an error
 $string = "
 <script type=\"text/javascript\">
 <!--
 window.location = \"../index.php";
 
 if($error == 1)
 {
 $string .= "?error=1";
 }
 
 $string .= "\"
 -->
 </script>
 
 There has been an error logging in, please click <a href=\"../index.php?error=1\">here</a> to go back home.
 ";
 echo $string;
 die();
}
if(!isset($_POST['submit']) || $_POST['email'] == "" || $_POST['password'] == "")
{
 //ensure that all parts of the form have been filled out.
 go_home(1);
}
 
//create a password hash
$email = clean($_POST['email']);
$password = md5($_POST['password']);
$result = mysql_query("SELECT * FROM users WHERE email='{$email}' && password='{$password}'");
if(mysql_num_rows($result) < 1)
{
 //email or password incorrect
 go_home(1);
}
 
$_SESSION['user']['email'] = $email;
$_SESSION['user']['password'] = $_POST['password'];
 
go_home();
 
?>


This file does exactly what I said it should, and really nothing too much more.  Not too much advanced stuff to talk about here so we can move on.  The only thing that I should mention is now you know how the code above the login form is used.  It displays an error on a failed login, and it also displays a “logged in” message when a login is successful.

Handling a registration.

Now all we really need to do to have a complete (but bare) membership system is to add the registration handler.  This will be almost as simple as the login handler, it will just be a little bit longer.  We need to verify that the email address isn’t already in use, the passwords match, then insert it all into the database.  Pretty simple right?
handlers/register_handler.php:

<?php
//set up mysql
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
function clean($string)
{
 //function used for cleaning mysql injection garbage from strings   
 if (get_magic_quotes_gpc()) {
 $string = stripslashes($string);
 }
 return $string;
}
 
function go_back($error=0)
{
 //redirect to the form with an error
 $string = "
 <script type=\"text/javascript\">
 <!--
 window.location = \"../register.php";
 
 if($error == 1)
 {
 $string .= "?error=1";
 }
 
 $string .= "\"
 -->
 </script>
 
 There has been an error registering, please click <a href=\"../register.php?error=1\">here</a> to go back to the registration page.
 ";
 echo $string;
 die();
}
 
if(!isset($_POST['email']) || !isset($_POST['password1']) || !isset($_POST['password2']))
{
 //ensure required fields are filled out
 go_back(1);
}
 
if($_POST['password1'] != $_POST['password2'])
{
 //make wure passwords match
 go_back(1);
}
 
//clean the variables
$email = clean($_POST['email']);
$password = md5($_POST['password1']);
$first_name = clean($_POST['first_name']);
$last_name = clean($_POST['last_name']);
$result = mysql_query("SELECT email FROM users WHERE email='$email'");
if(@mysql_num_rows($result) > 0)
{
 //make sure email is not in use
 go_back(1);
}
 
//insert the user into the database
$query = "INSERT INTO users
(first_name ,
last_name ,
email ,
password
)
VALUES (
'$first_name''$last_name''$email''$password'
)";
 
mysql_query($query);
echo "Successfu Register.  Click <a href=../index.php>here</a> to login!";
?>


The file creates a new entry in the database after ensuring that a.)The email has not been used yet and b.)that the users passwords match.

Making Additions.

Now that we have a plain jane membership system (Hooray!) we will probably need to start adding to it.  First of all the forms need some work and the error handling for the registration and login could be better, but that isn’t our main focus for adding to the membership system.
Mainly what we will want to do is add functionality, like maybe add an address field, phone number, user permissions, etc.  This will pe incredibly simple to do because of the way that you build your membership system.
As you know, all you need to do to get any of the users information is use the User objects function get_info() to get a any type of information on the user.  So to do something simple like an address or phone number you just need to add them to the database.  It will already be loaded into the object after you insert it,
For something like user permissions you would have to add the permissions to the database just like address/phone number, but there would be one more step.  You would either have to create a function library to be included with every page, or create methods in the User class to handler user permissions.  Either way is fine, I however prefer the latter.

Conclusion.

So after all of that you should have a working membership system on your website.  It may have required some tinkering with the code a little bit to get working on your homepage but nonetheless, you learned something new and that it always great.
If you have any problems, errors, or if you see a typo feel free to leave a comment here and I will do my best to help you out.  We also have a the forums where you could probably get some support, and I could use some help filling up the boards so if you feel like helping me and also helping start a great new online community for programmers everywhere freel free to stop by.