Система за потребители с cookies

Здравейте!

От доста време забелязвам че много хора търсят системки да си направят потребители на сайта. Тази е написана с cookies и искам да ви се извиня ако съм сбъркал някъде. Част от функциите са копирани.

Ето ги и файловете:
inc.php<\b>


<?
$mysql_host = "хост";
$mysql_user = "име";
$mysql_pass = "парола";
$mysql_db = "база с данни";
$maxusers = 5000;

function sqlesc($x) {
return "'".mysql_real_escape_string($x)."'";
}

/** Този код е копиран **/
function validip($ip)
{
if (!empty($ip) && $ip == long2ip(ip2long($ip)))
{
$reserved_ips = array (
array('0.0.0.0','2.255.255.255'),
array('10.0.0.0','10.255.255.255'),
array('127.0.0.0','127.255.255.255'),
array('169.254.0.0','169.254.255.255'),
array('172.16.0.0','172.31.255.255'),
array('192.0.2.0','192.0.2.255'),
array('192.168.0.0','192.168.255.255'),
array('255.255.255.0','255.255.255.255')
);

foreach ($reserved_ips as $r)
{
$min = ip2long($r[0]);
$max = ip2long($r[1]);
if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) return false;
}
return true;
}
else return false;
}

function getip() {
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && validip($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && validip($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR') && validip(getenv('HTTP_X_FORWARDED_FOR'))) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP') && validip(getenv('HTTP_CLIENT_IP'))) {
$ip = getenv('HTTP_CLIENT_IP');
} else {
$ip = getenv('REMOTE_ADDR');
}
}

return $ip;
}
/** Стига толкова копиран код **/

function db_connect()
{
global $mysql_host, $mysql_user, $mysql_pass, $mysql_db;

if (!@mysql_connect($mysql_host, $mysql_user, $mysql_pass))
{
switch (mysql_errno())
{
case 1040:
case 2002:
if ($_SERVER[REQUEST_METHOD] == "GET") die("<html><head><meta http-equive=\"Content-tybe\" content=\"text/html; charset=windows-1251\"><meta http-equiv=refresh content=\"5 $_SERVER[REQUEST_URI]\"></head><body><table border=0 width=100% height=100%><tr><td><h3 align=center>Сървърът е натоварен в момента. Моля изчакайте. Страницата ще се рестартира.</h3></td></tr></table></body></html>");
else die("Има прекалено много потребители онлайн.");
default: die("[" . mysql_errno() . "] dbconn: mysql_connect: " . mysql_error());
}
}

mysql_select_db($mysql_db) or die('dbconn: mysql_select_db: ' + mysql_error());

user_login();
}

function get_date_time($timestamp = 0)
{
if ($timestamp)
return date("Y-m-d H:i:s", $timestamp);
else
return gmdate("Y-m-d H:i:s");
}

function user_login() {
unset($GLOBALS["USER"]);
if (empty($_COOKIE["user"]) || empty($_COOKIE["pass"]))
return;
$id = 0 + $_COOKIE["user"];
if (!$id || strlen($_COOKIE["pass"]) != 32)
return;
$res = mysql_query("SELECT * FROM users WHERE id = $id");
$row = mysql_fetch_array($res);
if (!$row)
return;
if ($_COOKIE["pass"] !== $row["passhash"])
return;
mysql_query("UPDATE users SET last_access='" . get_date_time() . "', ip=".sqlesc($ip)." WHERE id=" . $row["id"]);// or die(mysql_error());
$row['ip'] = $ip;
$GLOBALS["USER"] = $row;
}

function logincookie($id, $passhash, $updatedb = 1, $expires = 0x7fffffff)
{
setcookie("user", $id, $expires, "/");
setcookie("pass", $passhash, $expires, "/");

if ($updatedb)
mysql_query("UPDATE users SET last_login = NOW() WHERE id = $id");
}

function logoutcookie() {
setcookie("user", "", 0x7fffffff, "/");
setcookie("pass", "", 0x7fffffff, "/");
}
?>


index.php <\b>

<?
require_once("inc.php");
header("Content-type: text/html;charset=utf-8");
db_connect();
if($USER)
{
echo "Здравей, $USER[username]!<br>Тука си от: $USER[added]";
?>
<br><a href="logout.php">Излез</a>
<?}
else
{

?>
<a href="login.php">Влез</a><br><a href="signup.php">Регистрация</a> <?
}
?>


login.php <\b>

<?
require_once("inc.php");
header("Content-type: text/html;charset=utf-8");
db_connect();


?>
<form action="tlogin.php" method="POST">
<input type="text" size="40" name=username>
<input type="password" size="40" name="password">
<input type="submit" value="Submit">
</form>



tlogin.php

<?

require_once("inc.php");
function unesc($x) {
if (get_magic_quotes_gpc())
return stripslashes($x);
return $x;
}

$username = $_POST["username"];
$password = $_POST["password"];


db_connect();

function erorr($text = "Username or password incorrect")
{
die("$text");
}

