Posts filed under 'PHP'

Beginners PHP Tutorial – Using Cookies

For users who prefer to learn PHP visually we have a range of video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the PHP Tutorial Videos – Beginners

.

Beginners PHP Tutorial – Cookies – Setting and Reading

A cookie is a small text file that is sent by a web server to a web browser and from the browser back again to the server whenever the server requests it.
Cookies are used for many purposes including authenticating logged-in users, tracking shopping cart contents, maintaining user site preferences and more.

A cookie consists of two parts. The cookie name is used to identify the cookie from other cookies sent by the same web server. The cookie value is the actual data that the web server writes to the user’s hard drive. That data is contained within a file using the cookie name.

How to Create a Cookie Using PHP

You can use the built-in SetCookie() function to create a cookie from within your program. This function takes up to six parameters. Only the first two are required. Those are Name and Content. A cookie must be sent before any other content is sent to the browser or an error will result and the cookie will not be written. Here is how you use the function:

How To Send a Cookie to the Browser

If you want to send a cookie to the browser you can use the setcookie() function. Note that you should call setcookie() before any other output statements. The following script shows you how to set cookies:

<?php
  setcookie("UserName","JoeGreen");
  setcookie("CartID","1234567");
 ?>

In the above example, the script set two cookies. The first one, named UserName, wrote the site user’s login name to a file. The second cookie, named CartID, wrote that user’s shopping cart ID to a file. Later, when the user is checking out, the server can retrieve both of these files and use the information to help the user pay for his order.

Here’s how you retrieve and read a cookie using the built-in global variable named $_COOKIE array.

<?php
  if (isset($_COOKIE["UserName"])) {
    $UserName = $_COOKIE["UserName"];
    print("Welcome ”.$UserName.” You are logged in\n");
  } else {
    print("Please log in.\n");
  } ?>

When does the cookie crumble?

Unless you take steps to make a cookie persistent, it is automatically deleted when the user closes their browser. Here’s how you can make a cookie stick around longer:

This example will keep a cookie live for 7 days:

setcookie("CartID","1234567",time()+(86400 * 7));

The above code is taking the current time, retrieved using the PHP function time(), and then multiplying the number of seconds in a 24-hour day (86,400) by the number of days in a week (7). That number is added totime() and results in a date seven days in the future.

How to Delete a Cookie

You can delete a cookie, regardless of whether it is temporary or persistent, simply by changing its expiration date to a time in the past. Here is an example:

setcookie("CartID","",time()-1);

Once you execute that line of code, the cookie immediately expires.

Here is a description of all the parameters that SetCookie() accepts:

setcookie(name,value,expire,path,domain,secure)
  • Cookie name: (already demonstrated)
  • Cookie value: (already demonstrated)
  • Cookie expiration date/time: (already demonstrated)
  • Cookie path: If set to “/”, the cookie will be available throughout the entire site path structure. If set to “/cart/”, the cookie can only be accessed when the user is in the /cart/ directory and any of its sub directories. The default value is the directory that the cookie was originally set in.
  • Domain: Specifies the domain name that the cookie is available in. To make the cookie available on all sub domains of MySite.com, you would set this parameter to “.mysite.com”. If you set it to www.mysite.com, then it is only available when they in the WWW portion of the domain. So, if you had mycart.mydomain.com, you could not read the cookie.
  • Secure: Determines whether the cookie can be created and read in an insecure connection, or only when the user has created an HTTPS connection. Set it to TRUE to force a secure connection. The default is FALSE.

Next PHP Tutorial Sessions

For users who are just getting started with PHP, Cheat Sheets can be an excellent way to learn, this link is an excellent resource on not only PHP Cheat Sheets but also CSS and HTML. PHP Cheat Sheets

Add comment November 14, 2008

Beginners PHP Tutorial – Sessions

For users who prefer to learn PHP visually we have a range of video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the Beginners PHP Video Tutorial

.

Beginners PHP Tutorials – PHP Sessions

PHP sessions are used to pass data between pages without having to encode that data and put it on the URL line. Sessions are different than cookies, in that sessions are not written to the user’s hard drive like cookies are, but they perform many of the same functions, to beginners PHP Sessions sound complicated but this tutorial shows the beginner just how simple Sessions are to use.

Sessions are safer to use than cookies because a user can block cookies from being written, but they cannot block sessions.

Like a cookie, sessions gives you a way to store data while the user is visiting the site. Unlike cookies, the data is not persistent. The session information is lost when the user leaves. Session data can be made persistent by storing it to a persistent cookie, or in your MySQL database, if desired.

How Sessions Work

