Webmaster Key - Discussion Forums


Welcome, Guest. Please login or register.
Did you miss your activation email?
February 09, 2012, 07:07:47 PM

Login with username, password and session length
Welceome to Forums!

Important information for guests and new members:

In order to understand the full benefits of becoming an active member of this forum, please review the following information on guest and new member restrictions. These forum changes have been prompted by an overwhelming and unreasonable amount of bot postings and incoherent guest spam messages. We wish to prevent these events from happening in the future and make our community a more comfortable place for all of our members.

For guests:

Guests are not allowed to open new topics, polls, or posts attachments.
If you wish to open up new discussions on this forum, we encourage you to register.

For new members:

New members with less than five posts are not allowed to modify additional profile information such as avatars, contact information, biographies, and signatures. However, new members are encouraged to post their own topics or reply to topics initiated by other members. Become active on the forums and 5 posts should be an easy task!

We are a diverse community with members from all over the world. We encourage new ideas and interesting conversation. Do not be afraid to post webmaster/computer-related questions or problems, as our active members are always willing to help when they are able. Interested? Join us.

+ Webmaster Key Forums
|-+ Webmaster Corner
| |-+ Site Design and Web Authoring
| | |-+ Coding Talk
| | | |-+ Simple guide to PHP coding
0 Members and 1 Guest are viewing this topic. « previous next »
Pages: [1] 2  All Go Down Stumble Upon! Digg It! del.icio.us! Add to Technorati! ReddIt!  Send this topic Print
Author Topic: Simple guide to PHP coding  (Read 17189 times)
Andy
Administrator
Veteran
*****
Posts: 5 752



« on: April 13, 2006, 11:56:10 AM »

PHP is a server-side scripting language which I find easier to code that Javascript. Unlike Javascript, it can't be turned off by a web browser but it means your server has to do all the work. For example it's useful to use Javascript as a filter between the client and your website to validate form data before it is sent.

To use PHP, your web host needs to support it. To find out if this is the case, upload the following text file to your site but call it pinfo.php

Code:
<?php

phpinfo
();

?>


Then open this page in your browser i.e.
http://yoursiteurl.net/pinfo.php

If you get a big list of all the details of your php installation then your host supports PHP.  Smiley

To include php code in your web pages you simply insert the code anywhere in the page but the file has to have the .php extension rather than .htm etc.

Here's some "hello world" code to test it out:

Code:
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>My First PHP Page</h1>
<p>
<?php
#this is not the easiest way to do this!
$x "Hel"."lo";
$y "World";
echo 
"Your PHP code says: $x $y!\n";
?>

</p>
</body>
</html>

Save this to a file called hello.php and upload it to your site to try it out.
http://yoursiteurl.net/hello.php

Notice I added a comment in the code and used some variables $x and $y.

I also used the string joining symbol (dot) to make the hello from 2 other strings.

Using double quotes with the echo command means the variables are inserted in the output text rather than the literal $x etc. I also added a newline character \n so the code looks clean when you view the source. Even though this has no effect on the web page.

So hopefully this will get you started with PHP coding. For futher reference you can browse the online documentation at http://www.php.net/manual/en/

Next time I would like to post about how to use PHP with forms since that is one of the most common uses for it i.e. how to process form data after the submit button was clicked.  Grin
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #1 on: April 15, 2006, 06:02:27 AM »

When using forms with PHP it's best to use the POST method to send data. This data is then accessed via the $_POST[] array.

Here is today's code:

Code:
<html>
<head>
<title>PHP Forms</title>
</head>
<body>
<?php
if (isset($_POST['visitor'])){
  
$visitor $_POST['visitor'];
  echo 
"<h1>Hello $visitor!</h1>\n";
} else {
?>


<form action="" method="post">
Please enter your name: <input type="text" name="visitor" value="" maxlength="32" />
<button type="submit">Send</button>
</form>

<?php
}
?>

</body>
</html>

The form has an input box and a submit button. I named the input box visitor.
When somebody enters text and clicks the submit button the action is to reload this same page (no url was specified) with the visitor value sent invisibly to the POST array.

The code first checks to see if the posted data exists. If it does then, the visitor value is extracted and used in the echo statement to display a message on the page. If the post data was not sent yet, the else part of the code is executed.

At this point we jump out of PHP and process the HTML for the form. Then we jump back into PHP to complete the else section of code with a closing }

To try this code out, save it as phpform.php and upload to your web space. Then open it in your browser with something like:
http://yoursiteurl.net/phpform.php

In BASIC programming you have:
IF condition THEN statement ELSE statement ENDIF

In PHP we have:
if (condition){
  do this
} else {
  do that
}