$res = mysql_query("SELECT id, passhash FROM users WHERE username = " . sqlesc($username) . "");
$row = mysql_fetch_array($res);

if (!$row)
erorr();

if ($row["passhash"] != md5($password))
erorr();

if ($row["enabled"] == "no")
erorr("This account has been disabled.");

logincookie($row["id"], $row["passhash"]);

header("Location: $BASEURL/index.php");

?>


signup.php<\b>


<?
ob_start("ob_gzhandler");
header("Content-type: text/html;charset=utf-8");
require_once("inc.php");

db_connect();

$res = mysql_query("SELECT COUNT(*) FROM users") or die(mysql_error());
$arr = mysql_fetch_row($res);
if ($arr[0] >= $maxusers) die("Лимитът е достигнат");

?>
<form method="post" action="tsignup.php">
<table border="1" cellspacing=0 cellpadding="10">
<tr><td align="right" class="heading">Потрибител:</td><td align=left><input type="text" size="40" name="wantusername" /></td></tr>
<tr><td align="right" class="heading">Парола:</td><td align=left><input type="password" size="40" name="wantpassword" /></td></tr>
<tr><td align="right" class="heading">Потв. Парола:</td><td align=left><input type="password" size="40" name="passagain" /></td></tr>
<tr valign=top><td align="right" class="heading">Email адрес:</td><td align=left><input type="text" size="40" name="email" /></td></tr>
<tr><td colspan="2" align="center"><input type=submit value="Регистрация" style='height: 25px'></td></tr>
</table>
</form>



tsignup.php<\b>

<?
header("Content-type: text/html;charset=utf-8");
require_once("inc.php");

db_connect();

$res = mysql_query("SELECT COUNT(*) FROM users") or sqlerr(__FILE__, __LINE__);
$arr = mysql_fetch_row($res);
if ($arr[0] >= $maxusers) die("Лимитът е достигнат");

function unesc($x) {
if (get_magic_quotes_gpc())
return stripslashes($x);
return $x;
}

function mkvars($vars) {
if (!is_array($vars))
$vars = explode(":", $vars);
foreach ($vars as $v) {
if (isset($_GET[$v]))
$GLOBALS[$v] = unesc($_GET[$v]);
elseif (isset($_POST[$v]))
$GLOBALS[$v] = unesc($_POST[$v]);
else
return 0;
}
return 1;
}

if (!mkvars("wantusername:wantpassword:passagain:email"))
die();

function error($msg) {
die("$msg");
}

function validusername($username)
{
if ($username == "")
return false;

// тука са позволените символи
$allowedchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

for ($i = 0; $i < strlen($username); ++$i)
if (strpos($allowedchars, $username[$i]) === false)
return false;

return true;
}

if (empty($wantusername) || empty($wantpassword) || empty($email))
error("Опа! Оправи си името паролата и имейла");

if (strlen($wantusername) > 12)
error("Много ти е дълго името");

if ($wantpassword != $passagain)
error("Паролите не съвпадат");

if (strlen($wantpassword) < 6)
error("Паролата е много кратка");

if (strlen($wantpassword) > 40)
error("Паролата е много дълка");

if ($wantpassword == $wantusername)
error("Ей мой, паролата и името ти трябва да са различни");
function validemail($email) {
return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}
if (!validemail($email))
error("Къв е тоя имейл ве!!!!!");

if (!validusername($wantusername))
error("С тва име не става.");


// check if email addy is already in use
$a = (@mysql_fetch_row(@mysql_query("select count(*) from users where email='$email'"))) or die(mysql_error());
if ($a[0] != 0)
bark("Некав вече се е регнал с $email");

$wantpasshash = md5($wantpassword);


$ret = mysql_query("INSERT INTO users (username, passhash, email,added) VALUES (" .
implode(",", array_map("sqlesc", array($wantusername, $wantpasshash, $email))).
", '". get_date_time() ."')");

if (!$ret) {
if (mysql_errno() == 1062)
error("Вече има някой с такова име");
error("Бог да ти е на помощ: ".mysql_error());
}


logincookie($id, $wantpasshash);

header("Refresh: 0; url=/index.php");

?>



logout.php<\b>

<?

require_once("inc.php");

db_connect();

logoutcookie();

Header("Location: /");

?>


SQL<\b>

CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`username` varchar(40) NOT NULL default '',
`passhash` varchar(32) NOT NULL default '',
`email` varchar(80) NOT NULL default '',
`added` datetime NOT NULL default '0000-00-00 00:00:00',
`last_login` datetime NOT NULL default '0000-00-00 00:00:00',
`last_access` datetime NOT NULL default '0000-00-00 00:00:00',
`ip` varchar(15) NOT NULL default '',
`enabled` enum('yes','no') NOT NULL default 'yes',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
KEY `added` (`added`),
KEY `ip` (`ip`),
KEY `last_access` (`last_access`),
KEY `enabled` (`enabled`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



Моля кодът да не бъде постван в други сайтове без съгласието ми.

Демо:
тук.


Download:тук






/ Трябва да сте регистриран за да напишете коментар /