- 2013-02-24 - Licence Fondamentale d'Informatique
samedi 2 mars 2013

Simple PHP forum


This tutorial shows the techniques required to make a simple PHP forum. It consists of four pages, one for displaying the forums, one for the topics, one for the replies and finally a page to post new topcis / replies.

Database

Below are the database tables that are required for this code.
CREATE TABLE  `main` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `name` text NOT NULL,
  `lastposter` varchar(200) NOT NULL,
  `lastpostdate` int(11) NOT NULL,
  `topics` int(11) NOT NULL default '0',
  `replies` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
)

CREATE TABLE `replies` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `topicid` int(11) unsigned,
  `message` text NOT NULL,
  `subject` text NOT NULL,
  `poster` text NOT NULL,
  `date` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`id`)
)

CREATE TABLE  `topics` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `forumid` int(11) unsigned,
  `message` text NOT NULL,
  `subject` text NOT NULL,
  `poster` text NOT NULL,
  `date` int(11) NOT NULL,
  `lastposter` varchar(200) NOT NULL,
  `lastpostdate` int(11) NOT NULL,
  `replies` int(11) unsigned NOT NULL,
  PRIMARY KEY  (`id`)
)

Displaying the forum list

This simple forum will consist of three elements. The first will be a list of forums, then each forum will have a list of topics and finally each topic will have a number of replies. We firstly need to set up the list of forums, these can be manually added to the database.
mysql_connect('localhost','user','password');
mysql_select_db('db');
$query1 = mysql_query('SELECT * FROM main ORDER BY id DESC'); 
This code connects to the database and selects the forums. We now need to display the information.
while ($output1 = mysql_fetch_assoc($query1))
This loop will get all the rows from the database and the loop will end when there are no rows left. Below is an example of getting the information from the database and printing it to the document. Note the link is to topics.php.
echo '<td><a href="topics.php?id='.$output1['id'].'">'.$output1['name'].'</a></td>';

Displaying topics

Now that the basic forums are set up we can list the topics for each one. The link from the main page sets an id variable that we can use to select the appropriate topics.
ob_start();
$id = (int) $_GET['id'];
if ($id < 1)
{
 header('Location: forum.php');
 exit();
}
ob_end_clean();
We start output buffering (ob_start()) to ensure that no headers are sent because if the topic id given is less than one, we will redirect the user to the main forum page.
mysql_connect('localhost','user','password');
mysql_select_db('db');
$output1 = mysql_fetch_assoc(mysql_query("SELECT name FROM main WHERE id = $id"));
echo $output1['name'];
Now that we have a topic id we can get all the topics that match that it. We firstly get the forum name associated with the id and print it out.
$query2 = mysql_query("SELECT * FROM topics WHERE forumid = '$id' ORDER BY id DESC");
$query3 = mysql_num_rows($query2);
Within the database table design for the topics there is a foreign key (called forumid) which links each topic to the id of the forum. Above the number of topics for the given forum is found. If there are no topics a message is displayed, otherwise the topics are printed out.
if ($query3 == 0)
 echo '<td colspan="5">No Topics</td>';
If there are no topics for this forum then we will inform the user. Otherwise a table is built with links to the replies for each topic. Note the link to replies.php. We will use mysql_fetch_assoc because we will refer to the fields in the array by name rather then by number.
while ($output2 = mysql_fetch_assoc($query2))
    echo '<td><a href="replies.php?id='.$output2['id'].'">'.$output2['subject'].'</a></td>';
if(empty($output2['lastposter']))
 echo '<td colspan="2">No replies</td>';
else {
    echo '<td>'.$output2['lastposter'].' @ '.date('d-m-y G:i', $output2['lastpostdate']).'</td>';
    echo '<td>'.$output2['replies'].'</td>';
}
We will keep track of the last poster for each forum and topic. If there are no posts a message is displayed otherwise the name and date of the last post is printed.
<form name="form1" id="form1" method="post" action="forumpost.php?type=topics&id=<? echo $id; ?>">
Finally on this page is the form that the user can use to post a new topic. It sends two pieces of information to the forum post page, the id of the topic and the type of post (in this case 'topic').

Displaying replies

This page is very similar to the topics page. It gets an id as an input which it uses to get all the replies. Each reply has a foreign key (topicid) which links to a particular topic and this is used to get all the relevant replies.
<form name="form1" id="form1" method="post" action="forumpost.php?type=replies&id=<? echo $id; ?>">
The form to post a reply is also very similar to the topics page, but the type is now set to 'replies' as this form can only post new replies for each topic.