It's the same as the C programming language in this case.

So, this shows you an easy way to get some user interaction on your site.

Maybe next time I'll show you how to use PHP with a MySQL database?  Cool
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #2 on: April 16, 2006, 11:07:18 AM »

Ok, here's how to use PHP with a MySql database.

First of all you need to check you have a database available with your hosting and get the database user name and password.

Also, it is usual to have an online tool called PHPMyAdmin that you access via your webhosting control panel. This lets you create database tables, insert data, delete data and browse the data etc.

When I have time I hope to post a simple cut and paste piece of code that you can drop into your PHPMyAdmin interface to make a demo database.

What I am going to do here is show you how to connect to an existing database and list some data on a web page.

The first thing to do is create a file called db.php to store the sensitive username and password in.

The contents of this file should look like this:
Code:
<?php
function open_db() {
mysql_connect('localhost','username','password')
or die("Can't connect to server");
mysql_select_db('database name')
or die("Can't open database");
}

function 
close_db() {
mysql_close();
}
?>


You need to replace the username, password and database name with the values for your particular database. I also created some functions that allow us to easily connect and disconnect from the database i.e. open_db() and close_db()

After uploading this file, check that the contents cannot be seen by anyone trying to open it with say:
http://yoursiteur.net/db.php

You should not see anything on the web page. For added protection of your database login details, it's best to change the file permissions to the minimum required for operation of your scripts. It's a subject beyond the scope of this simple tutorial but a search for info. about CHMOD may be useful if you are interested.

Now, to use the database we will include this file in our scripts. The reason we keep it separate is to make it near-impossible for bugs in our code to reveal the file contents and also, this file saves us duplication of code when we have several script files that access the database.

Imagine our database contains a stock list for a warehouse or shop and we want to list the stock items and the quantities of each. This example script shows how it may be done:
Code:
<?php
include('db.php');
?>


<html>
<head>
<title>PHP Database Example</title>
</head>
<body>
<?php

open_db
();
$q "SELECT item, quantity FROM stock WHERE quantity > 0";
$r mysql_query($q);
close_db();

echo 
"<table>\n<tr><th>Item</th><th>Stock Level</th></tr>\n";

$rows mysql_num_rows($r);
for (
$i 0$i $rows$i++) {
$data mysql_fetch_object($r);
$item $data->item;
$quantity $data->quantity;
echo "<tr><td>$item</td><td>$quantity</td></tr>\n";
}

echo 
"</table>\n";

?>

</body>
</html>

Notice the included file is before the HTML. It doesn't have to be here but it's a convenient place to execute PHP code that doesn't produce any HTML to keep the page code neater and to allow us to do some security checks on form data for example before we output the page to the browser.

To get to the data in the database, we use our function open_db() to connect to the database. Then we run a database query to get the data we want. Once we did this, we close the connection to the database with our close_db() function.

mysql_query() is the PHP function we are using to request the data.
We stored our MySQL query string in the variable $q. When you are debugging scripts, it can be helpful to print the value of $q to the screen using the echo function.

After we got the data, we use the echo function to output some HTML to start a table.

Next we check how many rows of data were returned from the database in response to our query. Hopefully it is more than zero!
We use the PHP function mysql_num_rows() for this.

p.s. if there was any problem connecting to the database, you would get them displayed on the browser window. Most likely is it cannot connect because there is no database, no table called 'stock' or incorrect login details were specified.

Next we loop through the rows pulling out the data we want from the result of our query $r.
There are various ways to do this. I usually fetch the data as a key->value pair array and grab the values I want using the method as per the code.
These values are extracted from the array into local variables that are then used in the echo statements to print the HTML of the table rows to the web page.

After the loop has completed. We have a final echo statement to complete the table. Then we exit PHP and complete the HTML of the page.

This piece of code is our web page. So it might be called stock-list.php for example.

That may be alot to take in but it is the bare-bones of a database-enabled web page.

The language used in the MySQL query is not PHP but SQL (Structured Query Language). It's a common database language that allows you to form simple or complex database queries. The same language used with PHPMySQL.

I probably won't cover much more on databases since it's a vast subject and it's probably better if I covered basic PHP programming tips from now on.

Anyway, stay tuned...  Grin

« Last Edit: December 07, 2006, 01:14:49 PM by Andy » Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #3 on: April 18, 2006, 12:37:02 PM »

Here's just some stuff to look forward to in future posts:

  • how to remember the visitor between pages as they surf your site
  • how to read and write to files on your web server
  • how to display information about the visitor


Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #4 on: April 20, 2006, 02:20:02 PM »

Here's a cool feature of PHP:

How to preserve data between pages without using databases or saving to files.

