Wednesday, August 22, 2007

Mysql Database 2

Continued after part one http://phptuts.blogspot.com/2007/08/mysql-database-1.html.

One part 1 we learned how to connect a database connection with mysql.

Now on this part we will learn how to create tables, insert values into the database.

Creating table

See this Example care fully.
//connection arleady established...on part 1.
mysql_query("CREATE TABLE example(id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),name VARCHAR(30), age INT)"( or die(mysql_error());


Explanation
mysql_query();
This function is called for every query we o on database with php.

CREATE TABLE
This sql command craetes the tables in database
Syntax:
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1" "Constraint_for_column_1_optional" ,
"column 2" "data_type_for_column_2" "Constraint_for_column_1_optional",
...,PRIMARY KEY(column name) )

Here the first column is id , The INT determines that the data type is Integer .
NOT NULL is a Constraint which states that the values in this column cannot be nulled.

AUTO_INCREMENT is used so that each time a new entry is added the value will be incremented by 1.

PRIMARY KEY(id)
PRIMARY KEY is used as a unique identifier for the rows. Here we have made "id" the PRIMARY KEY for this table. This means that no two ids can be the same, or else we will run into trouble. This is why we made "id" an auto incrementing counter in the previous line of code.

the other field name is a VARCHAR which stands for variable character. "character" because it stores characters (letters, numbers, etc) and "variable" because you can store a varied amount of characters in the field (from 0 up to 30).


Hope you had understood how to create a table.Now we will insert values to it.

// Insert a row of information into the table "example" created above
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());