When you create a session, PHP assigns a unique identification number to it. This is functionally equivalent to the way that a cookie assigns a cookie name. The unique session ID insures that one user’s data is not mixed in with another’s.

How to Initiate a Session

A session must be initiated at the top of your page before any other browser output. Otherwise an error will result and the session will fail. PHP provides the Session_Start() function for this purpose.

<?php
   session_start();  // start a new PHP session
   ?>

This is all it takes to register the new session with the server. Once this is done, you can begin storing information to the session variable.

How to Store a Session Variable

When you create a session, PHP initializes an associative array named $_SESSION. This is where you store and access session data.

<?php
   $_SESSION['UserID'] = ‘JoeGreen’;
// store  session data
   echo "Welcome “. $_SESSION[' UserID '];
//retrieve session data
   ?>

Advanced Session Use

You can use the PHP isset function to make sure that a session has been created and that any particular piece of session data has been set.

<?php
   if(isset($_SESSION['UserID']))
     echo "Welcome “. $_SESSION[' UserID '];else
       echo ‘Please log in.’;
   ?>

The first time the user arrives at the site, the UserID session variable will not be set and the user will be directed to log in before they can continue to access the site.

Once they are logged in, the session variable will be present and they will see the welcome message instead.

Ending a Session

In the example above we used session data to track login status. If your script has a logout function, you would want to destroy the session data once the user logs out.

<?php
   if(isset($_SESSION['UserID']))
       unset($_SESSION['UserID']);
   ?>

If you had other session variables as well, and you want to completely remove all of them, it is quicker to simply destroy the session.

<?php
   session_destroy();
   ?>

Sessions can be used to track anything pertaining to a user. Combine the power of sessions with PHP’s excellent array functions and you could store an entire shopping cart’s worth of data with very little effort.

1 comment November 14, 2008

Beginners PHP Tutorial – Regular Expressions

For users who prefer to learn PHP visually we have a range of PHP video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the PHP Tutorial Videos

.

Beginners PHP Tutorials – Regular Expression Basics

Regular expressions (regexes) provide a way to perform pattern matching inside of text strings as well as a way to extract subsets of text from within a string. Although the syntax looks complicated, it is really pretty easy once you understand these basics:

  • PHP offers both a PERL version of regex tools as well as its own. This tutorial covers using the PHP functions which include ereg, eregi, ergei_replace and ereg_replace.  The only difference between the functions ending in “g”, and the ones ending in “i”, is that the ones ending in “i” are case insensitive.int ereg ( string $pattern , string $string [, array &$regs ] )

The first parameter is the pattern to match. The second is the string to look for the pattern in, and the third, optional parameter, is an array to parse the matched parts of the string into. The parameters are the same for the eregi function.

  • Regexes work with patterns. The pattern is what you are seeking inside of the string you will be searching. Patterns are always delimited with a forward slash at the start and end of the pattern. Here is a very simple pattern:

/hello/

In the above example, the pattern would match a string that contained “hello world”.

<?php
   $string = ‘hello world’
   if (ereg ("(/hello/)", $string)) {
       echo “Found it!;
   } else {
       echo "Didn’t find it";
   }
   ?>
  • A basic pattern like the one shown above isn’t very useful. In fact, there are easier functions available in PHP to see if the string “hello” is part of another string. The real power of regexes comes in the use of metacharacters. These are special symbols that trigger regexes to perform more complex tasks. The available metacharacters are:
\ | . ( ) [ ] { } ^ $ + ?

When any of these metacharacters appear within a pattern, PHP knows that they have a special purpose and does not try to match them in the target string. If you wanted to actually match one of these, instead of use them as a metacharacter, you would have to delimit the character with a leading backslash.

A pattern to match “hello?” would be written like this:

/hello\?/