Posting replies

Now that we have have set up the pages for the forum, topics and replies we need a page that will insert the new topics and replies into the database.
ob_start();
$id = (int) $_GET['id'];
$type = $_GET['type'];
if ($id < 1 || ($type != 'replies' && $type != 'topics'))
{
 header('Location: forum.php');
 exit();
}
ob_end_clean();
This code checks that the id is greater than one and that the type given is one of the two constants that we defined (topics or replies).
function clear($message)
{
 if(!get_magic_quotes_gpc())
  $message = addslashes($message);
 $message = strip_tags($message);
 $message = htmlentities($message);
 return trim($message);
}
We now define a function to check the user input for any HTML tags, and remove any quotes, so that the information can be put into the database.
if($type == 'topics')
{
 $query = mysql_fetch_assoc(mysql_query("SELECT topics FROM main WHERE id = '$id'"));
 $topics = $query['topics'] + 1;
 mysql_query("UPDATE main SET topics = '$topics', lastposter = '$poster',
              lastpostdate = '$date' WHERE id = '$id'");
 mysql_query("INSERT INTO topics (id , forumid , message , subject, poster, 
              date, lastposter, lastpostdate, replies)
              VALUES ('', '$id', '$message', '$subject','$poster', '$date', '', '', '0')");
 echo 'Topic Posted.<a href="topics.php?id='.$id.'">View Topic</a>';
If the type of post is a topic then we need to update multiple rows in the database. We firstly need to update the topics field of the forum to add one to the number of topics. We do this by using the id input to get the forum and the current number of topics. The topic count is incremented and the forum is updated (the current poster is also added as the latest poster and the last post date is updated). Finally the topic is added to the database.
else
{
 $query = mysql_fetch_assoc(mysql_query("SELECT replies, forumid FROM topics WHERE id = '$id'"));
 $replies = $query['replies'] + 1;
 $id2 =  $query['forumid'];
 mysql_query("UPDATE topics SET replies = '$replies', lastposter = '$poster',
              lastpostdate = '$date' WHERE id = '$id'");
 $query = mysql_fetch_array(mysql_query("SELECT replies FROM main WHERE id = '$id2'"));
 $replies = $query['replies'] + 1;
 mysql_query("UPDATE main SET replies = '$replies', lastposter = '$poster',
              lastpostdate = '$date' WHERE id = '$id2'");
 mysql_query("INSERT INTO replies (id , topicid, message, subject, poster, date)
              VALUES ('', '$id', '$message', '$subject','$poster', '$date')");
 echo 'Reply Posted.<a href="replies.php?id='.$id.'">View Reply</a>';
If the type of post is a reply then we need to do a similar database update but this time we need to add one to the number of replies. Using the id input we get the number of replies and the forum id from the related topic. We then update the number of replies and update the last poster and last post date fields to the current poster. Using the forum id we then also update the forum so that the last poster / last post date is updated and a total number of replies is kept. Finally the reply is added to the database.

Downloads

Source : 

http://www.pixelcode.co.uk/tutorials/Simple+PHP+forum.html

EasyPHP

EasyPHP is a WAMP package including the server-side scripting language PHP, the web server Apache, the SQL server MySQL, as well as development tools such as the database manager PhpMyAdmin, the debugger Xdebug and many others.

A Complete and Ready-to-Use Environment For PHP Developers

Nothing to configure. It's already done! You just need to download, intall ... and code. The administration page allows you to list the docroot, extensions,change the Apache port, the timezone, max execution time, error reporting,upload max filesize, add/remove alias and manage modules.
Download: EasyPHP

Wamp Server

WAMP installs automatically Apache ,PHP, MySQL database ,PHPmyadmin and SQLitemanager on your computer. It's principal aim is to allow you to easily discover the new version oh PHP : PHP5. WAMP5 comes with a service manager installed as a tray icon. It allows you to manage WAMP and access all services. 

When you install WAMP, all the files are copied in the directory you choose. Conf files are then modified to point to that directory. It also installs a "www" directory which will be your Document Root.wamp menuAt the end of the installation, WAMP will automatically install Apache and MySQL as services :
  • service' wampapache' : apache service
  • service 'wampmysql' : mysql service
WAMP's installation is compact. This means that all files are copied to WAMP's directory. Only the MySQL conf file (usually my.ini) is copied to the Windows directory but as "mywamp.ini" to avoid conflicts with other installs. 

Download: WAMP

Notepad++

Notepad++ is a good free text editor for programmer, which supports several programming languages and has many cool features. 

Notepad++

Features

  • WYSIWYG
  • User Defined Syntax Highlighting
  • Auto-completion
  • Multi-Document
  • Multi-View
  • Regular Expression Search/Replace supported
  • Full Drag 'N' Drop supported
  • Dynamic position of Views
  • File Status Auto-detection
  • Zoom in and zoom out
  • Bookmark
  • Brace and Indent guideline Highlighting
  • Macro recording and playback

Support language

C, C++, Java, C#, XML, HTML, PHP, CSS, makefile ASCII art (.nfo), doxygen, ini file, batch file, Javascript, ASP, VB/VBS, SQL, Objective-C, RC resource file, Pascal, Perl Python, Lua, TeX, TCL, Assembler, Ruby, Lisp, Scheme, Properties, Diff, Smalltalk, Postscript, VHDL, Ada, Caml, AutoIt, KiXtart, Matlab, Verilog, Haskell, InnoSetup, CMake

Plugin

Notepad++ also has many free plugin such as Function lists, Insetion, XML tool, Hex editor and more, you can see on a donwload page. 

Download: Notepad++

Encrypting Password using md5() function

Using md5(); function to make your login system more secure.

Syntax

$password="123456";

md5($password);

Use md5(); to encrypts password to make it more secure

Overview

Look at these two databases, it's the same person and same info, the first one we don't encrypt his password, but the second one we encrypted his password. 
When you encryte "john856" using this code, you'll see the result
"ad65d5054042fda44ba3fdc97cee80c6"

This is not a random result, everytime you encrypt the same password you will get the same result.

$password="john856";
$encrypt_password=md5($password);
echo $encrypt_password; 

Example - Login


This is an example Login with encrypted password, but don't forget to encrypt password and insert into database when your user sign up.

// username and password sent from form 

$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// encrypt password 
$encrypted_mypassword=md5($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);
You can learn to create login system here

PHP Login script tutorial

Learn to create a simple login system with php + mysql script, this tutorial is easy to follow, teach you step by step.

Overview

In this tutorial, we create 3 php files for testing our code.
1. main_login.php
2. checklogin.php
3. login_success.php

Steps
1. Create table "members" in database "test".
2. Create file main_login.php.
3. Create file checklogin.php.
4. Create file login_success.php.
5. Create file logout.php

STEP1: Create table "members"

For testing this code, we need to create database "test" and create table "members".
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
--
-- Dumping data for table `members`
--
INSERT INTO `members` VALUES (1, 'john', '1234');

STEP2: Create file main_login.php

The first file we need to create is "main_login.php" which is a login form.
############### Code
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

STEP3: Create file checklogin.php

We have a login form in step 2, when a user submit their username and password, PHP code in checklogin.php will check that this user exist in our database or not.

If user has the right username and password, then the code will register username and password in the session and redirect to "login_success.php". If username or password is wrong the system will show "Wrong Username or Password".

############### Code
<?php

$host="localhost";
 // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form 
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 

header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

STEP4: Create file login_success.php

User can't view this page if the session is not registered.

############### Code

// Check if session is not registered, redirect back to main page. 
// Put this code in first line of web page. 
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

<html>
<body>
Login Successful
</body>
</html>

STEP5: Create file Logout.php

If you want to logout, create this file. The code in this file will destroy the session.

// Put this code in first line of web page. 
<?php
session_start();
session_destroy();
?>

For PHP5 User - checklogin.php

############### Code
<?php

ob_start();
$host="localhost";
 // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword 
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 

header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>

Encrypting Password - Make your Login More Secure

Create database, table and managing MySQL database using phpMyAdmin

phpMyAdmin is a tool for managing MySQL database and free of charge, it's a web base tool. This tutorial you'll learn how to create database, create table include export(backup) MySQL database. 

phpMyAdmin is a tool written in PHP intended to handle the administration of MySQL over the Web. Currently it can create and drop databases, create/drop/alter tables, delete/edit/add fields, execute any SQL statement, manage keys on fields, manage privileges,export data into various formats.

If you install Wamp, Xammp or EasyPHP, phpMyAdmin is included in the package. If you manually installed Apache, PHP and MySQL, you can download phpMyAdmin at their officail site. (Click here to download)
phpMyAdmin

phpMyAdmin home

1: Create database using phpMyAdmin

mysql create database1. To create new database use this form, type database name then click "Create" button. In this example I create database name "test_create_DB".

2: Create table

Create table form
mysql create table
1. After created database. this form'll be display. Enter the name of table and number of field. In this example, I create table name "web_members" for store my web members and it have 4 fields (id, name, lastname, email)


Result after created table on database

3: Create table by runing SQL query

1. You can create table by run SQL query for example, put this code in the form and click "Go"

CREATE TABLE `web_members` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;
or browse from text file (read export database for creating text file (.sql))

4: Export database

In tab Export. You can export your database in many format like
- SQL (text file .sql)
- Latex
- Microsoft Exel 2000
- Microsoft Word 2000
- CVS for MS Exel
- CVS
- XML

Steps
1. Select table you want to export or select all table.
2. Select file format
3. Select save as file(if you want to save as a file if not select it'll show you only Sql query)
4. Select compression
- None
- zipped (.zip)
- gzipped (.gzip)

PHP User online tutorial

This tutorial show you php script that count how many users are active on your site.

Overview

In this tutorial, create 1 PHP file for testing this code.
1. user_online.php

Steps
1. Create table "user_online" in mysql in database "test".
2. Create file user_online.php.

STEP1: Create table "user_online"


CREATE TABLE `user_online` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'
) TYPE=MyISAM;

STEP2: Create file - user_online.php

############### Code
<?php

session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){

$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}

else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "User online : $count_user_online ";
// if over 10 minute, delete session 
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
// Open multiple browser page for result


// Close connection
mysql_close();
?>

PHP Upload single file

Simple PHP uploade file script.

Overview

In this tutorial, create 2 files
1. upload.php
2. upload_ac.php


Steps
1. Create file upload.php.
2. Create file upload_ac.php.
3. Create folder "upload" for store uploaded files.
4. CHMOD your upload folder to "777" by using your ftp software(change permission).

STEP1: Create file upload.php

############### Code

<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile" type="file" id="ufile" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

STEP2: Create file upload_ac.php

############### Code
<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif


$path= "upload/".$HTTP_POST_FILES['ufile']['name'];
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";

//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file


echo "File Name :".$HTTP_POST_FILES['ufile']['name']."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
echo "<img src=\"$path\" width=\"150\" height=\"150\">";
}
else
{
echo "Error";
}
}
?>

STEP3: CHMOD upload folder to 777 (change permission)

This step, do it when you upload to real server. This example, I use WS-FTP, right click at upload folder > FTP Commands > CHMOD(Unix)

PHP Multiple files upload

You can upload multiple files with one time submit. Array is a big role in this tutorial, let's see the scripts.

Overview

In this tutorial, create 2 files
1. multiple_upload.php
2. multiple_upload_ac.php


Steps
1. Create file multiple_upload.php
2. Create file multiple_upload_ac.php
3. Create folder "upload" for store uploaded files.
.4. CHMOD your upload folder to "777" by using your ftp software(change permission).

STEP1: Create file multiple_upload.php

############### Code

<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="multiple_upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

STEP2: Create file multiple_upload_ac.php

############### Code
<?php

//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif


$path1= "upload/".$HTTP_POST_FILES['ufile']['name'][0];
$path2= "upload/".$HTTP_POST_FILES['ufile']['name'][1];
$path3= "upload/".$HTTP_POST_FILES['ufile']['name'][2];

//copy file to where you want to store file
copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2);
copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3);

//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>";
echo "<img src=\"$path1\" width=\"150\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>";
echo "<img src=\"$path2\" width=\"150\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>";
echo "<img src=\"$path3\" width=\"150\" height=\"150\">";

///////////////////////////////////////////////////////

// Use this code to display the error or success.


$filesize1=$HTTP_POST_FILES['ufile']['size'][0];
$filesize2=$HTTP_POST_FILES['ufile']['size'][1];
$filesize3=$HTTP_POST_FILES['ufile']['size'][2];

if($filesize1 && $filesize2 && $filesize3 != 0)
{
echo "We have recieved your files";
}
else {
echo "ERROR.....";
}

//////////////////////////////////////////////

// What files that have a problem? (if found)


if($filesize1==0) {
echo "There're something error in your first file";
echo "<BR />";
}

if($filesize2==0) {
echo "There're something error in your second file";
echo "<BR />";
}

if($filesize3==0) {
echo "There're something error in your third file";
echo "<BR />";
}
?>

STEP3: CHMOD upload folder to 777 (change permission)

This step, do it when you upload to real server. This example, I use WS-FTP, right click at upload folder > FTP Commands > CHMOD(Unix)

PHP Limit upload file size

This upload form can limit upload file size.

Overview

In this tutorial, you have to create 2 files for testing code.
1. limit_upload.php
2. limit_upload_ac.php

Steps
1. Create file limit_upload.php
2. Create file limit_upload_ac.php
3. Create folder "upload" for store uploaded files.
4. CHMOD your upload folder to "777" by using your ftp software(change permission).

STEP1: Create file limit_upload.php

############### Code

<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="limit_upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>File Upload (Limit file size 50 K)</strong></td>
</tr>
<tr>
<td align="center">Select file
<input name="ufile" type="file" id="ufile" size="35" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

STEP2: Create file limit_upload_ac.php

############### Code
<?php

// Define file size limit 
$limit_size=50000;
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif

$path= "upload/".$HTTP_POST_FILES['ufile']['name'];

if($ufile !=none)
{

// Store upload file size in $file_size 
$file_size=$HTTP_POST_FILES['ufile']['size'];

if($file_size >= $limit_size){
echo "Your file size is over limit<BR>";
echo "Your file size = ".$file_size;
echo " K";
echo "<BR>File size limit = 50000 k";
}
else {

//copy file to where you want to store the file
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
echo "<img src=\"$path\" width=\"150\" height=\"150\">";
}
else
{
echo "Copy Error";
}
}
}
?>