mysql_query("INSERT INTO example
(name, age) VALUES('Sandy Smith', '21' ) ")
or die(mysql_error());

mysql_query("INSERT INTO example
(name, age) VALUES('Bobby Wallace', '' ) ")
or die(mysql_error());

here we added 3 entries in the example table
stntax:
INSERT INTO tablename(columnname1, columnname2) VALUES('columnname1_value', 'columnname2_value' )

Note: the location and number of apostrophes and parentheses.If it don't match with field set and values mysql error will occur.
If you want to leave a blank value you must provide a blank quote as i did on third value, where i had leaved the age value blank. But be sure the field is not set to NOT NULL.

if you had any problem please leave a comment.

now after we had inserted values we will display the values through php. Which i will discuss on my nest part.
Copyright Ayon Baidya

Tuesday, August 21, 2007

Directory Lister Advanced


// false - don't allow switching to the parent-directory of this script

// true - allow simple switching to the parent-directory (via 'href')


$allow_parent = "false";


//configuration ends here---------------------------------------------------------------------------------------------------------------------------


//=======================================================================================

$path=$_GET["path"];

$SCRIPT_NAME=getenv("SCRIPT_NAME");

//put directory content in arrays-----------------------------------------------------------------------------------------------------------------

if (!isset($path)) { $path = "./"; }

if (!file_exists($path)) { echo "

File not found!

"; exit; }

if (strstr($path,"..")) { echo "

invalid path!

"; exit; }

$base_dir = getcwd();

if ($path=="/") { $path = "./"; }

chdir($path);

$current_dir = getcwd();

$directory = dir("./");

$directories_array = array();

$files_array = array();

while ($file = $directory->read()) {

if (is_dir($file) AND $file != ".") { $directories_array[] = $file; }

if (is_file($file)) { $files_array[] = $file; }

}

$directory->close();

//sort and output the arrays-----------------------------------------------------------------------------------------------------------------------

echo "

Directory listing for ".basename($current_dir)."

";

echo "";

echo "";

sort($directories_array);

foreach($directories_array as $value) {

if ($value=="..") { $new_path=strrev(substr(strstr(substr(strstr(strrev($path),"/"),1),"/"),1)); }

else { $new_path=$path.$value; }

if (($value != "..") OR ($base_dir != $current_dir)) {

echo ""; }

elseif ($allow_parent == "true") {

echo ""; }

}

sort($files_array);

foreach($files_array as $value) {

if($value != basename($SCRIPT_NAME) or $path!="./") {

$filesize=filesize($value);

if ($filesize > 1073741823) { $filesize = sprintf("%.1f",($filesize/1073741824))." GB"; }

elseif ($filesize > 1048575) { $filesize = sprintf("%.1f",($filesize/1048576))." MB"; }

elseif ($filesize > 1023) { $filesize = sprintf("%.1f",($filesize/1024))." kB"; }

else { $filesize = $filesize." byte"; }

echo "";

}

}

echo "
NameSizeDate
$value/".gmdate("d M Y H:i",filemtime($value))."
$value/".gmdate("d M Y H:i",filemtime($value))."
$value$filesize".gmdate("d M Y H:i",filemtime($value))."
";


?>
Copyright Ayon Baidya

Monday, August 20, 2007

User Authentication Advanced

NOTES:
________________________________________________

PASSWORDS IN COOKIES ARE SAVED MD5 ENCRYPTED.
PASSWORDS IN DATABASES SHOULD BE MD5 ENCRYPTED.
________________________________________________

USE ON PAGES FOR LOGGED IN MEMBERS:

$class = new userAut();
$loggedin = $class->loggedin();

If the user isn't logged on or there aren't any
cookies or the session terminated, the user
will be redirected to the login page.
________________________________________________

USE ON LOGIN PAGE:

$class = new userAut();
$login = $class->login();

If the user is already logged on or if there
are cookies or there is a valid session, he
will be redirected to the member page. If the
log in form isn't complete or the username or
the password is wrong, the function will
return the error variable.
________________________________________________

USE ON LOGOUT PAGE:

$class = new userAut();
$logout = $class->logout();

The user will be logged out.

______________________________________________________

class userAut {

// declare $_SESSION variables:
// The value is the name of the $_SESSION variable.
// example: $_SESSION[$this->session_username] is equal to $_SESSION["username"].
// You can change these variables to your desired value.
var $session_username = "username";
var $session_email = "email";
var $session_ip = "ip";

// declare $_COOKIE variables:
// The value is the name of the $_COOKIE variable.
// example: $_COOKIE[$this->cookie_username] is equal to $_COOKIE["username"].
// You can change these variables to your desired value.
var $cookie_username = "username";
var $cookie_password = "password";

// declare $_POST variables:
// The value is the name of the $_POST variable.
// example: $_POST[$this->post_username] is equal to $_COOKIE["username"].
// You can change these variables to your desired value.
var $post_username = "username";
var $post_password = "password";
var $post_cookie = "remember"; // not necesary

// declare database variables:
// Change these values.
var $DB_host = "host";
var $DB_user = "username";
var $DB_pass = "password";
var $DB_db = "database";
var $DB_table_name = "users"; // enter the name of the table where the user data is saved
var $DB_field_username = "username"; // enter the name of the field where the usernames are stored
var $DB_field_password = "password"; // enter the name of the field where the passwords are stored
var $DB_field_email = "email"; // enter the name of the field where the emails are stored

// declare other variables:
// Change these values.
var $member_area = "memberarea"; // page only for logged in members
var $login_page = "login"; // page with the login form
var $error_form = "Please complete the form"; // the error message when form is incomplete
var $error_user = "Username or password wrong"; // the error message when user doesn't exist or when the password is wrong

// ||
// ||
// _ || _ !!!DON'T CHANGE ANYTHING FROM THIS POINT ON!!!
// \ || //
// \||//
// /
// /

var $username;
var $password;
var $email;

/**
* @return bool
* @desc Verify if user has got a session and if the user's IP corresonds to the IP in the session.
*/
function verifySession() {
if (!isset($_SESSION[$this->session_username]) || !isset($_SESSION[$this->session_email]) || !isset($_SESSION[$this->session_ip]) || $_SESSION[$this->session_ip] != $_SERVER['REMOTE_ADDR']) {
return false;
} else {
return true;
}
}

/**
* @return bool
* @desc Verify if cookies exist.
*/
function verifyCookie() {
if (isset($_COOKIE[$this->cookie_username]) && isset($_COOKIE[$this->cookie_password])) {
$this->username = $_COOKIE[$this->cookie_username];
$this->password = $_COOKIE[$this->cookie_password];
return true;
} else {
return false;
}
}

/**
* @return void
* @param string $page
* @desc Redirect the browser to the value in $page.
*/
function redirect($page) {
header("Location: ".$page);
exit();
}

/**
* @return bool
* @desc Verify username and password with MySQL database.
*/
function verifyDB() {
mysql_connect($this->DB_host,$this->DB_user,$this->DB_pass);
mysql_select_db($this->DB_db);
$sql = "SELECT * FROM `".$this->DB_table_name."` WHERE `".$this->DB_field_username."` = '".$this->username."' AND `".$this->DB_field_password." = '".$this->password."';";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$num = mysql_num_rows($query);
if($num == 1) {
$this->email = $row[$this->DB_field_email];
return true;
} else {
return false;
}
}

/**
* @return void
* @desc Write username, email and IP into the session.
*/
function writeSession() {
$_SESSION[$this->session_username] = $this->username;
$_SESSION[$this->session_email] = $this->email;
$_SESSION[$this->session_ip] = $_SERVER['REMOTE_ADDR'];
}

/**
* @return void
* @desc Write cookie with username and md5 encrypted password.
*/
function writeCookie() {
setcookie($this->cookie_username,$this->username);
setcookie($this->cookie_password,$this->password);
}

/**
* @return bool
* @desc Verify if login form fields were filled out.
*/
function verifyForm() {
if (isset($_POST[$this->post_username]) && isset($_POST[$this->post_password]) && $_POST[$this->post_username] != "" && $_POST[$this->post_password] != "") {
$this->username = $_POST[$this->post_username];
$this->password = md5($_POST[$this->post_password]);
return true;
} else {
return false;
}
}

/**
* @return string
* @desc If the user is already logged in or if there
* are cookies or there is a valid session, he
* will be redirected to the member page. If the
* log in form isn't complete or the username or
* the password is wrong, the function will
* return the error variable.
*/
function login() {

// verify if user is already logged in
$v_session = $this->verifySession();
if ($v_session) {
$this->redirect($this->member_area);
}

// verify if cookies are set and if cookies' data corespond to database's data
$v_cookie = $this->verifyCookie();
if ($v_cookie) {
$v_db = $this->verifyDB();
if ($v_db) {
$this->writeSession();
$this->redirect($this->member_area);
}
}

// verify if login form is complete
$v_form = $this->verifyForm();
if (!$v_form) {
if (isset($_POST[$this->post_username]) && isset($_POST[$this->post_password])) {
return $this->error_form;
}
}

// verify if form's data coresponds to database's data
if ($v_form) {
$v_db = $this->verifyDB();
if (!$v_db) {
return $this->error_user;
} else {
$this->writeSession();
if ($_POST[$this->post_cookie]) {
$this->writeCookie();
}
$this->redirect($this->member_area);
}

}

}

/**
* @return void
* @desc The user will be logged out.
*/
function logout() {
$_SESSION = array();
session_destroy();
header("Location: ".$this->login_page);
}

/**
* @return void
* @desc If the user isn't logged on or there aren't
* any cookies or the session terminated, the
* user will be redirected to the login page.
*/
function loggedin() {

// verify if user is already logged in
$v_session = $this->verifySession();
if (!$v_session) {
// verify if cookies are set and if cookies' data corespond to database's data
$v_cookie = $this->verifyCookie();
if ($v_cookie) {
$v_db = $this->verifyDB();
if ($v_db) {
$this->writeSession();
}
} else {
$this->redirect($this->login_page);
}
}

}
}
Copyright Ayon Baidya

User Authentication Simple

Authenticaltion

Here i will show an easy way to authenticate a user.


login.php

session_start();
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
// check if the username and password combination is correct
if ($_POST['txtUserId'] === 'theadmin' && $_POST['txtPassword'] === 'chumbawamba') {
// the username and password match,
// set the session
$_SESSION['basic_is_logged_in'] = true;

// after login we move to the main page
header('Location: main.php');
exit;
} else {
$errorMessage = 'Sorry, wrong username / password';
}
}
/*
But before we start matching the user id and password. We must start the session first. Never forget to start the session before doing anything to the session since it won't work.

You can see above that the hardcoded user id and password are "theadmin" and "chumbawamba". If the submitted user id and password match these two then we set the value of $_SESSION['basic_is_logged_in'] to true. After that we move the application's main page. In this case it's called main.php

If the user id and password don't match we set the error message. This message will be shown on top of the login form.

Note : When starting the session you may stumble upon this kind of error :

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\Webroot\examples\user-authentication\basic\login.php:1) in C:\Webroot\examples\user-authentication\basic\login.php on line 3

PHP will spit this error message if the script that call session_start() already send something ( a blank space, newline, etc ). The error above happen when i add a single space on the first line right before the php opening tag (

*/
?>


Basic Login



if ($errorMessage != '') {
?>

echo $errorMessage; ?>


}
?>
id="frmLogin">
cellpadding="2" cellspacing="2">












User Idid="txtUserId">
Passwordid="txtPassword">




main.php


// like i said, we must never forget to start the session
session_start();

// is the one accessing this page logged in or not?
if (!isset($_SESSION['basic_is_logged_in'])
|| $_SESSION['basic_is_logged_in'] !== true) {

// not logged in, move to login page
header('Location: login.php');
exit;
}
?>

/// Your conte here



logout.php

// i will keep yelling this
// DON'T FORGET TO START THE SESSION !!!
session_start();

// if the user is logged in, unset the session
if (isset($_SESSION['basic_is_logged_in'])) {
unset($_SESSION['basic_is_logged_in']);
}

// now that the user is logged out,
// go to login page
header('Location: login.php');
?>



Hope you have understood the basic of php authentication now on my next tutorial i will show you how to authenticate using MYSQL and Session which is the best way .

Copyright Ayon Baidya

Top 10 Refferer

Here i will show how to log your refferers

create reff_connec.php write

//Connect to your rating database
$mysql_dbhost = 'localhost'; //your sql host
$mysql_dbuser = 'root'; //your sql username
$mysql_dbpass = 'pass'; //sql pass
$mysql_dbname = 'cdcol'; //database name

$rating_conn = mysql_connect($mysql_dbhost, $mysql_dbuser, $mysql_dbpass) or die ('Error connecting to mysql');
mysql_select_db($mysql_dbname);

close reff_connec.php

Now create refferer.php write the following

include('reff_connec.php');
// Find out or base pure referer.
$ref = $_SERVER['HTTP_REFERER'];
// Split our URL into bits.
$url = explode("/",$ref);
// Take the 3rd part of the url (the main site)
$surl = $url[2];
//Is found
// Check to see if it contains the www. at the begining
$found = ereg('\www.',$surl);
if ($found) {
$url = $surl;
} else {
$url = 'www.'.$surl;
}
$query = "SELECT website, hits FROM referers WHERE website = '$url'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if ($num == 1) {
$site = mysql_fetch_array($result, MYSQL_ASSOC);
$mysite=eregi('google',$site['website']); //chage googlet with your site name
if ($site['website'] != 'www.') {
if (!$mysite) {
$hits = $site['hits'] + 1;
$website = $site['website'];
$query = "UPDATE referers SET hits = $hits WHERE website = '$website'";
$result = mysql_query($query);
}
}

} else {

if (!empty($surl)&&!$mysite) {
$query = "INSERT INTO referers (website, hits) VALUES ('$url', '1')";
$result = mysql_query($query);
}

}
$query = "SELECT * FROM referers ORDER BY hits DESC LIMIT 10"; // Change the limit to the top XX that you want to show.
$result = mysql_query($query);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

echo ''.$row['website'].' - '.$row['hits'].''; //replace all -- as its only given as to disable html in post.
}
Copyright Ayon Baidya

.htaccess Getting started

What is .htaccess ?
Text file called .htaccess can be used to control web server (Apache) behavior for your web site. The other sections of this .htaccess tutorial deal with actual commands (called directives) which can be used.

Some exmaple of .htaccess usages

1. Enable/Disable Directory Listing

To have the web server produce a list of files for such directories, use the below line in your .htaccess.

Options +Indexes

To have an error (403) returned instead, use this line.

Options -Indexes

2. Listing Style

Either a basic list of files can be shown, or a 'fancy' list including icons, file size, modification date and more.

IndexOptions +FancyIndexing

Add this to your .htaccess file to use the 'fancy' style.

IndexOptions -FancyIndexing

Use the above line if you prefer a more basic file list.

3. Ignore Files

Let's say you have a directory with .jpg, .gif and .png image files. You only want the .png files to show in the directory listings. Add this line to your .htaccess.

IndexIgnore *.gif *.jpg

The web server now ignores the .gif and .jpg files.

4. Modify Index File

Maybe you don't want a list of the files, you want a specific file to be shown instead. You could upload an index.html file in this directory. There is another way.

DirectoryIndex myfile.html

Instead of listing the files, web page myfile.html will now be shown for this directory and its subdirectories.

5. Custom Error Messages

The ErrorDocument is used for this purpose, followed by a 3 digit errorcode and the action to perform.

ErrorDocument 404 /notfound.html

This example will display web page notfound.html in cases where the requested document is not found.

If you remove a web page from your site and someone tries to view it, they would see notfound.html instead.

ErrorDocument 404 http://www.other_site.com/notfound.html

This redirects such requests to the URL you specify.

You can also tell .htaccess to display a text message.

ErrorDocument 404 "No such document here

Here, the text 'No such document here' is shown.

Replace the action parts shown in red in the above examples to customize the web server behavior.

6. Other Error Numbers

Other comonly used 3 digit codes are listed below.

401 : Authorization Required

Someones tried to access a password protected area but did not provide correct user/pass info.

403 : Forbidden

This person is blocked from requesting the document.

500 : Internal Server Error

Usually, this means the cgi script being used crashed.


7. Create the .htaccess file

Let's say you remove file old.html and want to send people looking for it to web page new.html.

Redirect /old.html http://your_domain.html/new.html

All it takes is one simple line, quick and easy.

An additional option is available. This is said to be the best way from a search engine point of view.

Redirect permanent /old.html http://your_domain.html/new.html

The only difference is the error code generated while redirecting the request. It indicates the requested document has moved for good and will not be back.

8. Other uses

This .htaccess feature can be used for any file type.

Redirect /old.pdf http://your_domain.html/new.pdf

This will redirect requests for old.pdf to file new.pdf.

9. Hotlink Protection

Add the below lines to your .htaccess file to stop people from hotlinking to your .gif and .jpg files.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_domain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]