How Each Metacharacter Works

  • The dot (.) is a wildcard. It matches any character in a string. /h.llo/ will match hello, hallo, hillo, etc.
  • The caret and dollar sign (^$) are anchoring metacharacters. The ^ is used to match the beginning of a string. The $ matches the end. So to make sure a string started with the letter h, and ended with o, you would write /^hello$/. This match would fail with a string of “ahellow”, even though the string “hello” matches the “hello” in the pattern.
  • Parenthesis ( () ) are grouping metacharacters that allow complex patterns to be defined.
  • * + ? { } These symbols are quantifying metacharacters that define how many times a certain character or group of characters can or must appear.
  • The pipe ( | ) is an alternation metacharacter roughly equivalent to the PHP logical “or” statement. It tells the regex engine to match either one group of characters OR the other. It is used with the grouping metacharacter. The presence of either of these two strings would be considered a match: /(hello|(howdy)/
  • The square brackets [ ] are character metacharacters. They tell the regex engine to match any of the characters contained between the brackets. /h[eao]llo/. It also supports ranges of characters. /[a-zA-Z0-9_]/

The following shortcut symbols may also be used within or outside of the character class:

/\d/  matches any digit
/\D/  matches any non-digit character
/\w/  matches any of these characters: a-zA-Z0-9_
/\W/ #matches any non-word character
/\s/ #matches any whitespace character like space, tab or newline.
/\S/ #matches any non-whitespace character

So, for example – if you wanted to create a pattern that matched any 5 digits, you could write this: /\d{5}/

String Replacement

Both ereg_replace and eregi_replace use the same pattern matching rules as you have already learned.  The eregi_replace function is case insensitive.

string ereg_replace ( string $pattern , string $replacement , string $string )

The first parameter is the regex pattern you want to match. The second parameter is the string that you want to use as the replacement if your match is found. The third parameter is the string you are matching against. The function returns the modified string, if a match was found, or the original string if it was not.

$mystring =  ereg_replace(“/hello/”,”howdy”,”hello world”);
Echo $mystring;
   “howdy world”

Summary

Read through this lesson a few times and try to create some of your own examples. This is a great tool for validating strings used in input forms. Here’s an example that validates a North American telephone number that was passed to a routine from a customer registration form.  For this example, the number should be in the format of 999-999-9999. Anything other than that is invalid.

Work your way thorough the pattern and identify each metacharacter used.

function checkPhone($phone)
   {
      if(ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', $phone))
         return true;
     else
         return false;
   }

As an exercise, modify the above regexp to validate a phone number in this format (999) 999-9999.

Look at this pattern. Can you tell what it is used to match?

("#\d{3}-\d{2}-\d{4}#")

Add comment November 10, 2008

Beginners PHP Tutorial – Sending Mail with PHP

For users who prefer to learn PHP visually we have a range of PHP video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the PHP Tutorial Videos

.

Beginners PHP Tutorial – Sending E-mail Using PHP

PHP has a built in function that can be used to send email to one or more recipients. Some reasons you may want to use a mail function in your program include:

  • Staying in touch with your site members via a newsletter.
  • Sending a “welcome” message when someone joins your membership site.
  • Sending a purchase receipt to someone who has just bought your product or service.
  • Running a “Contact Us” form.

Introducing The PHP mail() Function

The mail() function is PHP’s built-in connection to your web site’s mail server. The function accepts up to 5 parameters. The first 3 are required. Let’s look at the parameters:

Parameter Description
to The email address of the recipient.
subject The email’s subject line.
message The body of the email message.
headers Any additional headers you want to pass such as “From”, “Cc”, “Bcc” etc. Although this is an optional parameter, I recommend always passing the “From” parameter (your email address), otherwise your server may substitute strange from addresses such as NULL@Servername.com, where ServerName is the actual name of your mail server. Some servers will not send your mail at all unless the from address is provided.
parameters Other optional parameters sent directly to your mail server. You’ll probably never use these.

How to Send an Email

A quick and dirty way is to simply call the function with each of the parameters separated by commas. Use double quotation marks as shown below:

mail(“somebody@somesite.com”,

  “Welcome to My Site!”,

  “Hello Somebody, thank you for joining my site!”,

  “From: webmaster@mysite.com“);

What we did was pass the 3 required parameters and one of the optional ones. Each parameter was separated by a comma.

Of course, in real life, you probably won’t be hard coding the recipients address. That will come from a contact form post or a MySQL query result.

In that case, you would put all of your email content into variables and pass the variables to the mail() function.

Let’s say that you received a contact form post. The email address of the person posting the form is passed to your script as $_POST[‘to’], and their name is in $_POST[‘name’]. You would set up the parameters like this:

$to =  $_POST['to'];
$name =  $_POST['name'];
$subject =  "Thank you for your message";
$message =  "Hello $name, thanks for contact me. I’ll be in touch soon.";
$from =  "webmaster@mysite.com";
$headers =  "From: $from";
// Send email
mail($to,$subject,$message,$headers);

And that’s all it takes to send simple text-based email from PHP. Sending HTML email, or email with attachments, is more complicated and may be the subject of a future PHP tutorial.

Add comment November 10, 2008

Beginners PHP Tutorial – Variables and Operators

For users who prefer to learn PHP visually we have a range of video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the Beginners PHP Tutorial Videos

.

Beginners PHP Tutorials – Variables and Operators

This short beginners PHP tutorial will give you a basic understand of variables and operators used in PHP and are an essential part of PHP Programming.

Unless you are going to create a script that does nothing more than echo “Hello World!,” it”s unlikely you are going to be able to get around using variables and operators. They are the basic building blocks of any computer program. But don”t worry, they”re a snap to use once you understand these basics:

Variables are used to hold data. That data is called a value. PHP uses these six different variable types:

• Integer (stores whole numbers)
• Double (holds real numbers)
• String (holds text or numbers depicted as text)
• Boolean (designates True or False)
• Array (holds multiple variables and values)
• Object (too advanced for this article)

Variables do not need to be declared in advance when programming in PHP. Many programmers do so anyway, but it’s a personal choice.

The easiest way to assign a value in PHP is to simply do this:

• $R=”100″ // this is a text depiction of a number
• $X=100; // this is an integer
• $Y=.0221 // this is a double
• $Z=”Hello”; // this is a string
• $AString =”World”; // this is another string
• $answer = TRUE; //this is a logical. You can use TRUE,FALSE, or 0 to depict false and 1 to depict true.

Notice that each variable begins with a $. This is how you alert PHP to the fact that you are creating a variable. Numeric variables do not use a quotation mark, text variables and numerics used as text, do.

Variables do not have to be a single letter. You can use any words as well. $MyName=”Joe”;

Text variables usually use a single quote unless the variable contains a variable. Here”s an example.

<?php

$z=”Hello”;
$w=”World”;
$ThisVariable = “I would like to say $z $w”;
echo “$ThisVariable”;

?>
would display: “I would like to say Hello World”

Variables can be added to any spot in a string either by using the above example or by using the period as a continuator. Here is an example.

echo “I would like to say ” .$z. ” And I would also like to say ” .$w. “to everyone.”;

Logical variables are typically used within control structures, such as an if statement to branch out to other code if a certain condition is true or false. Here is an example:

<?php
$x = TRUE;
If ($x){echo “True”;}
Else {echo “False”;}
?>

Note: Setting $x =”sometext” or $x = 1; would also evaluate the above code example to echo out “True”.

When testing for a true or false condition, you do not need to use the equality symbol.

if ($x) means “if the value of $x is true”. If you want to test for false, you use the NOT operator, which is the exclamation mark ( ! ).

Here is an example using the NOT Operator:

<?php
$x = TRUE;
If (!$x){echo “False”;}
Else {echo “True”;}
?>

Numeric variables can be used in any math formula. Here are some examples:

$MyTotal = $x+$y;

$Remaining = $x-$y;

$Piece = $x/$y; //($x divided by $y)

Understanding Operators

Operators go hand in hand with variables. PHP has five categories of operators:

• Assignment Operators
• Math Operators
• Comparison Operators
• String Operators
• Combination of Math and Assignment Operators
Assignment Operator

The assignment operator, equal sign, is used to assign a value to a variable.

$x=15;

Math Operators

Math or Arithmetic operators are used to perform math functions.

 + Addition
- Subtraction
* Multiplication
/ Division
 % Modulus

Comparison Operators
Comparison operators are used to test the relationship between variables or values.

 == Equal To
 != Not Equal To
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To

Combination Operators
Combination operators are primarily as shortcuts for incrementing or decrementing variables in one step.

For example, you might write $x = $x+1 if you were creating a counter. A combination operator would let you write $x+=1 and get the same result, you could also use a shortcut of $X++ , which increments the value of $X by one, $X—subtracts 1 from the value of $X, it”s hard to see just where this would fit in, but once you start using loops and conditional logic you will see how this little count makes life so much easier, in fact let me give you a quick example, lets say we want to print out the 12 times table:
<?php
$count=1;
  while($count <13 ){
    $val=$count*12;
 echo”$count x 12 = $val<br>”;
$count++;
}

?>

As long as the value of count is less than 13 this script will run, at the end of the loop count is increased by 1 and the loop starts again, the minute count is not less than 13 the loop stops executing, if you removed the counter from the bottom of this script the code would execute indefinitely, are at least till your server crashed.

PHP Operators

 +=Plus Equals
-=Minus Equals
*=Multiply Equals
 /=Divide Equals 
%=Modulo Equals $x
.=Concatenate Equals

Concatenate Equals is used with strings. $string = $string.” World.” Could be shortened to $string.=” World.”

Once you start working with variables and operators for a little while, they’ll become second nature to you.

1 comment November 7, 2008

Leopard Tutorial – Installing PHP Mac 10.5

For users who prefer to learn Apple Leopard 10.5 visually we have a range of video tutorials, this method of training greatly enhances learning and allows beginners to master Apple Leopard 10.5 at their own pace.
View the Apple Leopard Tutorial Videos

.

Installing PHP 5 on Apple Leopard 10.5
 

These short PHP tutorials will help users correctly install PHP on Apple 10.5 Leopard using the default Apache server configuration that ships with Leopard.

Really this tutorial is not about installing PHP on Leopard 10.5, and that’s because it’s already installed, all you need to do is make a few small changes and you will unleash the full power of the Apache 2 web server and a full working version of PHP 5, here’s how.

First you need either a copy of BBEdit or TextWrangler, either one of these programs will allow us access to the hidden system files that we need to change in order to set up PHP 5. BBEdit is a paid product whereas TextWrangler is a lite, free version of BBEdit, the directions are the same for both programs:-

Launch BBEdit or TW, Select  File > Open Hidden.image1

 

 

 

 

 

this will open a Finder Window, at the bottom of the window select “All Files”  from the Enable drop-down box.

Now we need to open the httpd.config file, this should be located inside your Macintosh HD private:etc:apache2:httpd.conf , once you have found this file click open, the file will open but editing of this file is prohibited since it’s a system file, no worries, to enable editing just click the red diagonal red line located in the top left of the BBEdit / TW title bar. image2

 

 

 

You will get a warning that the Apache httpd.conf file is owned by root and do want to alter this file.

A word of warning you are now playing with an hidden system file and under normal circumstances you should first make a back-up, and you can if you wish to, however Apple have already anticipate this and a back-up copy of this and all the other Apache system files exist in the Original folder inside the Apache2 directory.

Now on to making the changes to the http.conf file, scroll down until you see the line of code that starts #LoadModule php5_module libexec/apache2/libphp5.so ( around line 114 ).image3

 

Uncomment the line by removing the preceding # , it should now read:
LoadModule php5_module libexec/apache2/libphp5.so
We have now made PHP 5 active, save the file, since the file is a system file you will have to type your administrator password before the file will save, that’s it, PHP is now running, you could stop and this point and all should work, but it is better if we create the php.ini file is we can make custom changes to the standard PHP configuration later if we need to.
The php.ini file on the Mac
PHP 5 on the Mac does not install a php.ini file, but one does exist on the system, we only have to make a few small changes to make it active, unlike the httpd.conf file we can’t use BBEdit or TW to open the file, we have to use the terminal.

Open the terminal ( located in the Application > Utilities folder ) and enter the following command ( press the enter key after each line)

cd /private/etc
sudo cp php.ini.default php.iniimage4

 

 

 

After the last command you will be asked for you administrator password, enter it, hit return and we are nearly done.

Turn on Web Sharing
Go to System Preferences > Internet & Network and select Sharing, this should start Apache, but it’s always a good idea to restart your system too.

When your Mac restarts we can test to make sure PHP is enabled :
open up BBEdit and type the following

<?php phpinfo(); ?>

Save this as test.php in Macintosh HD:Library:WebServer:Documents

Now open up your browser and type
http://localhost/test.php/

If you see details about your php installation give yourself a big pat on the back

The working php.ini file as now been copied to Macintosh HD:private:etc , like the httpd.conf file, this file can in the future be edited with BBEdit or TW.

Add comment November 6, 2008

Redirect Using .htaccess or PHP

There are a few ways to redirect visitors to your website using either PHP or .htaccess and neither take preference over an other in my book, no doubt some geeky programmers will jump up and done saying one method takes 3 thousands of a second more to execute.

PHP Method
<?php
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location:
http://www.new-url.com” );
?>

This looks simple and it is, just a couple of things to remember:-
This code most come before any call to output to the browser, that means it must precede any text, images, even a space, if it doesn’t you will get an error.
Simple redirect using .htaccess file
Redirect 301 /oldpage.html http://www.example.com/newpage.html

The first section tells the Apache what to do and what HTTP Header Status to use, the next is the old page and the final chunk is the nice new shinny file that we want to send people too.
Mod_rewrite method in the .htaccess file
rewriteEngine on
rewriteRule ^oldpage\.php$
http://www.mywebsite.com/newpage.php [R=301,L]

The first line tells Apache to switch the mod_rewrite on.
The second line instructs mod_rewrite to match the request where the URI is exactly oldpage.php. The ^ matches the beginning and the $ matches the end of the expression, a the \ is used to escape the period, if we left the \ out the period would have become a meta character and matched any character, the R=301 means send HTTP Status Code 301 and the final L means LAST, in other words don’t process any other rules.

Add comment November 5, 2008


Follow us on Twitter

Categories