STEP3: CHMOD upload folder to 777 (change permission)

This step, do it when you upload to real server. This example, I use WS-FTP, right click at upload folder > FTP Commands > CHMOD(Unix)

Creating a simple PHP guestbook (2/2)

Creating simple PHP guestbook.

STEP4: Create file viewguestbook.php

############### Code
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td><strong>View Guestbook | <a href="guestbook.php">Sign Guestbook</a> </strong></td>
</tr>
</table>
<br>

<?php

$host="localhost";
 // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="guestbook"; // Table name 
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
?>


<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td><table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td>ID</td>
<td>:</td>
<td><? echo $rows['id']; ?></td>
</tr>
<tr>
<td width="117">Name</td>
<td width="14">:</td>
<td width="357"><? echo $rows['name']; ?></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><? echo $rows['email']; ?></td>
</tr>
<tr>
<td valign="top">Comment</td>
<td valign="top">:</td>
<td><? echo $rows['comment']; ?></td>
</tr>
<tr>
<td valign="top">Date/Time </td>
<td valign="top">:</td>
<td><? echo $rows['datetime']; ?></td>
</tr>
</table></td>
</tr>
</table>

<?php
}
mysql_close(); 
//close database
?>

Creating a simple PHP guestbook (1/2)


Creating simple PHP guestbook.