Replace your_domain.com with your domain name.

This starts by turning on the rewrite engine. Next, it checks the referer (where the request comes from).

If it did not come from your domain name and it is a request for a .gif or .jpg file, it will output an error message. Otherwise it will display the image as usual.

The rewrite engine is very powerful and can be used for many other purposes. This tutorial is for beginners.

10. Other Uses

This .htaccess trick can be used to protect other file types, such as .mp3, .ogg, .mpg and other files.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your_domain.com/.*$ [NC]
RewriteRule \.(mp3|ogg|mpg)$ - [F]

The only changes in this .htaccess file are on the last line. Enter the file extensions in the brackets, do not include the dot (.). Separated them with a pipe (|).


.htaccess Tutorial - Block An IP Address

There may be times where you want to refuse access to certain robots or human visitors to your web site.

11. Basic .htaccess file

order allow,deny
deny from 127.0.0.1
allow from all

This will refuse all GET and POST requests made by IP address 127.0.0.1, an error message is shown instead.

12. More options

To block multiple IP addresses, list them one per line.

order allow,deny
deny from 127.0.0.1
deny from 127.0.0.2
deny from 127.0.0.3
allow from all

You can also block an entire IP block/range. Here we will not specify the last octet in the .htaccess file.

deny from 127.0.0

