Система за регистрация с аватари
Автор: SandPrince
Сега ще си направим една много добра система за регистрация с админ панел за качване на аватари.
Ще започнем със създаването на две папки – images и avatars като на втората папка трябва да променим пермишъна на 777
Сега започваме изграждането на самата система
Заповаме с една таблица в БД
CREATE TABLE `php4all_members_system` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user` VARCHAR( 50 ) NOT NULL ,
`pass` VARCHAR( 75 ) NOT NULL ,
`email` VARCHAR( 90 ) NOT NULL
) ENGINE = MYISAM ;Сега ни трябва и един файл който да прави връзка с БД-то – файла ще се казва config.php
<?php
$dbuser = '';// Sql потребител на бд
$dbpass = '';// Sql парола
$db = '';// Sql име на базаданни
$dbhost = '';// Sql хост
mysql_connect($dbhost, $dbuser, $dbpass);//Connection...
mysql_select_db($db);//Selects the db
?>Тук си знаете какво трябва да попълните. продължаваме на татък с файла index.php
<?php ob_start(); //Output Buffering Allowed ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<style type="text/css">
body, table, form {
font-family: Tahoma;
font-size: 11px;
color: #333333;
background-color: #F9F9F9;
}
div.body {
color:#333333;
background-color: #F8F8F8;
border: 1px solid #CCCCCC;
text-align: center;
padding: 2px;
}
div.sitetitle {
font-weight: bold;
background-color: #CCCCCC;
padding: 2px;
}
div.banner {
margin: 3px;
padding: 3px;
border: 1px solid silver;
}
div.menu {
letter-spacing: 1px;
background-color: #CCCCCC;
padding: 2px;
}
div.content {
color: #000000;
background-color: #F9F9F9;
text-align: left;
padding: 2px;
}
div.leftcontent {
background-color: #CCCCCC;
border-right-width: 1px;
border-right-style: dotted;
border-right-color: silver;
float: left;
border-bottom-width: 1px;
border-bottom-style: dotted;
border-bottom-color: silver;
padding: 2px;
margin-right: 3px;
}
div.footer {
font-size: 10px;
color: #CCCCCC;
background-color: #333333;
padding: 2px;
}
a {
color: #0066CC;
font-weight: bold;
font-size: 10px;
text-decoration: none;
}
a:hover {
font-size: 10px;
font-weight: bold;
color: #0066CC;
text-decoration: underline;
}
input, textarea, select, radio {
font-family:Tahoma;
font-size:12px;
border: 1px solid #DDDDDD;
background-color: #F2F2F2;
}
</style>
<title>Your Site Title</title>
</head>
<body>
<div class="body">
<div class="sitetitle">PHP 4 ALL MEMBERS SYSTEM</div>
<div class="banner"><img src="images/Banner.gif" width="500" height="100" /></div>
<div class="menu"><a href="?go=main">Home</a> | <a href="?go=members&get=register">Register</a> | <a href="?go=members&get=login">Login</a> | <a href="?go=members&get=logout">Logout</a> | <a href="?go=members">View Members</a> | <a href="?go=members&get=cp">User CP</a></div>
<div class="content">
<?php
ob_start();// Output Buffering Start, this will allow cookies and stuff
include("config.php");// Includes the configuration file
include("functions.php");
clean();
// PHP Navigation -----------------------
$go = $_GET['go'];// Gets the ?go
$fd = $_GET['fd'];// Gets the ?fd
if(empty($go))// If go is empty
{
$go = 'main.php';// Includes the default page
}
// Cleaning the gets --------------------
$go = str_replace('http://','',$go);
$go = str_replace('www.','',$go);
$go = str_replace('.php','',$go);
$fd = str_replace('http://','',$fd);
$fd = str_replace('www.','',$fd);
$fd = str_replace('.php','',$fd);
// End of Cleaning the gets ---------------
if(isset($fd) && isset($go) && file_exists($fd."/".$go.".php")){
include ($fd."/".$go.".php");
}else if(isset($go) && file_exists($go.".php")){
include ($go.".php");
}else{
echo "Sorry, that page does not exist.";
}
// End of PHP Navigation -----------------
ob_end_flush();// Output Buffering End Flush
?>
</a><br />
<br />
</div>
<div class="footer">Copyrighted 2006 yoursite[dot]com - Powered by <a href="http://php4all.org" target="_blank">PHP4ALL</a> User System </div>
</div>
</body>
</html>Сега си правим и един документ – main.php
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
<p>Welcome to PHP 4 ALL User System v1.0!
This is an user system ready to ingrate to your site.
</p>
<p><strong>Instructions:</strong></p>
<p>To install this system, open the configuration file, and edit it with your sql information.<br />
Then, run install.php.<br />
Or you can also run SQL.txt in PhpMyAdmin.<br />
Finally chmod the folder avatars to 777.<br />
If you want you can change the layout, just keep the php code and then paste it in the content section of your new layout.</p>
<p> </p>
<p><strong>LICENSE</strong></p>
<p>This program is free software; you can redistribute it and/or<br />
modify it under the terms of the GNU General Public License (GPL)<br />
as published by the Free Software Foundation; either version 2<br />
of the License, or (at your option) any later version.</p>
<p>This program is distributed in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br />
GNU General Public License for more details.</p>
<p>To read the license please visit<br />
http://www.gnu.org/copyleft/gpl.htm</p>
<p> </p>Сега следва да си направим един от най-важните файлове – instal.php
<?php
include("config.php");
$ok = mysql_query("CREATE TABLE `php4all_members_system` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user` VARCHAR( 50 ) NOT NULL ,
`pass` VARCHAR( 75 ) NOT NULL ,
`email` VARCHAR( 90 ) NOT NULL
) ENGINE = MYISAM ;");
if($ok){
echo "PHP 4 ALL MEMBERS SYSTEM v1.0 HAS BEEN INSTALLED SUCCESFULLY. DELETE THE INSTALL.PHP FILE.";
}else{
echo "THERE WAS AN ERROR DURING INSTALATION, MAKE SURE TO EDIT THE CONFIGURATION FILE WITH YOUR SQL INFORMATION, OR YOU CAN ALSO RUN THE SQL FILE IN PHPMYADMIN.";
}
?>С този файл директно можете да си инсталирате системата без да влизате в phpMyAdmin-a да пишете кода на таблицата по горе. само трябва да си попълните информацията в config.php и после стратирате този файл.
Продължаваме нататък с още един файл – functions.php
<?php
// This function will clean the $_POSTS and $_GETS, i got from Zulumonkey[dot]org
// Clean Function ---------------
function clean()
{
foreach($_POST as $key => $val)
{
$_POST[$key] = stripslashes(strip_tags(htmlspecialchars($val, ENT_QUOTES)));
$$key = stripslashes(strip_tags(htmlspecialchars($val, ENT_QUOTES)));
}
foreach($_GET as $key => $val)
{
$_GET[$key] = stripslashes(strip_tags(htmlspecialchars($val, ENT_QUOTES)));
$$key = stripslashes(strip_tags(htmlspecialchars($val, ENT_QUOTES)));
}
}
// End of Clean Function ---------
?>И сега последния файл от цялата система – members.php
<?php
ob_start();
$table = 'php4all_members_system';//Sets the table name
switch($_GET['get'])
{
// Default page --------------
default:
//Pagination
$limit = 25;// Set the limit of results per page
$page = $_GET['page'];// Sets the page, the default is ?page=
$totalrows = mysql_num_rows(mysql_query("SELECT id FROM $table"));// Counts the total rows
if(empty($page))// If the page is empty
{
$page = '1';// Page is 1
};
$start = ($page-1)*$limit;
$start = round($start,0);// Sets the start
echo 'Registered Users:<br />';
$result = mysql_query("SELECT * FROM $table LIMIT $start, $limit");// Normal query
while ($r = mysql_fetch_array($result))
{
echo "$r[user]<br />";// Echoes the content
};
$totalusers = mysql_num_rows(mysql_query("SELECT id FROM $table"));
echo "<br />Total Users: $totalusers<br />";// Echoes the total users
$totalpages = $totalrows / $limit;// Get the total pages
$totalpages = ceil($totalpages);// Rounds the total pages to the highest possible numer
if($page == 1)// If the page is 1
{
$actualpage = '[1]';// Sets the actual page
}
else// Else
{
$actualpage = "[$page]";// The page is the one it's specified in ?page=
}
if($page < $totalpages)// If the actual page is smaller than the totalpages
{
$nv = $page+1;// Sets the next variable
$pv = $page-1;// Sets the preview variable
$nextpage = "<a href=?page=$nv>></a>";// Sets the next page
$prevpage = "<a href=?page=$pv><</a>";// Sets the prev page
$firstpage = "<a href=\"?page=1\">«</a>";// Sets the first page
$finalpage = "<a href=\"?page=$totalpages\">»</a>";// Sets the final page
}
if($page == '1')
{
$nv = $page+1;
$nextpage = "<a href=?page=$nv>></a>";
$prevpage = "<";
$firstpage = "«";
$finalpage = "<a href=\"?page=$totalpages\">»</a>";
}elseif($page == $totalpages){
$pv = $page-1;
$nextpage = ">";
$prevpage = "<a href=?page=$pv><</a>";
$firstpage = "<a href=\"?page=1\">«</a>";
$finalpage = "»";
}
if($totalpages == '1' || $totalpages == '0'){
$nextpage = ">";
$prevpage = "<";
$firstpage = "«";
$finalpage = "»";
}
echo "$firstpage $prevpage Actual Page: $actualpage $nextpage $finalpage<br />Pages: $totalpages";
// End of Pagination ---------
// End of Default Page -------
break;
// Register Page -------------
case 'register':
if(!(isset($_COOKIE['php4all_user'])))// If the cookie is not set it will show the form
{
if($_POST['Submit'])// If the form is submitted
{
$user = $_POST['user'];// Gets the user
$pass = $_POST['pass'];// Gets the pass
$pass = md5($pass);// Encrypt the pass using md5
$email = $_POST['email'];// Gets the email
if(!ereg("[a-z||0-9]", $user))// Check if the username is alphanumeric
{
die('Only alphanumerical nicks are allowed.');// If it isn't alphanumeric it will kill the script
}
if(!ereg("[a-z||0-9]@[a-z||0-9].[a-z]", $email))// Checks if it's a real email
{
die('Please, insert a valid email.');//If it isn't a valid email, it kill the script
}
$ckeck = mysql_fetch_array(mysql_query("SELECT id FROM $table WHERE user='$user'"));//Checks if there is another user with the same nick
if($ckeck)//If there is one
{
die('That username is already in use, please, choose another one.');// Kills the script
}
$ok = mysql_query("INSERT INTO $table (`id`, `user`, `pass`, `email`) VALUES ('NULL', '$user', '$pass', '$email')");// If everything is ok it will insert the info to the DB
if($ok)// If there were no errors
{
echo "Congratulations $user, you have registered succesfully";// Echoes this message
}
else// Else
{
echo 'Oops, Error.';// Echoes this one
}
}
else
{//Else, if it's not submitted, it will show the form
echo "<form action=\"?go=members&get=register\" method=\"post\">
<table border=\"0\">
<tr>
<td>Username</td>
<td><input name=\"user\" type=\"text\" id=\"user\" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name=\"pass\" type=\"text\" id=\"pass\" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name=\"email\" type=\"text\" id=\"email\" /></td>
</tr>
<tr>
<td> </td>
<td><input type=\"submit\" name=\"Submit\" value=\"Register\" /></td>
</tr>
</table>
</form>";
}
}
else
{
echo 'You are already regsitered and logged!.';// If there is a cookie it will display this message
}
// End of Register Page ------
break;
// Login Page ----------------
case 'login':
if(!isset($_COOKIE['php4all_user']))// Checks if the user is logged
{
if($_POST['Submit'])
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$pass = md5($pass);
$ok = mysql_fetch_array(mysql_query("SELECT id FROM $table WHERE user='$user' and pass='$pass'"));//Checks in the DB for the User and Pass
if($ok)//If it found it
{
setcookie('php4all_user',$user,time()+3600*24*30);// Cookie for 1 month
echo "Welcome $user, Enjoy your stay.";
}
else
{
echo 'Wrong username and password convination, please, try again.';
}
}
else
{
echo "<form action=\"?go=members&get=login\" method=\"post\">
<table border=\"0\">
<tr>
<td>Username</td>
<td><input name=\"user\" type=\"text\" id=\"user\" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name=\"pass\" type=\"password\" id=\"pass\" /></td>
</tr>
<tr>
<td> </td>
<td><input type=\"submit\" name=\"Submit\" value=\"Login\" /></td>
</tr>
</table>
</form>";
}
}
else
{
echo 'You are already logged in!';
}
// End of Login Page ---------
break;
// Logout --------------------
case 'logout':
if(isset($_COOKIE['php4all_user']))//Checks if the user is logged
{
setcookie('php4all_user',$user,time()-3600*24*30);
echo 'You are now logged out.';
}
else
{
echo 'You are not logged! You can not log out.';
}
// End of Logout -------------
break;
// User CP -------------------
case 'cp':
if(isset($_COOKIE['php4all_user']))//Checks if the user is logged
{
$user = $_COOKIE['php4all_user'];
$r = mysql_fetch_array(mysql_query("SELECT * FROM $table where user='$user'"));//Select the user stuff
if(!(file_exists("avatars/$r[user].gif")))//Checks if there is an avatar
{
$avatar = 'You do not have an avatar';
}
else
{
$avatar = "<br /><img src=\"avatars/$r[user].gif\" />";
}// Echoes the user info
echo "Your info:<br />
Username: $r[user]<br />
Password: Encrypted<br />
Email: $r[email]<br />
Avatar: $avatar<br />
<a href=\"?go=members&get=avatar\">Change Avatar?</a><br />
<a href=\"?go=members&get=edit\">Edit Profile?</a>";
}
else
{
echo 'Sorry, you must be registered and logged in to see the Control Panel.';
}
// End of User CP ------------
break;
// Avatar ---------------------
case 'avatar':
if(isset($_COOKIE['php4all_user'])){
// Avatar script modified, i got this one from http://zulumonkey.org/?id=tutorials&page=comment&oid=115
$username = $_COOKIE['php4all_user'];
$maxwidth = "80";
$maxheight = "80";
if (isset($_GET['delete']))
{
$filename = 'avatars/'.$username.'.gif';
if (file_exists($filename))
{
unlink($filename);
echo "Your avatar has been deleted<br /><a href=?go=members&get=avatar>Go back</a>";
die();
}
}
if (isset($_POST['Submit']))
{
$filetype = $_FILES['avatar']['type'];
$filetypex = substr($filetype,0,5);
if ($filetypex == image)
{
$newid = "avatars/";
$newid .= "$username";
$newid .= ".gif";
$mysock = getimagesize($_FILES['avatar']['tmp_name']);
$imagewidth = $mysock[0];
$imageheight = $mysock[1];
if ($imagewidth <= "$maxwidth" && $imageheight <= "$maxheight")
{
if(!(copy($_FILES['avatar']['tmp_name'], $newid))) die("Cannot upload files.");
echo "Your New Avatar Has Been Created";
}
else
{
echo "This avatar is to big, please change it";
}
}
else
{
echo "This File Is Not a Image Fool";
}
}
else
{
echo "<form action=\"?go=members&get=avatar\" method=\"post\" enctype=\"multipart/form-data\">
<table border=\"0\">
<tr>
<td>Avatar</td>
<td><input name=\"avatar\" type=\"file\" id=\"user\" /></td>
</tr>
<tr>
<td> </td>
<td><input type=\"submit\" value=\"Upload\" name=\"Submit\"></td>
</tr>
<tr>
<td> </td>
<td>Max Size 80x80<br />
All files will be converted to gif </td>
</tr>
</table>
</form>";
}
}
else
{
echo 'You need to be registered and logged to see this page.';
}
// End of Avatar --------------
break;
// Edit -----------------------
case 'edit':
if($_POST['Submit'])
{
$user = $_POST['user'];
$email = $_POST['email'];
$id = $_POST['id'];
$pass = $_POST['pass'];
$md5pass = md5($pass);
/*
Here we make 2 different queries because if the password is empty
It will encode it and introduce a new password, so, only introduce the password
If you want to change it!
*/
if(empty($pass))
{
$ok = mysql_query("
UPDATE `$table` SET `id` = '$id',
`user` = '$user',
`email` = '$email' WHERE `id` =$id LIMIT 1 ;");
}
else
{
$ok = mysql_query("
UPDATE `$table` SET `id` = '$id',
`user` = '$user',
`pass` = '$md5pass',
`email` = '$email' WHERE `id` =$id LIMIT 1 ;");
}
if($ok)
{
echo 'Your profile has been updated succesfully.';
}
else
{
echo 'Oops, Error';
}
}
else
{
$user = $_COOKIE['php4all_user'];
$r = mysql_fetch_array(mysql_query("SELECT * FROM $table WHERE user='$user'"));
echo "<form action=\"?go=members&get=edit\" method=\"post\">
<table border=\"0\">
<tr>
<td>Username</td>
<td><input name=\"user\" type=\"text\" id=\"user\" value=\"$r[user]\" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name=\"pass\" type=\"text\" id=\"pass\" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name=\"email\" type=\"text\" id=\"email\" value=\"$r[email]\" /><input type=\"hidden\" value=\"$r[id]\" id=\"id\" name=\"id\" /></td>
</tr>
<tr>
<td> </td>
<td><input type=\"submit\" name=\"Submit\" value=\"Edit\" /></td>
</tr>
</table><br />ONLY ADD THE PASS IF YOU WANT TO CHANGE IT.
</form>";
}
// End of Edit ----------------
break;
}
?>Това е! Урока е преведен специално за Web-Tourist!!!!
ползвайте тези данни:
потребител: SandPrince
парола: qwertyuiop