Overview

In this tutorial, we have to create 3 files.
1. guestbook.php
2. addguestbook.php
3. viewguestbook.php

Steps
1. Create table name "guestbook" in database "test".
2. Create file guestbook.php.
3. Create file addguestbook. php.
4. Create file viewguestbook.php

STEP1: Set up database


CREATE TABLE `guestbook` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
`comment` longtext NOT NULL,
`datetime` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
If you don't know how to create database and table, read this tutorial

STEP2: Create file guestbook.php


############### Code
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td><strong>Test Sign Guestbook </strong></td>
</tr>
</table>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form id="form1" name="form1" method="post" action="addguestbook.php">
<td>
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td width="117">Name</td>
<td width="14">:</td>
<td width="357"><input name="name" type="text" id="name" size="40" /></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="email" type="text" id="email" size="40" /></td>
</tr>
<tr>
<td valign="top">Comment</td>
<td valign="top">:</td>
<td><textarea name="comment" cols="40" rows="3" id="comment"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td><strong><a href="viewguestbook.php">View Guestbook</a> </strong></td>
</tr>
</table>

STEP3: Create file addguestbook.php


############### Code
<?php
$host="localhost";
 // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="guestbook"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$sql="INSERT INTO $tbl_name(name, email, comment, datetime)VALUES('$name', '$email', '$comment', '$datetime')";
$result=mysql_query($sql);
//check if query successful 
if($result){
echo "Successful";
echo "<BR>";

// link to view guestbook page
echo "<a href='viewguestbook.php'>View guestbook</a>";
}

else {
echo "ERROR";
}
mysql_close();
?>
 
-