All times are UTC - 6 hours




Post new topic Reply to topic   Page 1 of 1
 [ 10 posts ] 
Author Message

 Post subject: PHP Guide [Abridged]
PostPosted: November 10th, 2011, 8:32 pm 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
PHP Guide (Abridged)

This is a very abridged introduction to the basics of PHP, touching on some of the fundamentals to building a PHP file. Unlike HTML or XHTML, PHP is a server-side programming language. PHP is typically focused on communicating with databases (typically mySQL, among others) to load and handle data for the page before the page is generated. The PHP file extension is exclusively .php.

Getting Started

Source files

Source files are basically the PHP page itself. However, you may also use HTML pages as a functioning PHP page in some cases, though it may prove to be a bad practice to some. :awesome: Any PHP content should be surrounded an opening tag (<?php) and a closing tag (?>). For an exclusively PHP file (.php), these should appear at the top and bottom of the document, respectively.

In the event of a PHP-enabled HTML page, the most common uses I've seen of PHP being included in the page include Session handlers and Inclusion of other pages into that page.

For Session handlers, the PHP opening tag should appear at the top of the file with no lines above it, thus forcing the PHP source to be parsed prior to the HEADERs being sent.
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

For inclusion of other pages into a PHP-enabled HTML page, the PHP opening tag can appear anywhere you want the content to appear. You would simply use an Include function. This function will be explained later as it is often used and necessary to keep files clean.
<body>
   <?php include('content-pages/body.html'); ?>
</body>

Some Basics

Here are a few things you absolutely should know before starting to attempt PHP. Every line of processed code is read as-is, until it hits an end character ";" which tells the processor to stop and begin a new line. The handler does not recognize line breaks as a means of separating code and will read it as if it were on a single line - causing a fatal error and preventing the page from being processed.

Also, the methods of displaying content I use most often are:
   echo "string";
   echo("string");
   echo $variable;
   print "string";
   print("string");
   print $variable;

From what I've heard, this is typically a coder's preference, because there isn't always a noticeable difference in using either of them.

IF-ELSEIF-ELSE (conditional) statements are a must-have for PHP coders. IF this statement is true, do this. Otherwise, (else)IF this statement is true, do this. Otherwise, do this.
   function findValue($a)
   {
      if ($a == 2)
      {
         return "WIN";
      } elseif ($a == 5)
      {
         return "ALMOST";
      } else
      {
         return "FAIL";
      }
   }
   findValue(2); // returns "WIN"
   findValue(5); // returns "ALMOST"
   findValue(1); // returns "FAIL"

Another big one to mention is the difference between single quotes (') and double quotes ("). While double quotes generally mean a string of text, they also enable the use of inclusive variables and special characters, such as \n (newline) and \r (carriage return). Single quotes are typically used for numbers or within SQL statements to denote data to be searched.
   $text = "hello";
   $otherText = "$text world";
   
   echo $otherText; // displays "hello world" on page


Variables

PHP variables are set much like other languages, but is prepended with a leading '$' to signify it is a variable. These variables can either be Local or Global, depending on how you need them in your use. Further, variables can be given a TYPE to limit what type of data can be saved to that variable. However, PHP does not require TYPE declaration and automatically gives variables a TYPE when set, based on the data saved. The default is a STRING.

Setting Variables
W3Schools wrote:
Naming Rules for Variables
  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
  • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)

Standard naming etiquette says spaces should be removed altogether and the first letter of each word following the first word should be capitalized. This method will be utilized in this guide.

PHP variables can be set using either

   $textVariable      = "Data to save";
   $numericVariable   = 1;

or

   var $textVariable      = "Data to save";
   var $numericVariable   = 1;

though prepending 'var' is not necessary for setting the variable.

It is also possible to set variables using a simplified IF-ELSE statement
   $a = 1;
   $textVariable = ($a == 1) ? "WIN" : "LOSE";

