Designing a Simple “Quote of the Day” Script in PHP

Simple Quote of the Day Script in PHP“Quote of
the Day” is quite an old feature, people put on their sites. And of course
people like it; I mean who doesn’t like to know the sayings of great persons!
In this post we’re going to design a complete quote of the day system
to place on our web site.


The title is a bit misleading actually, because most of these types of scripts
show a new quote (randomly) each time the page is requested and not once a day.
So if you incorporate this script on our web site, you’d see a different
quote each time you reload the page. You may easily change it to “actually”
display different quotes for each day only but people like that random one!


The working of the quote scrip is pretty simple. We first store a good number
of quote in an array (here we’ll just be storing a handful as an example).
Generate a random number from 0 to NUM_ELEMENTS_IN_ARRAY-1 and just show the
quote from the array with that index.


Here is the script:



<?php

//quotes

$quote[0]="All mankind is divided into three classes: 

those that are immovable, those that are movable and those that move."
;

$quote[1]="Beauties in vain their pretty eyes 

may roll....but merit wins the soul."
;

$quote[2]="Everything has its beauty but not 

everyone sees it."
;

$quote[3]="A superior man: \"He acts before 

he speaks and afterwards speaks according to his actions.\""
;

$quote[4]="It is not enough to succeed, others 

must fail."
;



//respective authos

$author[0]="Benjamin Franklin";

$author[1]="Alexander Pope";

$author[2]="Confucius";

$author[3]="Confucius";

$author[4]="Gore Vidal";



//total number of quotes

$total_quotes=count($quote);



//generate random number

srand((double)microtime()*1000000);

$random_number=rand(0,$total_quotes-1);



//format and display the quote

echo "<p><b><i>Quote of the Day:</i></b><br /> 

$quote[$random_number] <br /> <span style=\"text-align: right\"><i>By 

$author[$random_number]</i></span></p>"
;



?>





It was better to show the author of the quotes too so I’ve implemented
that also, using a second array to hold the author names in the same order.


One thing worth discussing about the above code is the random number generation
part. These two lines do that:


//generate random number


srand((double)microtime()*1000000);


$random_number=rand(0,$total_quotes-1);


Here, the first line is initializing the random number generator with some
large number generated by the microtime () function. The next line actually
generates the random number in the range (0, 5).


Rest of the script is fairly straightforward for you to understand.


That’s it for this post!


Related Articles:


Arrays and Array Processing in PHP

Arrays are a set of variables of the same data type. If you’ve ever programmed
before you should be knowing about it. but PHP takes arrays to the next level
by providing so many useful in-built features to operate on them, let’s
see some of them.


Types of Arrays


You should be familiar with the following type of array:


$ar[0]=1;


$ar[1]=10;



It is an example of numerically indexed array since numerical values are used
as indices to reference different elements of the array.


One other type of array that PHP supports is those having string indices which
sometimes may make indexing more meaningful.


$temp['jan']=21;


$temp['feb']=23;


$temp['mar']=24;


This type of array is also called Associative Arrays.


As is obvious, the array above should most probably be having temperatures
of different months. Had it been numerically indexed, it wouldn’t have
made that much sense. So you can use these types of arrays to make indexing
and referencing of elements more meaningful.


Initializing Arrays


You may simply initialize arrays like below:


$ar[0]=1;


$ar[1]=10;


Or use the following construct:


$ar=array(110);


This would make “$ar” have the following indices and values:


$ar[0]=1;


$ar[1]=10;



Same goes for associative arrays:


$ar['mon']=0;


$ar['tue']=2;


Or using the following method:


$ar=array('mon'=>0'tue'=>2);


“=>” is a symbol consisting of an equals to “=”
and a greater than “>” symbol.


Processing Arrays Using Loops


You can simply process all the elements of an array using the “for loop”
as:


$ar=array(110100100010000);


for(
$i=0$i<5$i++)


    echo 
$ar[$i];


Apart from this, there is one other variation of for loop that is designed
to process arrays, it is used like:


$ar=array(110100100010000);


foreach(
$ar as $a)


    echo 