This will refuse access for any user with an address in the 127.0.0.0 to 127.0.0.255 range.

Instead of using numeric addresses, domain names (and subdomain names) can be used to ban users.

deny from isp_name.com

It bans users with a remote hostname ending in isp_name.com. This would stop all users connected to the internet via isp_name.com from viewing your site.

Using .htaccess to block an entire range or name is likely to lock out innocent users. Use with caution.

I will add some more uses...later..



Copyright Ayon Baidya

Read Directory Content

Here I will show you how to read a directory Content using php readdir function. Simple
 // Define the full path to your folder from root
$path = "/home/user/public/foldername/";

// Open the folder
$dir_handle = @opendir($path) or die("Unable to open $path");

// Loop through the files
while ($file = readdir($dir_handle)) {

if($file == "." || $file == ".." || $file == "index.php" )

continue;
echo "
$file
";

}

// Close
closedir($dir_handle);

Advnaced

Copyright Ayon Baidya

Database handeling

Here i will show you how to handle php with mysql.

to be cont...

Mysql Database 1.

Here i will show you how to handle php with mysql.

Before we start mysql you must read the following topic Database Normalization so that you can handle data properly.

Connection to mysql

// To connect to mysql the mysql_connect() function is called.The mysql_connect function takes three arguments. Server, username, and password.
Example:
* Server - localhost
* Username - admin
* Password - admin123
so the code to connect will be
mysql_connect("localhost", "admin", "admin123") or die(mysql_error());
?>