Code:
<?php
session_start
();

$_SESSION['visited'] = 'YES';
?>


This code saves a value that is preserved as long as the current visitor is on your site.

So on another page you can tell if they visited the other page:
Code:
<?php
session_start
();

if (isset(
$_SESSION['visited'] )){
  echo 
"Thanks for continuing to surf my site!";
}

Or you can use PHP sessions to store any other data you want to keep between pages whilst this visitor surfs.

e.g. (on another page)
Code:
<?php
session_start
();

$answer "NO!"//default answer

echo "<p>The man from Del Monte said: ";

if (isset(
$_SESSION['visited'] )){
  
$answer $_SESSION['visited'];
}

echo 
"$answer</p>";
?>

« Last Edit: April 20, 2006, 02:23:44 PM by Andy » Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #5 on: April 21, 2006, 12:15:24 PM »

Today's topic is about how to read and write to files  Smiley

So you can use this for say a hit counter. Here's how to do it:

Save this code as a file called hitcounter.php in a directory called log:

Code:
<?php
function hitcounter(){
//hit counter script

define("MAXCOUNT",10);  //the max count value *

$fn "hitcount.txt";  //the filename to record the hit count

// create new file if necessary
if (!file_exists($fn)) {
   
$fp fopen ($fn"w");  //create a new file to write to
   
$fw fwrite($fp'0');  //write an initial count value of zero to the file
   
fclose($fp);  //close the file
}

//fetch current count
$fp fopen($fn,"r");  //open the file for reading
$count = (int) fgets($fp); //read the data in the file and force the value to be an integer
echo "$count";  //output the value to the web page that runs this function
fclose($fp);  //close the file

//increment the count
$count++;  //this is shorthand for the variable $count = $count + 1

if ($counter MAXCOUNT$count 0//loop back to zero if max count value is reached *

//save the count
$fp fopen($fn,"w"); //open the file for writing
$fw fwrite($fp$count); //over-write the file contents with the new value
fclose($fp);  //close the file, just like you would do at home ;-)
//end the function definition
?>
  //end the PHP code

This file creates a PHP function that you can include on any page on your site to log total hits.

I added comments in the code instead of describing it here. Hopefully it makes sense.

I adapted this code from a banner rotation script I was writing so you need to delete the lines highlighted with an * if you want a hit counter. I left these lines in so you can see how to code a looping counter.

Also, for this script to work, it needs to be saved in a directory with CHMOD settings of 777  Tongue This will allow the script to initially create the hitcount.txt and write values to it. If you use a database, you don't have to worry about issues like this.

So if you save it to a directory called log in the root of your site, you can reference this script with: log/hitcounter.php

To use it on a page, try it out with a page coded like this:
Code:
<?php
include ("log/hitcounter.php"); //include the hitcounter function
?>

<html>
<head>
<title>Untitled</title>
</head>
<body>
<h2>Hits so far:
<?php
hitcounter
(); //run the hitcounter function with no values needed to pass to it. It "echos" the count value to the page via the echo statement in the function!
?>

</h2>
</body>
</html>

A quick recap:
Referring to earlier tutorial posts, we learn't to transfer data from one page to another using forms, then we learn't how to access data anytime from a database, then we learn't how to keep data available between pages as a particular visitor is surfing our site. Now we learn't how to store semi-permanent data for everybody coming to our site like you can do with a database, but using files.

As a side-note I'd like to say that using files is easy for very simple tasks like hit counters, but databases are the way to go if you are storing information such as catalogs and any other data that you want to exract according to rules and various criteria. Plus databases are more secure and the code is written by teams of developers to keep it updated according to the latest security theats and features.
« Last Edit: February 06, 2008, 08:54:51 AM by Andy » Report to moderator   Logged

Rifat
Jr. Member
*
Posts: 20


« Reply #6 on: June 23, 2006, 07:40:26 AM »

Thanks this will be helpful in the near future when i start learning it, also going to learn some Ruby.
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #7 on: June 23, 2006, 11:14:40 AM »

No problem  Smiley

I'm glad to hear you are going to study PHP and Ruby.

One thing I didn't mention in my tutorial is that for large projects OOP techniques can be used with PHP to reduce errors and contain working blocks of code in modules that can be re-used by other programmers.

OOP is Object Orientated Programming where lumps of code are encapsulated in re-useable objects like mechanical parts assembled and shipped as a car engine. You just need to know how the object works and how to connect to it to use it.
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #8 on: August 25, 2006, 01:36:05 PM »

I just coded some nifty stuff to rotate 2 banners but only one of them was to show up on Saturday  Grin

It uses the date function and the rand function.

The power of php and the simplicity is mind-blowing. It's the coolest programming language I ever used and the online documentation really makes it easy to look up functions and get code examples.

Anyway, here is the jist of my code:
Code:
<?php
if ((!= date('w'))& rand()&1){ //generate 0 or 1 randomly unless it's Saturday (day 6 in this way of using the date function)
  
echo "banner A";
} else { 
//sat or zero (false)
  
echo "banner B";
}
?>

Report to moderator   Logged

mic_comte
Contributor
Jr. Member
***
Posts: 32



WWW
« Reply #9 on: June 01, 2007, 08:02:12 AM »

 Hi,
Thanks for your tutorial, this is very usefull.
Here is a very simple script I wrote which can be usefull for multilingual sites. The problem is that when you want to add your site to directories, some of them only accept the root address. So it is usefull to make an automatic redirection on an index page in the relevant language, depending of the browser's language preference.

Here is the script:
<?php
$lang = getenv('HTTP_ACCEPT_LANGUAGE');
if ( substr ($lang, 0, 2) == 'fr' )
{
   header("Location: http://www.braquedubourbonnais.info/fr/index.htm");
}
else
{
   header("Location: http://www.braquedubourbonnais.info/en/index.htm");
}
?>
Report to moderator   Logged

iaimang
Limited Member

Posts: 7


« Reply #10 on: August 23, 2007, 07:52:56 PM »

You should try writing some php security tips.
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #11 on: August 24, 2007, 12:45:43 PM »

Quote
You should try writing some php security tips.

Here is a useful article about preventing MySQL injection attacks:
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

More at PHP.net: http://jp2.php.net/manual/en/function.mysql-real-escape-string.php

My solution is to filter all POSTed variables in the header code of my website since only POSTed vars in my case are used in MYSQL queries. I use GET to select an action and POST for data.

Here is the one-liner to filter the POST vars:

Code:
<?php
foreach ($_POST as $key => $value$_POST[$key] = mysql_real_escape_string($_POST[$key]);
?>


This should work for any PHP script that interfaces with a MySQL database.

It's easy to place this right at the start of every page if you include it in a header file in your template. I did a quick test and it seemed to work OK for me.
« Last Edit: January 31, 2008, 09:54:24 AM by Andy » Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #12 on: November 06, 2007, 03:08:00 PM »

Today I posted about how to track clicks on links using PHP at: http://www.adscube.com/testing/tracking-clicks
Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #13 on: February 06, 2008, 09:08:10 AM »

If you want to speed up the responses of your PHP pages to user input, you can use Ajax.

This combines PHP and Javascript to dynamically update HTML elements on your page. For example, you tag a text area with an ID and then your code updates the text area without reloading the whole page.

A great example of this is Google Maps where the map is updated as you pan around it or zoom in and out.

Since writing the above tutorial, I found some other ways to handle text which is handy:

Code:
<?php
$text 
"hello",$string,'some "example text" here' $x ' additional text.' CONSTANT_VALUE "\n New Line x=$x";
$text .= "The End!";
die(
$text);
?>

Report to moderator   Logged

Andy
Administrator
Veteran
*****
Posts: 5 752



« Reply #14 on: February 19, 2008, 05:00:16 AM »

If you re-display the user-entered text in a text input element it can create problems. For example, if a user enters:
Code:
><h1>H1</h1>
it can break your code by closing the input tag and inserting extra code into your web page.

Example, easily hacked form (save as test.php):
Quote
<html><body>
<form method="post">
<input type="text" name="example"><?php echo $_POST['example']; ?></input>
<input type="submit" />
</form>
</body>
</html>

To filter any html, you can add this code in your header:

Code:
<?php
foreach ($_POST as $key => $value$_POST[$key] = htmlentities($value); // Prevent sql injection
?>
Report to moderator   Logged

Pages: [1] 2  All Go Up Stumble Upon! Digg It! del.icio.us! Add to Technorati! ReddIt!  Send this topic Print 
+ Webmaster Key Forums
|-+ Webmaster Corner
| |-+ Site Design and Web Authoring
| | |-+ Coding Talk
| | | |-+ Simple guide to PHP coding

Jump to:  
« previous next »


Our Partners
RelmaxTOP Ranking System Web Hosting RelmaxTOP Ranking System
Staff Sites
12Noon[12Noon Gallery] Andy[Urgentclick]
Tamuril[Tamuril's Digital Art Exhibit] Sensovision
Powered by MySQL Powered by PHP We are hosted by Relmax Inc. |Our Privacy Policy | Sitemap
Powered by SMF 1.1.9 | SMF © 2006-2009, Simple Machines LLC
Forum design by Tamuril © 2005.
Valid XHTML 1.0! Valid CSS!