In this case, it checks if $a is equal to int(1). If this is true, the variable is set to "WIN." Otherwise, the variable is set to "LOSE."

Note that while it is expected to set a numeric variable without quotes, it is required to surround strings of data in single (') or double (") quotes or it will cause a fatal error.

Variable TYPEs

Variable TYPEs, though unnecessary for setting most PHP variables, since they're generated automatically based on the content received, can be useful in maintaining integrity of values. This is especially true when calling data from a database where numbers may be saved and retrieved as strings but need to be read as a number.

For the purposes of this guide and being an abridged version, the only TYPE we will worry about is the INTEGER. As stated, it may be necessary to convert a string to a number in any number of cases, so the easiest method I've seen is to simply use the following:
   $textVariable = "1";
   $numericVariable = (int) $textVariable;
   or
   $numericVariable = (int) "1";

By including the (int) or (integer) infront of the content to be forced into INTEGER format, it actually changes the content to reflect a numeric number and will return as int(1) in the example. This method is called Casting.

Local Variables

Variables are set in the scope by which they are expected to be used. In the case of local variables, these variables are generally called from within functions and are disposable, which is to say they're only useful when data is passed through a function and into the variables. For instance, the following example sets a local variable.
   function helloWorld()
   {
      $variable = "Hello";
      echo $variable;
   }
   
   helloWorld();
   echo $variable;

The first instance of echo would return a value of "Hello" while the second instance would return a NULL value. This demonstrates how data saved in a local scope is only available within the limits of its scope.

Global Variables

Global variables can be called throughout PHP files (granted they're within the same file throughput) by using the global identifier, declaring the variable outside of a local scope, or by using the $GLOBALS array.
   $variable = "Hello";
   echo $variable;

This will cause "Hello" to be displayed on the page.
   $variable = "Hello";
   $anotherVariable = "Goodbye";
   
   function helloWorld()
   {
      global $variable;
      $byeVariable = $GLOBALS['anotherVariable'];
      $worldVariable = "World";
      $variable .= $worldVariable;
      
      $variable = str_replace("Hello",$byeVariable,$variable);
   }
   helloWorld();
   echo $variable;

This should cause "GoodbyeWorld" to be displayed on the page. Note the use of the $GLOBALS array - variables are treated as array keys.

Operators

Operators are used when changing the value of variables and in conditional statements. At this point it is worth pointing out that a '.' in PHP signifies a combination of elements.
W3Schools (Abridged) wrote:
Arithmetic Operators
  • + => Addition => x=2; x+2; => x=4
  • - => Subtract => x=2; 5-x; => x=3
  • * => Multiply => x=4; x*5; => x=20
  • / => Division => x=15; x/5; => x=3
  • % => Modulus => x=5; x%2 => x=1
  • ++ => Increment => x=1; x++; => x=2
  • -- => Decrement => x=1; x--; => x=0
[Variable] Assignment Operators
  • = => x=y => x=y
  • += => x+=y => x=x+y
  • -= => x-=y => x=x-y
  • *= => x*=y => x=x*y
  • /= => x/= => x=x/y
  • .= => x.y => x=x.y
  • %= => x%y => x=x%y
Comparison Operators
  • == => is equal to
  • != => is not equal
  • <> => is not equal
  • > => is greater than
  • < => is less than
  • >= => is greater than or equal to
  • <= => is less than or equal to
Logical Operators
  • && => and => x=6; y=3; (x<10 && y>1) returns true
  • || => or => x=6; y=3; (x==5 || y==1) returns false
  • ! => not => x=6; y=3; !(x == y) returns true

Functions

Since functions have already been used within the guide, it seems necessary to include their basic structure in this guide. I feel the most effective way to show this to a novice is to demonstrate the creation of functions while also touching on a few library (included with PHP installs) functions which are used frequently.

Creating your own function

Functions all follow the same basic structure, regardless of what they end up doing within.
   function functionName($data)
   {
      /** This is where you would include
      * all of your fantastic, original code
      */
   }
   functionName();
   functionName('this will be passed into $data for use within the function');

All functions begin with the 'function' identifier. The function naming dynamic generally follows the same standard of captalization as variables, but is typically only alphabetical. The $data within the parenthesis is optional, whereas the parenthesis are not. When you call the function, any variables named within those parenthesis will both be expected and set locally to their respective values as per the function's call. Because these variables are required (disregarding them will cause an error), you may set a default.
   function functionName($data=null)
   {
      /** This is where you would include
      * all of your fantastic, original code
      */
   }
   functionName();
   functionName('this will be passed into $data for use within the function');

This way, the function will already have a value for $data, though it will be overrode by any data passed through the function. This function would be called using either of the two methods shown at the bottom of either example.

Frequently Used Library Functions

The PHP library has a huge selection of functions already built in which can be found at http://www.php.net. Here are a few commonly used functions with a short explanation of their use.
   str_replace($needle,$replacement,$haystack);
   str_replace("happy","sad","What a happy guide!"); // returns What a sad guide!

This is the String Replacement function. It works by finding the Needle in the Haystack and replacing it with the Replacement.
   include('file location');
   include('../filesToInclude/necessary.html');

The include function basically places the contents of a page into another page at the point where the function is called. The file location must be within your domain, for safety reasons. Therefore, there should never be a "http://" or "www.domain.com" anywhere in there. This is particularly useful when using a common PHP file among many PHP pages. Rather than having duplicates of a function on every page, you can simply Include a page containing that function and it will be processed as if it were always a part of that page.

It's worth mentioning that in PHP, the ".." is regarded as one layer up in respect to the current directory. So if a file is in http://www.runevillage.com/files/secrets/ and you call "../file.html", it will look for "/files/file.html". In the case of only using "/file" it should look for "http://www.runevillage.com/file.html."
   switch('example')
   {
      case 'text':
         echo "Text case";
      break;
      
      case 'example':
         echo "Hello World";
      break;
      
      case '':
      default:
         echo "What";
      break;
   }

The switch function is considered to be slow, but is utilized extensively on RV as the best method of deciphering page content. Within the switch's parenthesis is the data passed through the switch - it is typically a variable with a string value. Each case looks for the processed string to be equal to the value within the single quotes while the "break;" is used to stop the PHP code within that case to flow over. In the last case, the lack of a "break;" shows that this behavior should be used as both the default and whenever the processed data is an empty string.
   header("Location: http://www.RuneVillage.com/");

This function sends a header to the browser basically telling it where it should be. If the page happens to not be the specified location, you're quickly redirected to the appropriate page. This is useful for limiting access to pages and acting as redirects within PHP codes incase of user data errors.

Further Information

For further information, I would suggest checking both http://www.w3schools.com/php and http://www.php.net as they're comprehensive and show standards and often have examples of function uses.

Special Thanks
Razick - Additional information / Technical jargon

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Last edited by Demon on November 11th, 2011, 9:31 pm, edited 4 times in total.
Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 10th, 2011, 8:34 pm 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
So... this is a result of having too much time on my hands and waiting for people to reply to staff topics. >.>

Let me know if I made an error (I didn't test any of my examples) or a statement is less than correct. Also feel free to correct bad usage (like not using a standard form).

If you have any specific examples of scenarios you'd like me to include / elaborate on, feel free to ask. I'm sure myself or one of the other coders will answer! :awesome:

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 11th, 2011, 8:37 pm 
Squire
Squire
User avatar

Joined: May 29th, 2010, 3:37 pm
Posts: 135
Gender: Male
Status: Offline

Donor: Guardian (2011)
I just scanned over it, I might look at it closer later. Looks like a good start.

Quote:
By including the (int) or (integer) infront of the content to be forced into INTEGER format, it actually changes the content to reflect a numeric number and will return as int(1) in the example.


It should be noted in your guide that this is called casting.


Top
 Profile WWW 
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 11th, 2011, 9:27 pm 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
Razick wrote:
I just scanned over it, I might look at it closer later. Looks like a good start.

There's so much I felt I should mention, but it was already getting really lengthy that I left it to those basics. That's more or less enough to get a fairly decent foundation in working with PHP. Knowing these things and having the ability to trial-and-error would have been rather nice when I was first learning. :P

Razick wrote:
It should be noted in your guide that this is called casting.

Thanks for the input! I updated the guide to include that. ;D

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 12th, 2011, 9:40 am 
Squire
Squire
User avatar

Joined: May 29th, 2010, 3:37 pm
Posts: 135
Gender: Male
Status: Offline

Donor: Guardian (2011)
Yep. It's a good way to get started and decide if you like the language before buying expensive books.

If you added one thing, I would suggest brief description of the uses and capabilities of PHP.

----

By the way, do you know of any good advanced PHP books/references?


Top
 Profile WWW 
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 12th, 2011, 9:58 am 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
I would have to say php.net is the best place to look for advanced PHP references. All plugins and expansion libraries are available there aswell as all PHP-related updates and standards.

Pretty much anything you could need is in there, I would imagine. They're relatively good at giving useable examples too (if not, look in the comments).

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 14th, 2011, 11:26 pm 
O_o
Clan Chat Moderator
Clan Chat Moderator
User avatar

Joined: June 22nd, 2005, 8:18 pm
Posts: 2,755
Gender: Male
Status: Offline

Donor: Prince (2011)
Friend of Hiker
Looks like a great starter guide... One suggestion I have for you is to talk about a few of the global variables that are of great importance to most PHP scripts ($_SESSION, $_POST, $_GET come to mind). Since dynamic pages typically have user interaction, explaining a bit on how to use those variables (you use session_start(); in the first code snippet but don't explain it much), it'd really round out the guide.

__________________
Image
Queen Black Dragon Kill Log


Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 15th, 2011, 1:08 am 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
True - I'd forgotten about those.

Thanks ventrue :awesome: I'll add that when I get a chance.

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Top
 Profile
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 19th, 2011, 12:18 pm 
Host Lord
Page
Page
User avatar

Joined: May 11th, 2005, 7:34 pm
Posts: 93
Location: Huntsville, Alabama
Gender: Male
Status: Offline
Looks good... one thing in particular to me is that you didn't cover alternate file inclusion methods like require() and require_once(). So many people learn PHP these days thinking include() is the only way to display content or access functions/classes from other pages, when in fact include() should probably be the least used method of them all.

__________________
Looking to start a website?
Click the link below to start your own .com, .org, or .net website for $1.95/month
http://www.sitepearl.com


Top
 Profile WWW 
 

 Post subject: Re: PHP Guide [Abridged]
PostPosted: November 19th, 2011, 1:21 pm 
:D Panda tyme!
Staff Elder
Staff Elder
User avatar

Joined: April 18th, 2004, 4:29 pm
Posts: 1,036
Gender: Male
Status: Offline

Donor: Guardian (2011)
That really depends on the page you're including and what it's being used for. You don't have to require the content to load in some cases as it'll give you a fatal error if it doesn't load. (Not necessary in all cases). Worth noting though, thanks.

__________________
Hidden: 
Jackstick wrote:
Nice. It's like codeporn.

Hidden: 
n00b 4 m1nin wrote:
Dakota Lesmercy wrote:
IS that technically called slavery?

Dakota.


Slavery with payment and education, the perfect disguise.

Hidden: 
Milton Jones wrote:
If you're being chased by a police dog, try not to go through a tunnel, then on to a little seesaw, then jump through a hoop of fire. They're trained for that!


and this is me testing fun stuff.


Top
 Profile
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  Page 1 of 1
 [ 10 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to:  

cron
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
The Village and this web site are © 2002-2012

ThePub 2.0 - Designed by Goten & Jackstick. Coded by Glodenox & Henner.
With many thanks to the Website Team!