The "or die(mysql..." code displays an error message in your browser if there is an error!
After establishing a MySQL connection with the code above, you then need to choose which database you will be using with this connection.
For this you need to call the mysql_select_db function.

mysql_connect("localhost", "admin", "admin123") or die(mysql_error());
mysql_select_db("test")or die(mysql_error());
?>

The above code will first connect the local mysql server then select the database test.
Now you are ready for mysql queries from the database test with php.

To be cont...
Copyright Ayon Baidya

Cookies

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.


Facts

  1. You have to put the cookie code as the first line of your file, it has to be before the head, before any other code, HTML or PHP.
  2. The cookie will not work on the page until its refreshed, or the user visits the page again.
  3. The cookie only works on the directory you're in and down. Its best to place the cookie in a file which is located in the root directory, so you can use the cookie anywhere around the site.
Code:
setcookie(name, value, expire, path, domain);


Exmaples

setcookie ("cookie", "spoono rocks");
//makes a variable $cookie with a value of "spoono rocks"


setcookie ("cookie", "spoono rocks", time()+3600);
//same thing as above, but will last for 3600 seconds, or one hour from the current time.
Retrieve a cookie value.
The PHP $_COOKIE variable is used to retrieve a cookie value.

setcookie ("cookie1", "spoono rocks once", time()+3600);
setcookie ("cookie2", "spoono rocks 2 times", time()+3600);
setcookie ("cookie3", "spoono rocks 3 times", time()+3600);

