· 9 years ago · Sep 30, 2016, 01:24 PM
1<?php
2// Script users (registration /login) - coursesweb.net/php-mysql/
3
4// here add you data for connecting to MySQL database (MySQL server, user, password, database name)
5$mysql['host'] = 'localhost';
6$mysql['user'] = 'root';
7$mysql['pass'] = '';
8$mysql['bdname'] = '9_register_login_script_users_online_v1';
9
10// if $rank is 0, the script will send a link to the user's e-mail, to confirm the registration
11// if $rank > 0, the user can log in immediately after registration
12$rank = 0;
13
14// here you cand edit the settings for the image uploded by User
15$imgup = array(
16 'dir' => 'usersimg/', // directory where the images will be saved
17 'allowext' => array('gif', 'jpg', 'jpe', 'png'), // allowed extensions
18 'maxsize' => 500, // maximum allowed size for the image file, in KiloBytes
19 'width' => 800, // maximum allowed width, in pixeli
20 'height' => 600 // maximum allowed height, in pixeli
21);
22
23
24// start session (if isn't started), and header for utf-8
25if(!isset($_SESSION)) session_start();
26header('Content-type: text/html; charset=utf-8');
27
28// if "get_magic_quotes_gpc" is activated, delete additional slashes
29if(get_magic_quotes_gpc()) { $_POST = array_map("stripslashes", $_POST); }
30
31include('class.Logare.php'); // Include the Logare class
32?>
33
34<?php
35// Logare class Logare
36class Logare {
37 // properties
38 protected $conn = false; // store the connection to mysql
39 protected $conn_datas = array(); // will contain the data for connecting to mysql
40 protected $sid; // for the session ID
41 protected $nr_logs = 1; // for the current number of login attempts
42 public $users = array(); // will store the total users, last registered, and online users
43 protected $eror = false; // to store the errors
44 protected $ip; // for the user IP (the IP saved in cookie or the current IP)
45 public $dir = 'users/'; // the directory that contains the classes for this script
46 protected $file_log = 'index.php'; // the file in which the instances of the classes are created
47 public $logat = ''; // stores the login form or the "Welcome" message
48 public $js = ''; // for the code that include the file with JavaScript functions
49
50 // constructor
51 public function __construct($conn_datas) {
52 // daca parametrul e array
53 if(is_array($conn_datas)) {
54 $this->conn_datas = $conn_datas; // add data from parameter in 'conn_datas' property
55 $this->sid = session_id(); // add the session ID in $sid property
56
57 // define the $js property
58 $this->js = '<script src="'. $this->dir. 'logare.js" type="text/javascript"></script>';
59
60 // if no $_POST['ajax'], define the login form in "logat" property
61 if(!isset($_POST['ajax'])) $this->logat = '<form action="" method="post" id="log_form"> Name: <input type="text" name="nume" id="nume" size="12" maxlength="30" /> <input type="submit" name="login" class="submit" value="Login" /><br /> Password: <input type="password" name="pass" id="pass" size="11" maxlength="30" /> <label for="rem" id="lrem"><input type="checkbox" name="rem" id="rem" />Remember</label><br/><br/>
62 <a href="'. $this->dir.$this->file_log. '?rc=Recover" title="Recover data" id="recdat">Recover data</a>
63 <span id="log_reg"><a href="'. $this->dir.$this->file_log. '?submit=Register" title="Register" id="linkreg">Register</a></span></form>'.$this->js;
64
65 // if $_COOKIE['ip'] exists, get the IP from cookie, else, get the current IP and save it in cookie
66 if(isset($_COOKIE['ip'])) $this->ip = $_COOKIE['ip'];
67 else {
68 $this->ip = $_SERVER['REMOTE_ADDR'];
69 setcookie("ip", $this->ip, time()+60*60*24*100, "/");
70 }
71
72 $this->setConn(); // calls setConn() method (that sets the mysql connection)
73
74 // if the connection to database is set ('conn' property isn't false)
75 if($this->conn!==false) {
76 // if there is data from the login form, calls the getLogin() method
77 if(isset($_POST['login']) && isset($_POST['nume']) && isset($_POST['pass'])) {
78 $_POST = array_map("trim", $_POST); // removes whitespace from the beginning and end
79 $this->getLogin($_POST);
80 }
81 // if request for logout ($_GET['lout']), calls logOut() method
82 else if(isset($_GET['lout'])) $this->logOut();
83 else $this->setLogat(); // else, calls setLogat() method that sets the $logat property
84
85 if($this->nr_logs>1) $this->logOut(2); // $nr_logs>1 means two logins with the same name. Logout the user
86 }
87 }
88 else $this->eror = 'The argument for class instance must be an Array';
89
90 // if $eror property isn't false, add it in $logat property
91 if($this->eror!==false) $this->logat = '<div id="logeror">'.$this->eror. '</div>'. $this->logat;
92 }
93
94 // method that create the connection to mysql
95 public function setConn() {
96 // if the connection is successfully established
97 if($conn = new mysqli($this->conn_datas['host'], $this->conn_datas['user'], $this->conn_datas['pass'], $this->conn_datas['bdname'])) {
98 $sql = "SET NAMES 'utf8'";
99 $conn->query($sql);
100 $this->conn = $conn; // add the connection in the $conn property
101 }
102 else if (mysqli_connect_errno()) $this->eror = 'MySQL connection failed: '. mysqli_connect_error();
103 return $this->conn;
104 }
105
106 // method that sets the $logat property (the $sl is passed to the call of the userOn() method)
107 private function setLogat($sl=0) {
108 // If the user is stored in cookie, add the data in session
109 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])) {
110 $_SESSION['nume'] = $_COOKIE['cookname'];
111 $_SESSION['parola'] = $_COOKIE['cookpass'];
112 }
113
114 // if the name and password are stored in session
115 if(isset($_SESSION['nume']) && isset($_SESSION['parola'])) {
116 // calls the confirmUser() method to confirm if the name and passord are valid
117 if($this->confirmUser($_SESSION['nume'], $_SESSION['parola'])===0) {
118 $this->logat = '<div id="logat">Welcome <b>'.$_SESSION['nume'].'<br />Click <a href="'.$this->dir.$this->file_log.'?usr='.$_SESSION['nume'].'" id="idpp">Personal page</a><br/><a href="'.$_SERVER['PHP_SELF'].'?lout=lo">LogOut</a></b></div>'.$this->js;
119 }
120 else {
121 // else, the variables are incorrect, calls logOut() to delete the session and cookies
122 $this->logOut(0);
123 $this->logat = 'Incorrect data logging session';
124 }
125 }
126
127 // calls the method that gets and adds total users, last and registered users in $users property
128 $this->usersOn($sl);
129 }
130
131 // method to check if the string contains only the allowed characters
132 protected function checkStr($str) {
133 $allow = '/^([A-Za-z0-9_-]+)$/';
134 if(preg_match($allow, $str)) return true;
135 else return false;
136 }
137
138 // method that checks data from the login form (passed in parameter) and from the database
139 private function getLogin($ar_post) {
140 // check for allowed characters
141 if(!$this->checkStr($ar_post['nume']) || !$this->checkStr($ar_post['pass'])) $this->eror = 'The data should contain only letters, numbers, "-" and "_"';
142
143 // check the length of the name
144 else if(strlen($ar_post['nume'])<3 || strlen($ar_post['nume'])>32) $this->eror = 'Name must be between 3 and 32 characters';
145
146 // check the length of the password
147 else if(strlen($ar_post['pass'])<7 || strlen($ar_post['pass'])>18) $this->eror = 'Password must be between 7 and 18 characters';
148 else {
149 // Check and register with userTemp() method the log in attempt
150 $continua = $this->userTemp($ar_post['nume']);
151
152 if($continua==='continue') {
153 $md5pass = md5($ar_post['pass']); // encript the password
154 $re = $this->confirmUser($ar_post['nume'], $md5pass); // uses confirmUser() to check if name and password are correct
155
156 // sets 'eror' if name or password are incorrect
157 if($re===1) $this->eror = 'The name <b>'. stripslashes($ar_post['nume']). '</b> not registered';
158 else if($re===2) $this->eror = 'Incorrect password';
159 else if($re===3) {
160 exit('<center><h4 style="color:red">Registration for <u>'. stripslashes($ar_post['nume']). '</u> is unconfirmed.</h4>Check your e-mail used for registration (including in Spamm directory), for the message with the confirmation link.<br /><br />If you wish to request a new confirmation e-mail <a href="'.$this->dir.$this->file_log.'?rc=Confirm">Click here</a></center>');
161 }
162 else {
163 // user name and password are correct
164 // if the "Remember" checkbox is checked, sets 2 cookies, for name and password (expires in 100 days)
165 if(isset($ar_post['rem'])) {
166 setcookie("cookname", $_SESSION['nume'], time()+60*60*24*100, "/");
167 setcookie("cookpass", $_SESSION['parola'], time()+60*60*24*100, "/");
168 }
169
170 // UPDATE `ip_visit` with the user's IP, and the `visits` number
171 $sql = "UPDATE `users` SET `ip_visit`='$this->ip', `visits`=`visits`+1 WHERE `nume`='". $_SESSION['nume']. "' LIMIT 1";
172 $this->conn->query($sql);
173
174 $this->setLogat(1); // calls the method that sets $logat property
175 }
176 }
177 else {
178 // Sets a message with the remaining time to a new allowed authentication attempt
179 $continua = floor($continua/60). ' minute, '. ($continua%60). ' secunde';
180 $this->eror = 'Exceeding number of login attempts.<br/>You can retry after:<br /><b>'. $continua. '</b>';
181 }
182 }
183 }
184
185 // this method checks the name and password in the database,
186 // if they are correct returns 0, otherwise 1 or 2, indicating the error
187 private function confirmUser($nume, $parola) {
188 // apply real_escape_string() to filter data
189 $nume_db = $this->conn->real_escape_string($nume);
190
191 // Check if the name is in the database
192 $sql = "SELECT `id`, `parola`, `rank`, DATE_FORMAT(`datevisit`, '%M %D, %Y, %H:%i') AS datavisit FROM `users` WHERE `nume`='$nume_db' LIMIT 1";
193 $result = $this->conn->query($sql);
194 if(!$result || $result->num_rows<1) return 1; // Indicates name not confirmed
195 else {
196 // Find password that is associated with the name
197 $dbarray = $result->fetch_assoc();
198 $dbarray['parola'] = stripslashes($dbarray['parola']);
199
200 // Check if the user is confirmed
201 if ($dbarray['rank']==0) return 3; // Registration has not been confirmed
202
203 // if the password is the same as that found in the database
204 else if($parola==$dbarray['parola']) {
205 // adds in session name, parola, id, rank, and last-visit-date (if isn't added)
206 $_SESSION['nume'] = $nume;
207 $_SESSION['parola'] = $parola;
208 $_SESSION['idusr'] = $dbarray['id'];
209 $_SESSION['rank'] = $dbarray['rank'];
210 if(!isset($_SESSION['datavisit'])) $_SESSION['datavisit'] = $dbarray['datavisit'];
211 return 0; // name and password confirmed
212 }
213 else return 2; // indicating incorrect password
214 }
215 }
216
217 // this method deletes rows in the 'user_temp' table, older than 10 minutes
218 // if the user already tried 3 times to log in, blocks that name for 10 minutes
219 private function userTemp($nume) {
220 $dt = time();
221 $timp_expir = $dt-600;
222
223 // deletes rows in the 'user_temp' table, older than 10 minutes
224 $sql = "DELETE FROM `user_temp` WHERE `dt`<$timp_expir";
225 $this->conn->query($sql);
226
227 $nume = $this->conn->real_escape_string($nume); // Filter the name to add safe
228
229 // add / increment number of attempt by 1, and updates the date-time
230 $sql = "INSERT INTO `user_temp` (`nume`, `ip`, `dt`) VALUES ('$nume', '$this->ip', $dt) ON DUPLICATE KEY UPDATE `nri`=`nri`+1";
231 $this->conn->query($sql);
232
233 // check if it was performed UPDATE (existing names) [ mysql_affected_rows()=2]
234 if($this->conn->affected_rows==2) {
235 // select to get the number of attempts
236 $sql = "SELECT `nume`, `nri`, `dt` FROM `user_temp` WHERE `nume`='$nume' LIMIT 1";
237 $result = $this->conn->query($sql);
238
239 if(!$result || $result->num_rows<1) return 'continue';
240 else {
241 // get the number of login attempts, 'nri'
242 $tbarray = $result->fetch_assoc();
243 $nri = $tbarray['nri'];
244 if($nri<3) return 'continue';
245 else {
246 $timp = 600 - ($dt - $tbarray['dt']);
247 return $timp; // Indicates number of attempts exceeded, returns the number of seconds to wait
248 }
249 }
250 }
251 else return 'continue'; // otherwise, it was performed INSERT
252 }
253
254 // this method gets the total number of users, last registered user, and online users
255 private function usersOn($sl) {
256 $re = array('total'=>0, 'last'=>'', 'online'=>0); // this array will be added in $users property
257 $dt = time();
258 $timp_expir = $dt-120; // Current time minus 2 minutes
259
260 // deletes rows in the 'useron' table, older than 2 minutes
261 $sql = "DELETE FROM `useron` WHERE `dt`<$timp_expir";
262 $this->conn->query($sql);
263
264 // If the user is logged in, insert or update him in 'useron'
265 if(isset($_SESSION['nume'])) {
266 $nume = $this->conn->real_escape_string($_SESSION['nume']); // Filter the name to add safe
267
268 // add the users, or if already in the table, update date-time
269 $upd_sid = ($sl==1) ? ", `sid`='$this->sid'" : ''; //if $sl is 1 (the user is logging) sets to update the SID too
270 $sql = "INSERT INTO `useron` (`nume`, `sid`, `dt`) VALUES ('$nume', '$this->sid', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt". $upd_sid;
271 $this->conn->query($sql);
272 }
273
274 // select that gets the total number of users, last registered user, and online users
275 $sql = "SELECT `useron`.`nume`, `useron`.`sid`, (SELECT count(*) FROM `users`) AS nrusers, (SELECT `nume` FROM `users` WHERE `rank`>0 ORDER BY `id` DESC LIMIT 1) AS last FROM `useron`";
276 $result = $this->conn->query($sql);
277
278 // if the select returns at least one row
279 if($result->num_rows>0) {
280 while ($rand = $result->fetch_assoc()) {
281 $useron = stripslashes($rand['nume']);
282 if($useron!==NULL) $numeon[] = '<a href="'.$this->dir.$this->file_log.'?usr='.$useron.'" title="'.$useron.'">'.$useron.'</a>';
283
284 // if $_SESSION['nume'] exists and the SID from table is different from $sid, increment $nr_logs
285 if(isset($_SESSION['nume'])) {
286 if(strtolower($useron)==strtolower($_SESSION['nume']) && $rand['sid']!==$this->sid) $this->nr_logs++;
287 }
288
289 // adds the total number of users, last registered user, and online users in $nrusers property
290 $re['total'] = $rand['nrusers'];
291 $re['last'] = '<a href="'.$this->dir.$this->file_log.'?usr='.$rand['last'].'" title="'.$rand['last'].'">'.$rand['last'].'</a>';
292 $re['online'] = implode('<br/>', $numeon);
293 }
294 }
295 else {
296 // if 0 returned rows, perform another Select for total users (when 'useron' is empty, the "nrusers" also returns 0)
297 $sql = "SELECT `nume` AS last, (SELECT count(*) FROM `users`) AS nrusers FROM `users` WHERE `rank`>0 ORDER BY `id` DESC LIMIT 1";
298 $result = $this->conn->query($sql);
299 if($result->num_rows>0) {
300 $rand = $result->fetch_assoc();
301 $re['total'] = $rand['nrusers'];
302 $re['last'] = '<a href="'.$this->dir.$this->file_log.'?usr='.$rand['last'].'" title="'.$rand['last'].'">'.$rand['last'].'</a>';
303 }
304 }
305
306 $this->users = $re; // adds in the $users property the array stored in $re
307 }
308
309 // the method for LogOut
310 private function logOut($rd=1) {
311 // if there are cookies for name and password, sets to remove them
312 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
313 setcookie("cookname", "", time()-60*60*24*100, "/");
314 setcookie("cookpass", "", time()-60*60*24*100, "/");
315 }
316
317 // if $rd parameter different from 2, delete the user from the onlinwe-users
318 if($rd!==2) {
319 $sql = "DELETE FROM `useron` WHERE `nume`='".$_SESSION['nume']."'";
320 $this->conn->query($sql);
321 }
322
323 // if exist sessions with: nume, parola, idusr, and datavisit, delete them, then perform redirect
324 if(isset($_SESSION['nume'])) unset($_SESSION['nume']);
325 if(isset($_SESSION['parola'])) unset($_SESSION['parola']);
326 if(isset($_SESSION['idusr'])) unset($_SESSION['idusr']);
327 if(isset($_SESSION['rank'])) unset($_SESSION['rank']);
328 if(isset($_SESSION['datavisit'])) unset($_SESSION['datavisit']);
329
330 // if $rd=1, auto-redirect to avoid resending data on refresh
331 if($rd===1) echo '<meta http-equiv="Refresh" content="1;url=/"><script type="text/javascript">alert("Logged Out");</script>';
332 else if($rd===2) echo '<meta http-equiv="Refresh" content="1;url=/"><script type="text/javascript">alert("Logged OutnThere is another Login with this account.nYou can re-login.");</script>';
333 exit;
334 }
335}
336?>
337
338<?php
339// LogareReCon class, extended from LogareReg
340class LogareReCon extends LogareReg {
341 // constructor
342 public function __construct($conn_datas) {
343 // if $conn_datas is an array, sets 'conn_datas' property, and calls setConn() method, otherwise, error
344 if(is_array($conn_datas)) {
345 $this->conn_datas = $conn_datas; // adds data from parameter in 'conn_datas' property
346 $this->site = $_SERVER['SERVER_NAME'];
347
348 // if received data through POST, or GET for confirmation, creates connection
349 if((isset($_POST['submit']) && isset($_POST['email'])) || (isset($_GET['mp']))) $this->setConn();
350
351 // if 'conn' property is set
352 if($this->conn!==false) {
353 // if GET (for confirmation) calls getConfirm(), otherwise, calls getReCon() with form data
354 if(isset($_GET['mp'])) {
355 $_GET = array_map("strip_tags", array_map("trim", $_GET)); // remove external whitespace
356 $this->result = $this->getConfirm($_GET['mp']);
357 }
358 else {
359 $_POST = array_map("strip_tags", array_map("trim", $_POST)); // remove external whitespace and tags
360 $this->result = $this->getReCon($_POST);
361 }
362 }
363 else $this->result = $this->setFormReCon($_REQUEST['rc']); // initially returns the form
364 }
365 else $this->result = 'The parameter should be an array';
366
367 echo $this->result; // return / output the data stored in $result
368 }
369
370 // this method sends the user data to his e-mail, or the message for reconfirmation
371 private function getReCon($ar_post) {
372 $tip = $ar_post['submit']; // request type (recovery or confirmation)
373 $email = $ar_post['email'];
374 $re = $tip; // for data returned by this method
375
376 // validate the e-mail address
377 if(preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/", $email)) {
378 // If the verification code is correct
379 if(isset($_SESSION['nrv']) && $_SESSION['nrv']==$ar_post['nrv']) {
380 unset($_SESSION['nrv']);
381
382 // check if email address is in the database
383 $sql = "SELECT `nume`, `parola`, `pass`, `email`, `id` from `users` WHERE `email`='$email' LIMIT 1";
384 $result = $this->conn->query($sql);
385
386 // if not found, sets a message and add the form with the setFormReCon() method
387 if(!$result || $result->num_rows<1) {
388 $re = '<div id="logeror">There is not registration with the e-mail: <i><u>'. $email.'</u></i></div><br/>'.$this->setFormReCon($tip);
389 }
390 else {
391 // gets the name, password, and id associated to the email
392 while ($rand = $result->fetch_assoc()) {
393 $nume = stripslashes($rand['nume']);
394 $parola = stripslashes($rand['parola']);
395 $pass = stripslashes($rand['pass']);
396 $id = (int)$rand['id'];
397 }
398
399 // sends data to e-mail (recovery request)
400 if($tip=='Recover') {
401 // sets the subject and message
402 $subiect = 'Recovery registration datas';
403 $mesaj1 = " Hy<br /> n
404 You received this email due to a request to recover your registration data on $this->site. nn";
405 }
406 else if($tip=='Confirm') {
407 // sets the link for registration confirmation
408 $set_url = 'http://'. $_SERVER['HTTP_HOST'].'/'. $this->dir.$this->file_log. '?mp='. $id. '_'. $parola;
409 $link_confirm = '<a href="'. $set_url. '">'. $set_url. '</a>';
410 // sets subject and message
411 $subiect = 'Registration Confirmation';
412 $mesaj1 = " Hy<br /> n
413 You received this email due to a request to resend the link for registration confirmation.<br /> nn
414 To confirm the registration on $this->site , click on the following link:<br /><br /> n
415 $link_confirm <br /> nn";
416 }
417
418 $mesaj2 = "<br />Your login data are:<br /><br /> n
419 Name = $nume <br /> n
420 Password = $pass <br /><br /> nn
421 <center><i>If you want, visit also: <a href="http://coursesweb.net/">coursesweb.net</a></i></center><br /><br /><br /> nn
422 Have a good day<br /> n
423 With respect, Admin";
424 $mesaj = $mesaj1. $mesaj2;
425 if($this->sendMail($email, $this->from, $this->site, $subiect, $mesaj)) {
426 $re = '<center>Your login data have been sent to: <b>'. $email. '</b>.<br />
427 Check the Spamm folder, too. If you have not received the email, please contact the site administrator.
428 <br /><br />Thank you, <a href="/">Home Page</a></center>';
429 }
430 else {
431 $re = '<div id="logeror"><h2>Error at data checking.<br/>Try again.</h2></div><br />'.$this->setFormReCon($tip);
432 }
433 }
434 }
435 else {
436 unset($_SESSION['nrv']);
437 $re = '<h4 id="logeror">Incorrect verification code.</h4><br />'.$this->setFormReCon($tip);
438 }
439 }
440 else $re = '<div id="logeror">Incorrect e-mail address.</div><br />'.$this->setFormReCon($tip);
441 return $re;
442 }
443
444 // the method that confirms the registration
445 private function getConfirm($get) {
446 // get and split data (id_password) to check in database
447 $ar_get = explode('_', $get);
448 $id = (int)$ar_get[0];
449 $parola = $ar_get[1];
450 $rank = 1;
451
452 $parola = $this->conn->real_escape_string($parola); // filter to add safety
453
454 // update to set 'rank' to the value of $rank
455 $sql = "UPDATE `users` SET `rank`='$rank' WHERE `id`='$id' AND `parola`='$parola' LIMIT 1";
456 if($this->conn->query($sql)) {
457 // Select to check if 'rank' was updated
458 $sql = "SELECT `rank` FROM `users` WHERE `id`='$id' LIMIT 1";
459 $result = $this->conn->query($sql);
460 $rand = $result->fetch_assoc();
461 if($rand['rank']>0) $re = '<center><font color="blue"><h2>Confirmation approved</h2></font><h4>Now you can log on the site. <a href="/">Home Page</a></h4></center>';
462 else {
463 $link_confirm = '<b><a href="'.$this->dir.$this->file_log.'?rc=Confirm">Click aici</a></b>';
464 $re = '<center><font color="red"><h2>Confirmation approved</h2></font><h4>The URL for confirmation is incorrect</h4><br /><br /> - To request a new e-mail with the link for confirmation: '. $link_confirm. '<br /><br /><i>Or contact the site administrator.</i></center>';
465 }
466 }
467 else $re = 'The Confirmation failed, error: '. $this->conn->error;
468 $this->conn->close();
469 return $re;
470 }
471
472 // the method with the form for Recovery and Confirmation
473 function setFormReCon($tip) {
474 $nrv = $this->setCodNr('nrv'); // calls the method that returns a verification code
475
476 // define the form
477 $re = '<div id="form_re">
478 <p>Add the e-mail address you used for registration and this verification code: <b><font color="blue" size="4">'. $nrv. '</font></b></p><br />
479 <form action="" method="post" onsubmit="return datReCon(this);">
480 <input type="hidden" name="nrv0" value="'. $nrv. '" />
481 <label for="email">E-mail: </label> <input type="text" name="email" maxlength="42" id="email" /><br /><br />
482 <label for="nrv">Verification code: </label><input type="text" name="nrv" size="5" maxlength="6" id="nrv" /><br />
483 <input type="submit" name="submit" value="'. $tip. '" />
484 </form><br/><sub>From: <a href="http://coursesweb.net/php-mysql/" target="_blank" title="Free PHP-MySQL Course">coursesweb.net</a></sub></div>';
485 return $re;
486 }
487}
488?>
489
490<?php
491// LogareReg class, extended from Logare
492class LogareReg extends Logare {
493 // properties
494 public $from = 'From: contact@domain.net'; // administrator e-mail
495 private $rank; // determines rank and confirmation of registration
496 private $nr_count = 1; // If the value is different from 1, allow the creation of multiple accounts with same IP
497 protected $site; // website name
498 protected $result = ''; // the result returned by this class
499 protected $ip; // the user IP when registers
500
501 // constructor
502 public function __construct($conn_datas, $rank=0) {
503 // if $conn_datas is an array, sets 'conn_datas' property and calls setConn() method, otherwise, error
504 if(is_array($conn_datas)) {
505 // sets the properties values
506 $this->conn_datas = $conn_datas;
507 $this->rank = intval($rank);
508 $this->ip = isset($_COOKIE['ip']) ? $_COOKIE['ip'] : $_SERVER['REMOTE_ADDR'];
509 $this->site = $_SERVER['SERVER_NAME'];
510
511 // if received data through POST, creates connection
512 if(isset($_POST['submit']) && isset($_POST['nrv'])) $this->setConn();
513
514 // if 'conn'is set
515 if($this->conn!==false) {
516 // if received data from the registration form, call the method getReg()
517 if(isset($_POST['nume']) && isset($_POST['email']) && isset($_POST['pass']) && isset($_POST['pass2']) && isset($_POST['nrv'])) {
518 $_POST = array_map("strip_tags", array_map("trim", $_POST)); // remove external whitespace and tags
519 $this->result = $this->getReg($_POST);
520 }
521 else $this->result = 'Incorrect form fields';
522 }
523 else $this->result = $this->setFormReg(); // returns only the form
524 }
525 else $this->result = 'The first parameter should be an array';
526
527 echo $this->result; // Return the $result property
528 }
529
530 // the method sends the e-mail
531 protected function sendMail($to, $from, $from_name, $sub, $msg){
532 $eol = "rn"; // Used for new line
533
534 // Sets headers for email
535 $headers = "From: " . $from_name . "<" . $from . ">".$eol;
536 $headers .= "MIME-Version: 1.0" . $eol;
537 $headers .= "Content-type: text/html; charset=iso-8859-1" . $eol;
538
539 // If the mail is sent successfully returns True, otherwise False
540 if (mail($to, stripslashes($sub), stripslashes($msg), $headers)) return true;
541 else return false;
542 }
543
544 // the method that adds user's data in database
545 private function addUser($nume, $pass, $email) {
546 $parola = md5($pass);
547 $nume1 = $nume;
548
549 // filter to add safety in database
550 $nume = $this->conn->real_escape_string($nume);
551 $pass = $this->conn->real_escape_string($pass);
552 $email = $this->conn->real_escape_string($email);
553
554 $sql = "INSERT INTO `users` (`nume`, `parola`, `email`, `rank`, `ip_reg`, `ip_visit`, `datereg`, `pass`) VALUES ('$nume', '$parola', '$email', '$this->rank', '$this->ip', '$this->ip', NOW(), '$pass')";
555 if($this->conn->query($sql) === TRUE) {
556 $mesaj = '<center><h1>Succes!</h1>
557 <font size="4">Thank you <b><font color="blue">'. $nume1. '</font></b>, the registration has been completed successfully.</font><br /><br />You can Log in.</center>';
558
559 $id = $this->conn->insert_id; // gets the auto-inserted ID
560
561 // sets the link for registration confirmation
562 $set_url = 'http://'. $_SERVER['HTTP_HOST'].'/'. $this->dir.$this->file_log. '?mp='. $id. '_'. $parola;
563 $link_confirm = '<a href="'. $set_url. '">'. $set_url. '</a>';
564
565 if($this->rank===0) {
566 // sets subject and message
567 $subiect = 'Confirm the registration on: '.$this->site;
568 $mesaj = " Hy <br />
569 You received this message because you need to confirm your registration on the website $this->site <br /><br />
570To confirm the registration, click on the following link (<i>or copy it in the address bar of your browser</i>):<br /><br />
571 <center><b> $link_confirm </b></center><br /><br />
572 Your login data:<br /><br />
573 Nume = $nume1 <br />
574 Parola = $pass <br /><br /><br />
575 <center><i>If you want, visit also <a href="http://coursesweb.net/">coursesweb.net</a></i></center><br /><br /><br />
576<i>Thanks, respectfully,<br /> Admin</i><br />";
577
578 // sends the email
579 $email = stripslashes($email);
580 if($this->sendMail($email, $this->from, $this->site, $subiect, $mesaj)) {
581 $mesaj = '<center><h3>Registration performed successfully</h3>A message with a link to confirm your registration will be send to the e-mail<u> '. $email. '</u>.<br/><br/> If you have not received the email, check the Spamm folder, too.<br/><br/> After confirmation you can log in.</center>';
582 }
583 else $mesaj = 'Error, check if you entered the correct data.';
584 }
585 }
586 else {
587 $mesaj = '<h1>Error:</h1><i>'. $this->conn->error. ' </i><br />Your registration for the name <b>'. $nume1. '</b>, not performed.';
588 }
589 return $mesaj;
590 }
591
592 // sets the string with the error
593 private function strEror($str) { return '<div id="rerror">'.$str.'</div>'.$this->setFormReg(); }
594
595 private function getReg($ar_post) {
596 $nume = $ar_post['nume'];
597 $pass = $ar_post['pass'];
598 $email = $ar_post['email'];
599 $re = false;
600
601 // check if there is already a session with registration
602 if(isset($_SESSION['registered'])) $re = $_SESSION['registered'];
603 // Check if the password is the same as in "Retype password"
604 else if($pass!=$ar_post['pass2']) $re = $this->strEror('You must write the same password in the field "<b>Retype password</b>"');
605 // check the string to contain only the allowed characters
606 else if(!$this->checkStr($nume) || !$this->checkStr($pass)) $re = $this->strEror('The data should contain only letters, numbers, "-" and "_"');
607 // Verifica lungimea numelui
608 else if(strlen($nume)<3 || strlen($nume)>32) $re = $this->strEror('The name must contains between 3 and 32 characters<br/> Only letters, numbers, "-" and "_"');
609 // Verifica lungimea parolei
610 else if(strlen($pass)<7 || strlen($pass)>18) $re = $this->strEror('The password must contains between 7 and 18 characters<br/>Only letters, numbers, "-" and "_"');
611 // Validate the email
612 else if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/", $email)) $re = $this->strEror('Incorrect email address');
613 // check the verification code
614 else if($_SESSION['nrv']!==$ar_post['nrv']) {
615 $re = $this->strEror('Incorrect verification code. '.$ar_post['nrv']);
616 $this->setCodNr('nrv');
617 }
618
619 // if $re is False check the name and e-mail in database
620 else if($re===false) {
621 // filter with real_escape_string()
622 $nume = $this->conn->real_escape_string($nume);
623 $email = $this->conn->real_escape_string($email);
624
625 $sql = "SELECT `nume`, `email`, `ip_reg`, `ip_visit` FROM `users` WHERE `nume`='$nume' OR `email`='$email' OR `ip_reg`='$this->ip' OR `ip_visit`='$this->ip' LIMIT 1";
626 $result = $this->conn->query($sql);
627
628 // check if name and email already in database
629 if($result->num_rows>0) {
630 while ($rand = $result->fetch_assoc()) {
631 $nume_bd = stripslashes($rand['nume']);
632 $email_bd = stripslashes($rand['email']);
633 $ip_reg_bd = stripslashes($rand['ip_reg']);
634 $ip_visit_bd = stripslashes($rand['ip_visit']);
635 }
636 // Sets error if the user name, email-ul, ip_reg, or ip_visit already registered
637 if(strcasecmp($nume_bd, $nume)==0) $re = $this->strEror("The name: <u>$nume</u> already registered, please choose another one.");
638 else if (strcasecmp($email_bd, $email)==0) $re = $this->strEror("The e-mail: <u>$email</u> has already been used for registration");
639 else if ($this->nr_count==1 && (strcasecmp($ip_reg_bd, $this->ip)==0 || strcasecmp($ip_visit_bd, $this->ip)==0)) $re = $this->strEror('There is already a registration with your IP.<br />If you think that is an error, contact the administrator');
640 }
641 else {
642 // calls addUser() methot to add the new account in database, and sets a session with the registration
643 $re = $this->addUser($ar_post['nume'], $pass, trim($ar_post['email']));
644 $_SESSION['registered'] = $re;
645 }
646 }
647 $this->conn->close();
648 return $re;
649 }
650
651 // This method create a verification code in the Session $ses, and return it
652 protected function setCodNr($ses) {
653 // sets the code with the current date-time
654 $data_nrv = date(" j-F-Y, g:i a ");
655 $nr_v = md5($data_nrv);
656 if(isset($_SESSION[$ses])) { unset($_SESSION[$ses]); }
657 $_SESSION[$ses] = substr($nr_v, 3, 5);
658 return $_SESSION[$ses];
659 }
660
661 // method that sets the registration form
662 private function setFormReg() {
663 // if there is a session with the registration, return it. Otherwise return the form
664 if(isset($_SESSION['registered'])) $re = $_SESSION['registered'];
665 else {
666 // keep the data from form fields (not need rewriting)
667 $nume = isset($_POST['nume']) ? $_POST['nume'] : '';
668 $pass = isset($_POST['pass']) ? $_POST['pass'] : '';
669 $pass2 = isset($_POST['pass2']) ? $_POST['pass2'] : '';
670 $email = isset($_POST['email']) ? $_POST['email'] : '';
671 $nrv = $this->setCodNr('nrv'); // seteaza cod de verificare
672
673 $re = '<h2>Registration</h2><div id="form_re">
674 <p><br /><b> - Add your registration data and this code: <font color="blue" size="4">'. $nrv. '</font></b></p>- <i>You must use a valid e-mail address, you will receive a message to confirm the registration.</i><hr style="width:88px;" /><br />
675 <form action="" method="post" onsubmit="return datReg(this)">
676 <input type="hidden" name="nrv0" value="'. $nrv. '" />
677 <label for="nume">Name: </label><input type="text" name="nume" maxlength="32" id="nume" value="'.$nume.'" /><br /><br />
678 <label for="pass">Password: </label><input type="password" name="pass" maxlength="18" id="pass" value="'.$pass.'" /><br /><br />
679 <label for="pass2">Retype password: </label><input type="password" name="pass2" maxlength="18" id="pass2" value="'.$pass2.'" /><br /><br />
680 <label for="email">E-Mail: </label><input type="text" name="email" maxlength="42" id="email" value="'.$email.'" /><br /><br />
681 <label for="nrv">Verification code: </label><input type="text" name="nrv" size="5" maxlength="6" id="nrv" /><br /><br />
682 <input type="submit" name="submit" value="Register" />
683 </form><br/><sub>From: <a href="http://coursesweb.net/php-mysql/" target="_blank" title="Free PHP-MySQL Course">coursesweb.net</a></sub></div>';
684 }
685 return $re;
686 }
687}
688?>
689
690<?php
691header('Content-type: text/html; charset=utf-8');
692
693include('admin.php'); // Include the file with data for connecting to mysql
694$objLogare = new Logare($mysql);
695$conn = $objLogare->setConn(); // get the connection
696
697// Create the users table
698
699 $sql = "CREATE TABLE `users` (`nume` VARCHAR(32), `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, `parola` VARCHAR(32), `email` VARCHAR(45), `rank` DECIMAL(1,0) DEFAULT 0, `ip_reg` VARCHAR(15), `ip_visit` VARCHAR(15), `datereg` DATETIME NULL, `datevisit` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `visits` SMALLINT UNSIGNED DEFAULT 0, `pass` VARCHAR(18)) CHARACTER SET utf8 COLLATE utf8_general_ci";
700 if($conn->query($sql) === TRUE)
701 echo '<br /><br /><br /><center><h4>The <u>users</u> table was created.</h4></center><br />';
702 else
703 echo '<br /><br /><br /><center><h4>The <u>users</u> table could not be created - '. $conn->error. '</h4></center>';
704
705 // Create the user_temp table
706 $sql2 = "CREATE TABLE `user_temp` (`nume` VARCHAR(32) PRIMARY KEY, `nri` TINYINT UNSIGNED DEFAULT 0, `ip` VARCHAR(15), `dt` INT(10)) CHARACTER SET utf8 COLLATE utf8_general_ci";
707 if($conn->query($sql2) === TRUE)
708 echo '<br /><br /><br /><center><h4>The <u>user_temp</u> table was created.</h4></center><br />';
709 else
710 echo '<br /><br /><br /><center><h4>The <u>user_temp</u> table could not be created - '. $conn->error. '</h4></center>';
711
712 // Create the 'userdat' table, which contains the users optional data
713 $sql3 = "CREATE TABLE `usersdat` (`id` INT UNSIGNED PRIMARY KEY, `nume` VARCHAR(32), `pronoun` VARCHAR(32), `country` VARCHAR(15), `city` VARCHAR(25), `adres` VARCHAR(125), `bday` DATE, `ym` VARCHAR(25), `msn` VARCHAR(32), `site` VARCHAR(32), `img` VARCHAR(125), `ocupation` VARCHAR(500), `interes` VARCHAR(500), `transmit` VARCHAR(1000)) CHARACTER SET utf8 COLLATE utf8_general_ci";
714 if($conn->query($sql3) === TRUE)
715 echo '<br /><br /><br /><center><h4>The <u>usersdat</u> table was created.</h4></center><br />';
716 else
717 echo '<br /><br /><br /><center><h4>The <u>usersdat</u> table could not be created - '. $conn->error. '</h4></center>';
718
719 // Create useron table (which store the online users)
720 $sql4 = "CREATE TABLE `useron` (`nume` VARCHAR(32) PRIMARY KEY, `sid` CHAR(50), `dt` INT(10)) CHARACTER SET utf8 COLLATE utf8_general_ci";
721 if ($conn->query($sql4))
722 echo '<br /><br /><br /><center><h4>The <u>useron</u> table was created.</h4></center><br />';
723 else
724 echo '<br /><br /><br /><center><h4>The <u>useron</u> table could not be created - '. $conn->error. '</h4></center>';
725
726 $conn->close();
727 ?>
728
729<?php
730include('admin.php');
731// create the object instance of Logare class
732$objLogare = new Logare($mysql);
733$logare = $objLogare->logat; // get data from the "logat" property
734
735// sets a variable which determines whether or not the request is by Ajax via POST
736$is_ajax = (isset($_POST['ajax'])) ? 1 : 0;
737
738// if data via GET or POST with index 'submit', 'mp', 'rc' (Confirm / Recover), 'usr' (User data)
739if(isset($_REQUEST['submit']) || isset($_GET['mp']) || isset($_REQUEST['rc']) || isset($_GET['usr'])) {
740 // sets to not include login data to Registration or data Recovery request
741 if(isset($_REQUEST['submit']) || isset($_REQUEST['rc'])) $logare = '';
742
743 if($is_ajax===0) include('../templ/head.php'); // if not Ajax request, include head.php (from templ/)
744 include('class.LogareReg.php'); // include the class for Register (used also for Recovery data)
745
746 // if 'submit'=Register, create objet of LogareReg (for Register)
747 // if 'rc' or 'mp' (for Recover-Confirma), uses LogareReCon class
748 // if 'usr', create object of LogareUser class (for user page data)
749 if(isset($_REQUEST['submit']) && $_REQUEST['submit']=='Register') {
750 $objRe = new LogareReg($mysql, $rank);
751 }
752 else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
753 include('class.LogareReCon.php');
754 $objRe = new LogareReCon($mysql, $rank);
755 }
756 else if(isset($_REQUEST['usr'])) {
757 include('class.LogareUser.php');
758 $objUsr = new LogareUser($mysql, $imgup);
759
760 // if not Submit, calls the getUser() method, that returns an Array with user data
761 if(!isset($_REQUEST['submit'])) $ar_usrdat = $objUsr->getUser($_REQUEST['usr']);
762 }
763
764 if(isset($_GET['usr']) && $is_ajax===0) include('../templ/usrbody.php'); // include usrbody.php, for user page
765 if($is_ajax===0) include('../templ/footer.php'); // if not Ajax request, include footer.php (from templ/)
766}
767
768// if is Ajax request, with index ajax=log output the response
769if(isset($_POST['ajax'])) if($_POST['ajax']=='log_form') echo $logare;
770?>