$a;


In each iteration element of the array “$ar” gets stored in the
variable “$a” which gets printed out by the echo statement. This
loop processes all the elements storing different elements of array “$ar”
one-by-one into “$a”, in each iteration.


Related Articles:


String Manipulation Functions in PHP

In the previous post Properties
of String in PHP
, we were discussing about the different properties
of strings in PHP. String manipulation as you know, is an important part of
web programming. PHP being a web programming language thus provides good set
of string manipulation functions. In this post we’re going to discuss
some of those which arte frequently needed.


1. trim() function


Prototype: string trim (string str);


This function strips white spaces from the start and end of the string supplied
returning the resulting string..


When we have to take user input via form, it’d be a good idea to “trim”
the variables as extra white spaces sometimes creep in.


$name=trim($_GET['name'];


2. explode() function



Prototype: array explode (string separatorstring inputint limit);

The argument “limit” is optional.


This function splits the string “input” on a specified “separator”
and returns the different split strings as an array. The optional parameter
“limit” determines the maximum number of splitting you want.


$str="String Manipulation in PHP";


$arr=explode(" "$str);


Now $arr would be having the following values:


$arr[0]="String";


$arr[1]="Manipulation";


$arr[2]="in";


$arr[3]="PHP";


2. substr() function



Prototype: string substr (string strint startint length);


“length” is optional.


This function can help you take a sub string starting from the position “start”
till the end (or the “length”, if specified) from the string “str”.




$str="She is here";


$s=substr($str1);


$s2=substr($str15);



$s will contain “he is here”.

$s2 will contain “he is”.


Note: Position of first character is 0.


4. strlen() function



Prototype: int strlen (string str);


It returns the length of the string “str”.


$str="PHP is Great";


$len=strlen($str);


$len = 12 here.


5. strcmp() function


Prototype: int strcmp (string str1string str2);


This function does a case-sensitive comparison of the two strings passed “str1”
and “str2” and returns 0 if both are identical. It returns other
negative and positive values in other cases depending on which string is greater
in lexicographic order.


6. strpos() function


Prototype: int strpos (string haystackstring needleint offset);


“offset” is optional. “needle” is the string to be searched
for in “haystack”.


It returns the position of the first occurrence of the string “needle”
in “haystack” starting from the position “offset”, if
specified.


$haystack="We are discussing string manipulation functions in PHP";


$needle="are";


$pos=strpos($haystack$needle);


$pos will contain 3.


Note: Position of first character is 0.


Related Articles:


Parallelism with Map/Reduce

We explore the Map/Reduce approach to turn sequential algorithm into parallel

Map/Reduce Overview

Since the "reduce" operation need to accumulate results for the whole job, as well as communication overhead in sending and collecting data, Map/Reduce model is more suitable for long running, batch-oriented jobs.

In the Map/Reduce model, "parallelism" is achieved via a "split/sort/merge/join" process and is described as follows.
  • A MapReduce Job starts from a predefined set of Input data (usually sitting in some directory of a distributed file system). A master daemon (which is a central co-ordinator) is started and get the job configuration.
  • According to the job config, the master daemon will start multiple Mapper daemons as well as Reducer daemons in different machines. And then it start the input reader to read data from some DFS directory. The input reader will chunk the read data accordingly and send them to "randomly" chosen Mapper. This is the "split" phase and begins the parallelism.
  • After getting the data chunks, the mapper daemon will run a "user-supplied map function" and produce a collection of (key, value) pairs. Each item within this collection will be sorted according to the key and then send to the corresponding Reducer daemon. This is the "sort" phase.
  • All items with the same key will come to the same Reducer daemon, which collect all the items of that key and invoke a "user-supplied reduce function" and produce a single entry (key, aggregatedValue) as a result. This is the "merge" phase.
  • The output of reducer daemon will be collected by the Output writer, which is effective the "join" phase and ends the parallelism.
Here is an simple word-counting example ...






















Properties of String in PHP

1. Strings in PHP can either be enclose in single quotes (‘)
or double quotes (“).


   $str=’Strings in PHP’;    
$str2=”PHP”;

both of the above are valid strings in PHP.


2. Two strings can be concatenated or joined together with
the help of the “.” Dot operator.


   $str=”I Like “.”PHP”;    
$str2=$str.” a lot!;

Now, $str will have the string “I Like PHP a lot!”.


3. Guess what the following code will print


   $str=”String”;    
echo 
“This is $str”;

I bet many of you thought that it’d print “This is $str”.
But actually it is going to print “This is String” because variables
inside (“) double quotes are evaluated in PHP. If we had used (‘)
single quotes for the string like:


   $str=”String”;    
echo 
‘This is $str’;

It’d have printed “This is $str” as variable inside (“)
single quotes are not evaluated.


4. What would you do if you have to output a string like below:


He said “Wow!”


Would you write?


   echo “He said “Wow!””;    

Obviously, it won’t work.


To do this we will have to “escape” the two quotes inside the string
to tell PHP that they are a part of the string itself. How?, by using backslash
“\”.


   echo “He said ”Wow!””;    

Single quotes can also be used inside a string like below:


   echo “I’ll see you”;   

or


   echo ‘I’ll see you’;    

Now let’s us have a look at an example program which illustrates all
of these properties:


<?php

//strings

$str="This is a double quoted string";


$str2='This is a single quoted string';


$str3="He said \"Wow\"";


$str4="I'm here";


$str5='I\'m here';




//concatenating two strings

$join=$str.$str2;




//print the strings

echo "Joined string: $join <br />";


echo 
"Variable inside double quoted string: $str <br />";


echo 
'Variable inside single quoted string: $str <br />';


?>


Related Articles:


Bayesian Classifier

Classification Problem

Observing an instance x, determine its class. (e.g. Given a Email, determine if this is a spam).


Solution Approach

Based on probability theory, the solution is class[j] which has maximum chance to produce x.

Also, x can be represents by a set of observed features (a set of predicates). ie: x = a0 ^ a1 ^ a2 ... ^ ak

For each class[j], calculate j which maximize P(class[j] | x).

Also assume we have already gone through a learning stage where a lot of (x, class) has been taught

Note that X is a huge space, it is unlikely that we have seen x during training. Therefore, apply Bayes theorem:

P(class[j] | x) = P(x | class[j]) * P(class[j]) / P(x)

Since P(x) is the same for all j, we can remove P(x).

Find j to maximize: P(a0 ^ a1 ... ^ ak | class[j]) * P(class[j])

P(class[j]) = no_of_training_instances_whose_class_equals_classJ / total_no_of_training_instances. (This is easy to find).

Now P(a0 ^ a1 ... ^ ak | class[j]) is very hard to find because you probably have not met this combination during the training.

Lets say we have some domain knowledge and we understand the dependency relationship between a0, a1 ... We can make some assumptions.


Naive Bayes

So if we know a0, a1 ... ak are "independent of each other given knowing class == class[j], then

P(a0 ^ a1 ... ^ ak | class[j]) is same as P(a0 | class[j]) x P(a1 | class[j]) x .... x P(ak | class[j])

Now P(ak | class[j]) = no_of_instances_has_ak_and_classJ / no_of_instances_has_classJ (This is easy to find)


Spam Filtering Example

x is an Email. class[0] = spam, class[1] = non-spam

Lets break down the observed instance x as a vector of words.

  • x = ["Hello", "there", "welcome", .....]
  • a0 is position[0] == "Hello"
  • a1 is position[1] == "there"
  • a2 is position[2] == "welcome"

We assume position[k] == "Hello" is the same for all k and the occurrence of words are independent of each other given a particular class

Therefore, we try to compare between ...

  • P(a0 ^ a1 ... ^ ak | spam) * P(spam)
  • P(a0 ^ a1 ... ^ ak | nonspam) * P(nonspam)

P(a0 ^ a1 ... ^ak | spam) is the same as:

P(pos[0] == "Hello" | spam) x P(pos[1] == "there" | spam) x .... x P(ak | spam) * P(spam)

P(pos[0] == "Hello" | spam) = no_of_hello_in_spam_email / total_words_in_spam_email


Algorithm

Class NaiveBayes {

def initialize(word_dictionary) {
@word_dictionary = word_dictionary
}

def learn(doc, class) {
@total_instances += 1
@class_count[class] += 1
for each word in doc {
@word_count_by_class[class][word] += 1
@total_word[class] += 1
}
}

def classify(doc) {
for each class in ["spam", "nonspam"] {
prob[class] = @class_count[class] / @total_instances
for k in 0 .. doc.length {
word = doc[k]
prob[class] *= (@word_count[_by_class[class][word] + 1) / (@total_word[class] + @word_dictionary.length)
}
if max_prob < prob[class] {
max_prob = prob[class]
max_class = class
}
}
return max_class
}
}

Bayesian Network

Sometimes, assuming complete independence is too extreme. We need to relax this assumption by letting some possible dependencies among a0, a1 ... ak.

We can draw a dependency graph (called Bayesian network) between features. For example, if we know ak depends on a2, then a node a2 will have an arc pointing to ak.

P(a0 ^ a1 ... ^ ak | class[j]) = P(a0 | class[j]) x P(a1 | class[j]) x .... x P(ak | a2 ^ class[j])

Now P(ak | a2 ^ class[j]) = no_of_instances_has_ak_a2_and_classJ / no_of_instances_has_a2_and_classJ (this is harder to find than Naive Bayes but still much better).

How File Processing is done in PHP?

In the previous post’s (Designing
a Simple Order Form Application in PHP
) example we implemented the
file I/O for storing order information without discussing about it.


For those of you who were eager to know more about PHP File I/O read along,
this post has it.


File processing requires the following steps:



  1. Opening a file

  2. Doing the operation

  3. Closing the file


Opening a file


First of all we have to open the file before any operation (reading/writing)
can be done.


If you remember the previous post Designing
a Simple Order Form Application in PHP
, we had this line


//open file
$fp=fopen("orders.txt","a");

There we’re opening a file named “orders.txt” in the “append”
file mode. File modes tell PHP what we want to do with the file.


Some of the commonly used files modes along with what they mean is listed below:



























r For reading only, reading begins from the start of the file
r+ Reading and writing, beginning from the start of the file
w For writing only. Creates the file if it doesn’t exist. Deletes
existing content if it exists.
w+ For writing and writing. Creates the file if it doesn’t exist. Deletes
existing content if it exists.
a For appending (writing) beginning from the end of the existing data. Creates
the file if it doesn’t exist.
a+ For appending (writing) and reading beginning from the end of the existing
data. Creates the file if it doesn’t exist.

Doing the operation


Once the file is opened, we can any operation we want on it (of course those
which are supported for that file mode).


In the previous post Designing
a Simple Order Form Application in PHP
, we used


//write the data to the opened file
fputs($fp,$data);

Here first argument is the file resource pointer and second is the string to
be written to that file (pointed to by $fp).


fgets () is another function, it is used to read back information from file.
It has the following form:


$data=fgets($fp,999);

It reads one line at a time marked by “\n” which here gets stored
in the variable $data.


One line can also be when it encounters and EOF (End Of File) or when the line
has length greater than the maximum length (999) to be read.


Besides these functions that operate on a file, there are many others but we
won’t be discussing any more of them here.


Closing the file


after all the operations have been done we need to close the file. It is done
like below:


//close the file
fclose($fp);

$fp is a file resource that needs to be closed.


It tells PHP and the Operating System that we’ve performed the operations
we needed and it’s safe to close our link from that file.


Related Articles:


Designing a Simple Order Form Application in PHP

Designing a Simple Order Form Application in PHP


Ok guys, for this post we’re going to create a simple yet
complete order form page. Order forms are used on many sites to take customers
order online. Order forms should have the capability to take orders from visitors
regarding what items they want to purchase and store the information for further
processing.


For this post’s example, we are going to create an order form for a Book
Seller. The form will be designed to take order of five different items (books).
Our order form application should be able to take order of five different items
in any separate quantities tht user wants, it should also ask for shipping address
and name of the customer. It should then store the information provided in a
file along with the date and time order was placed. The application should also
be able to take any number of orders and store them all linearly for further
human processing.


For this, we need a front end of a HTML form to which the user would interact
and supply information regarding their purchase. These information would then
be sent to a PHP script that would show the order and save the same in a file.


Wait, did I say File? Yeah, PHP has a good support for file I/O on the server.


Below is the code for the HTML front-end page:




<html>

<head>

<title>My Book Store: Order Form</title>

</head>



<body>

<h1>My Book Store</h1>

<h2>Orders Form</h2>

<form name="form1"
id="form1" method="post"
action="takeorder.php">

<div align="center">

<table width="500"
border="0" cellspacing="0"
cellpadding="0">

<tr bgcolor="#CCCCCC">

<td height="19">NAME
OF BOOK</td>

<td>QUANTITY</td>

</tr>

<tr>

<td height="19">&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr>

<td width="202">Book
on PHP</td>

<td width="298"><input
name="q1" type="text"
id="q1" value="0"
size="5" />

</td>

</tr>

<tr>

<td>Book on MySQL</td>

<td><input
name="q2" type="text"
id="q2" value="0"
size="5" /> </td>

</tr>

<tr>

<td>Book on ASP</td>

<td><input
name="q3" type="text"
id="q3" value="0"
size="5" /> </td>

</tr>

<tr>

<td>Book on Web Development</td>

<td><input
name="q4" type="text"
id="q4" value="0"
size="5" /> </td>

</tr>

<tr>

<td>Book on AJAX</td>

<td><input
name="q5" type="text"
id="q5" value="0"
size="5" /> </td>

</tr>

<tr>

<td height="19">&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr bgcolor="#CCCCCC">

<td>Personal Information</td>

<td>&nbsp;</td>

</tr>

<tr>

<td height="19">&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr>

<td>Your Name</td>

<td><input
name="name" type="text"
id="name" size="40"
/> </td>

</tr>

<tr>

<td>Shipping Address</td>

<td><input
name="address" type="text"
id="address" size="40"
/> </td>

</tr>

</table>

</div>

<p align="center">

<input type="submit"
name="Submit" value="Submit"
/>

</p>

</form>

</body>

</html>




It has a form and several text boxes to take the quantity of different items,
shipping address and name of the customer.


NOTE: Quantity text boxes have been given default values of ‘0’.
And POST method is used to send data.


Now, below is the PHP script:



<html>

<head><title>Order Processed</title></head>

<body>

<h1>My Book Store</h1>

<h2>Order Successfully Processed</h2>

<?php

//have the POST data

$qty[0]=(int)$_POST['q1'];

$qty[1]=(int)$_POST['q2'];

$qty[2]=(int)$_POST['q3'];

$qty[3]=(int)$_POST['q4'];

$qty[4]=(int)$_POST['q5'];



//have the name and address

$customer_name=$_POST['name'];

$shipping_address=$_POST['address'];



//calculate total number of books

$total_qty=$qty[0]+$qty[1]+$qty[2]+$qty[3]+$qty[4];



//print out the order information

echo "<h3>".date("H:i
A, jS F Y"
)."</h3>";

echo "<p>Total Number of Books Requested: ".$total_qty."</p>";

echo "Items will ship to: <br />";

echo "<b>".$customer_name."</b><br
/>"
;

echo $shipping_address."<br />";



//open file

$fp=fopen("orders.txt","a");



//create a string of data to be written to the file

//format the data using "\n" to move to a new
line


//in the file

$data="---------ORDER START----------\n";

for($i=0;$i<count($qty);$i++)

$data.="Item ".$i.":
"
.$qty[$i]."\n";



$data.="\nName: ".$customer_name;

$data.="\nAddress: ".$shipping_address;

$data.="\n---------ORDER END----------\n\n\n";



//write th data to the opened file

fputs($fp,$data);



//close the file

fclose($fp);

?>

</body>

</html>


Look at this line


  $fp=fopen("orders.txt","a");

This function opens the file having the name provided in the first argument
in the mode provided in the second argument. We’re using “Append”
file mode which creates the file named (orders.txt) to start with (since it
doesn’t exist). In the second or consecutive runs however as the file
exists, new information is appended to the end of the file.


So, after two runs, the file (orders.txt) would contain the two separate order
information as below:


---------ORDER START----------

Item 0: 2

Item 1: 5

Item 2: 5

Item 3: 10

Item 4: 10


Name: Test User

Address: Test Address, Test Street, Test Town

---------ORDER END----------




---------ORDER START----------

Item 0: 10

Item 1: 2

Item 2: 1

Item 3: 5

Item 4: 5



Name: Someone Testing

Address: From Somewhere

---------ORDER END---------


If you put these types of script on your site, you’d have to check for
new orders every now and then by opening the orders.txt file. After the orders
have been processed you may delete the file, so that only unprocessed orders
remain in the file or you may do whatever you wish!


In the next post we’ll discuss about the file processing part that we’ve
used here.


Related Articles:


How does CMS Create Dynamic Pages II

This is the continuation of the last post How
does CMS Create Dynamic Pages
.


If you run the script given on that post (save it with the name “cms.php”),
you’d see a site like below:


An Example of How Content Managment System Create Pages Dynamically



As you can see, it’s a simple five page site of which all of the five
pages are available (only 3 are shown in the image though).


Isn’t it amazing for just one PHP script to create a five page site!


If you look at the code and try to understand, you see that the script is designed
to show the Homepage when no data is passed. It creates different pages from
the data in the arrays when the respective page is asked for, by passing p=0
to p=4 to the script.


We can create 10, 20, 100 or even a 1000 page site like this just from one
script. In fact most CMS do that.


Do remember however that the array storing the content was just to depict the
database and real sites would store content in database.


Did you notice the line $page=$_GET[‘p’];

As you know we have two methods of sending and receiving data “get”
and “post”. The question is why we are using “get” method
here.


Answer is, its necessary, as “get” method sends data via the URL
and we need to put links to those URLs on the page. Read An
Example of User Authentication System in PHP II
for more information.


Look at these lines:


   <a href="cms.php?p=0">Hello world</a>
<a href="cms.php?p=1">How does it look</a>
<a href="cms.php?p=2">PHP is great</a>
<a href="cms.php?p=3">Content Management System</a>
<a href="cms.php?p=4">CMS work this way!</a>

All links are sending data (p=0 to p=4) via “get” method. If we
use “post” method all URLs would be the same (cms.php) and since
normal links like this cannot send any data via “post” method, all
the links would point to the same page, which of course we don’t want.


Also, peoples bookmark pages from a site and pages created via “post”
method CANNOT be bookmarked.


This should have cleared any doubts you had regarding the use of “get”
method in that script.


That’s all we’ve for this post, do check back for updates.


Related Articles:


How does CMS Create Dynamic Pages

Content Management System (CMS) gives you an easier way to manage sites. It
gives you a nice front-end to write, publish and manage content while hiding
the technical details like FTP, HTML and other coding work. Most of the CMSs
have a web based front-end that means you can manage the whole site from within
the browser. Some examples of popular CMS are Joomla, Wordpress etc.


One major characteristic of CMS is the fact that it creates the whole site
dynamically, it means most (if not all) of the pages that the site has, are
created dynamically. Conventional way of creating site was to create different
HTML pages for each article (page) the site has. Contrary to that most CMS don’t
create different files for pages. They store the content in the Database and
create the pages from the Database. That means the content don’t reside
in pages or files but rather in the Database.


In this post we’re going to create a simple system that will help you
understand how pages are created from the content of the Database this way.
Please note that we’ll not create an example of CMS but just a part of
it.


Database in simple terms is something that is used for storing and retrieving
data. Since we haven’t discussed it yet we’ll not be using it rather
we’ll be using arrays. While arrays and databases have very things in
common, they both can store data, the only feature of the database we need for
this example.


Have a look at the following code:



<?php
//these arrays contain title of the articles
$content_title[0]="Hello world";
$content_title[1]="How does it look";
$content_title[2]="PHP is great";
$content_title[3]="Content Management System";
$content_title[4]="CMS work this way!";

//these contain the actual content
$content_main[0]="First article of this site.
blah blah.";
$content_main[1]="It looks great. blah blah.";
$content_main[2]="Yeah sure PHP is very useful.
blah blah.";
$content_main[3]="Yeah CMS is good and very useful
for managing sites without much technical knowledge.";
$content_main[4]="Yeah, it teaches you how a single
script can be used to create multi-page site.";

//the function count returns the number
//of elements (strings) in the array (5 in this case)
$num_pages=count($content_title);

//catch the data being passed
$page=$_GET['p'];

//isset function returns true if the
//variable has been assigned a value
if(!isset($page)) //if page is requested without any GET data
{//show the homepage
echo "<h1>My Site: Homepage</h1>";
echo "Welcome to my Web site. Below are the
links to pages to this site:</p>";
echo "<p><b>LINKS</b></p>";

//show the links to all the pages with
//title of contant as anchor text
//< br /> is used to break line or goto next line.
for($i=0;$i<$num_pages;$i++)
{
echo "<a href=\"cms.php?p=".$i."\">".
$content_title[$i]."</a> <br />";
}
}
else//if any page is requested
{
echo "<h1>My Site</h1>";
//show title of article
echo "<h2>".$content_title[$page]."</h2>";
//show the main content
echo "<p>".$content_main[$page]."</p>";
echo "<p><b>LINKS</b></p>";

//put the links
for($i=0;$i<$num_pages;$i++)
{
echo "<a href=\"cms.php?p=".$i."\">".
$content_title[$i]."</a> <br />";
}
}
?>


This article is to be continued in the next post where we’ll be discussing
about the working of this code.


[Update: Read the next part of this post How
does CMS Create Dynamic Pages II
]


Related Articles:


An Example of User Authentication System in PHP II

This is a short follow-up of the last post An
Example of User Authentication System in PHP
. In this post we’ll
talk about the two methods of from sending GET and POST and how thy affect the
way data sending


From the previous posts example, when we provided the username and password
and clicked on submit, we saw something like this:


User Authentication Example in PHP




If you look at the address bar, you can see the data (username and password)
being sent. Now, that’s not a good thing, if we are using a password box
to hide the password being entered then what its use is if it can be seen this
way!


The good thing is that with very few modifications, the data passed can be
made invisible (not to appear on the address bar). How? By using POST method
of data sending for the HTML form.


It can be done like below:



<html>
<head>
<title>Simple Uesr Authentication System</title>
</head>

<body>
<form name="form1" method="post" action="verify.php">
<p>Uername
<input name="user" type="text" id="user">
</p>
<p>Password
<input name="pass" type="password" id="pass">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>


As you cab see we’ve to change only one thing, just the method=”get”
to method=”post”.


And for the PHP script, we’ve got to access the data from the $_POST
[] array rather than from $_GET[].


The PHP script would look like this:



<?php
//define some constants
define("USERNAME", "goodjoe");
define("PASSWORD", "123456");
define("REALNAME", "Joe Burns");

//have the data being passed
$user=$_POST['user'];
$pass=$_POST['pass'];

//if username and password match
if($user==USERNAME && $pass==PASSWORD)
{
echo "<h1>Hello ".REALNAME."</h1>";
echo "<p>Nice to see you logging in again...</p>";
echo "<p>USER: <i>".USERNAME."</i></p>";
}
//if not
else
{
echo "<h1>Wrong username or password!</h1>";
}
?>


That’s it, now if you try to log in to this page; the address bar would
only show the name of the script as below:


User Authentication Example in PHP



This is because data is sent in another way which doesn’t need the address
bar (URL) to contain the data string.


Related Articles:


An Example of User Authentication System in PHP

In this post we’re going to create a very simple user authentication
system in PHP. It’d be like the one’s you see while logging in to
various sites/services (emails, forums, social networking sites etc)


User authentication is a way for sites to know who you are among the other
registered users and showing you relevant content (may be confidential). For
example it’s only you ho is authorized to see your emails because you
only know your authentication information.


In this post we’re going to create two files, a HTML page which will
collect the username and password in a form. These information will then be
send to a PHP script, which will verify and show the required information.


Below is the PHP code:



<?php
//define some constants
define("USERNAME", "goodjoe");
define("PASSWORD", "123456");
define("REALNAME", "Joe Burns");

//have the data being passed
$user=$_GET['user'];
$pass=$_GET['pass'];

//if username and password match
if($user==USERNAME && $pass==PASSWORD)
{
echo "<h1>Hello ".REALNAME."</h1>";
echo "<p>Nice to see you logging in again...</p>";
echo "<p>USER: <i>".USERNAME."</i></p>";
}
//if not
else
{
echo "<h1>Wrong username or password!</h1>";
}
?>


The code above is pretty straightforward. You may change the constants that
hold the user information.


Now, as you know from Taking
User Inputs to Create Personalized Pages II
, we need a HTML page with
a form to send information to this script. Here it is:



<html>
<head>
<title>Simple Uesr Authentication System</title>
</head>

<body>
<form name="form1" method="get" action="verify.php">
<p>Uername
<input name="user" type="text" id="user">
</p>
<p>Password
<input name="pass" type="password" id="pass">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>


Refer to Taking
User Inputs to Create Personalized Pages II
to know more about the
form tag. Note that the PHP script must be of the name as in the “action=…”
of the form tag and in the same directory as the HTML page.


Notice this line


   <input name="pass"    type="password" id="pass">

The above code creates an element that shows asterisks (*) on entering anything,
just like on other sites.


Now, we’re ready to put these files on the server and request the HTML
page. Do it and play with the page for a while!


Creating a Simple User Authentication System in PHP



This is how it’d look.


A few points to note:




  • This is a very simple example and holds the user information in the script
    itself (hard coded). Real sites store user information in Databases.




  • For real-life applications, we’d also need to use session variables
    or cookies.




[Update: Read the next post An
Example of User Authentication System in PHP II
]


Related Articles:


Taking User Inputs to Create Personalized Pages II

HTML Forms are a method of sending information from a page to a script. Forms
in HTML have the following form:



<form name="form1" id="form1" method="get" action="script.php">
</form>


here,



  • name=”form1” is the name of the form, may be anything

  • id=”form1” is usually same as the name of the form

  • method=”get” is the method by which sending of data will take
    place. It can also be “post”.

  • action=”script.php” is the name of the script to which the data
    is to be passed to.


A form can have many child elements such as input box, password box, check
box etc. a form almost always has a submit button which on clicking sends the
data entered in various elements of the form to the “action” script.


We’d created the script in the previous post Taking
User Inputs to Create Personalized Pages
, so we need not work on that,
here we’ll only create a HTML page having a form which will send the data
to that script. For this purpose, we need an input box for the user to enter
their name and obviously the submit button, as the form elements.


Look at the following HTML code:



<html>
<head>
<title>Enter Your Name</title>
</head>

<body>
<h2>Enter your name </h2>
<form name="form1" id="form1" method="get" action="name.php">
Name: <input name="name" type="text" />
<input name="submit" type="submit" id="submit" />
</form>
</body>
</html>


We have a form here which connects to the PHP script, we have an input box
with the name of the variable that the script takes and a submit button. That’s
it!


Put this HTML file and that script (form the post
Taking User Inputs to Create Personalized Pages
) in the same directory
on a server and you’re ready to go.


Open the HTML page in the browser type in the name, click on submit and bingo!
The script got the data via this form.


Now look at the address bar it’d be showing something like:


http://localhost/temp/lcp/name.php?name=PHP+Rocks&submit=Submit


So we can conclude that a form is a way of sending data to some script. The
value of each elements including the buttons is sent when submit button is pressed.


That’s it for this post guys. Do check back for updates!


Related Articles:


Check out this stream