//Then in the main body, you can place:

echo $_COOKIE["cookie1"]; //will display "spoono rocks once"
echo $_COOKIE["cookie2"]; // "spoono rocks 2 times"
echo $_COOKIE["cookie3"]; // "spoono rocks 3 times"

//if you want to display all cookies for debugging
//you can use:
print_r($_COOKIE);
Another Example

if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!
";
else
{
echo "Welcome guest!
";
setcookie("user", "Blogger", time()+3600);
}

///On first visit it will display guest and there after blogger.

Delete cookies

Just place a new setcookie() statement with the variable you want to deconstruct

setcookie ("cookie");
//deletes the spoono cookie

Copyright Ayon Baidya

Counter

Counter

Learn how to make a text counter in PHP.

A counter is an essential part of a site to know how many people are coming to site. Here is an easy way to make a counter. All you need is access to PHP and be able to chmod a directory. We're going to save the amount of hits in a .dat file, so you don't even need a mySQL database. First off, you have create a directory and CHMOD it 777 so PHP can write the counter.dat file.

Here is what we have to write in English:
  1. Use the file_exists() function in PHP and see if the counter.dat file exists. If it does, then open the file using the PHP fopen() function.
  2. Use the PHP fgets() function to find the number of hits there and save it in a variable.
  3. Add one to the variable.
  4. Close the file.
  5. Display the number of hits.
  6. Open the counter.dat file using the fopen() function and save it as a variable.
  7. Use the PHP fputs() function to insert the new number of hits.
  8. Close the file.
  9. If the counter.dat file doesn't exist, then use the fopen() function and declare it as a variable.
  10. Use the Fputs() function and put a "1" in there.
  11. Print out that 1 person has come to the page and then close the file.
Here is some useful information about these functions, which may be helpful for you that I got from the PHP Manual:

  1. int fopen (string filename, string mode, int use_include_path])
    Filename: the name of the file
    Mode:
      'r' - Open for reading only; place the file pointer at the beginning of the file.
      'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
      'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
      'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
      'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
      'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    use_include_path:
      Set it to "1", if you want to search for the file in the include_path.

  2. string fgets (int fp, int length) - Gets line from file pointer
      Returns a string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).

  3. int fputs (int fp, string str [, int length])
      fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
Here it is in PHP:

if(file_exists("counter.dat"))
{
$exist_file = fopen("counter.dat", "r");
$new_count = fgets($exist_file, 255);
$new_count++;
fclose($exist_file);
print("$new_count people have visited this page");
$exist_count = fopen("counter.dat", "w");
fputs($exist_count, $new_count);
fclose($exist_count);
}
else
{
$new_file = fopen("counter.dat", "w");
fputs($new_file, "1");
print("1 person have visited this page");
fclose($new_file);
}

Copyright Ayon Baidya

Php Mail

Here I will show you the complete tutorial to send mails using php

To send email using PHP, you use the mail() function. This accepts 5 parameters as follows (the last 2 are optional)

mail(to,subject,message,headers,parameters)
Parameter Description
to Required. The recipient's email address.
subject Required. The email's subject line.
message Required. The actual email body.
headers Optional. Additional header fields such as "From", "Cc", "Bcc" etc.
parameters Optional. Any additional parameters.

Examples

Simple Mail

 "Thank you for registering!",
"Hello ayon, thank you for the tutorial!",
"From: viewer@somebloggersite.com");
?>

----Or--------

// Set up parameters
$to = "exampleayon@qmail.com";//or $_GET/$_POST['postorgetvalue']; To get value from forms.
$subject = "Thanks";
$message = "Hello ayon, thank you for the tutorial!";
$from = "viewer@somebloggersite.com";//or $_GET/$_POST['postorgetvalue']; To get value from forms.
$headers = "From: $from";

// Send email
mail($to,$subject,$message,$headers);

// Inform the user
echo "Thanks for registering! We have just sent you an email with your password.";
?>

Advance Html Mails
//add From: header
$headers = "From: webserver@localhost\r\n";

//specify MIME version 1.0
$headers .= "MIME-Version: 1.0\r\n";

//unique boundary
$boundary =
uniqid("HTMLDEMO");

//tell e-mail client this e-mail contains//alternate versions
$headers .= "Content-Type: multipart/alternative" .
"; boundary = $boundary\r\n\r\n";

//message to people with clients who don't
//understand MIME
$headers .= "This is a MIME encoded message.\r\n\r\n";

//plain text version of message
$headers .= "--$boundary\r\n" .
"Content-Type: text/plain; charset=ISO-8859-1\r\n" .
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .=
chunk_split(base64_encode("This is the plain text version!"));

//HTML
version of message
$headers .= "--$boundary\r\n" .
"Content-Type: text/html; charset=ISO-8859-1\r\n" .
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .=
chunk_split(base64_encode("This the HTML version!"));

//send
message
mail("root@localhost", "An HTML Message", "", $headers);
?>


OR----------------

You may download the greate php class http://phpmailer.sourceforge.net/ from which you can send mails with all the features like attachments, html, simple, multiple adresses more.
Copyright Ayon Baidya