PHP - Mysql Privileges Per User Signup
Hi,
I have wondered if just one user should be used (e.g. root) for connecting to the database is the right way of doing things? (which is what I have always done). Would it be better to have a new user created in the privileges section in MySQL and have all operation/table access assigned appropriately for every single user that signs up? I would think that this would give a lot more security but would need a bit more work. What are your thoughts? Similar TutorialsHi there I have a problem here, I think I may know what it is but just wanted some guidance on this issue. I took the logic from a previous help from the people on this forum and here is my landing page: <?php // ini_set("display_errors", 1); // randomly starts a session! session_name("jeremyBasicLogin"); session_start(); if(isset($_SESSION['username'])) { // display whatever when the user is logged in: echo <<<ADDENTRY <html> <head> <title>User is now signed in:<title> </head> <body> <h1>You are now signed in!</h1> <p>You can do now what you want to do!</p> </body> </html> ADDENTRY; } else { // If anything else dont allow access and send back to original page! header("location: signin.php"); } ?> This is where the user goes to when they go to this system (not a functional system, ie it doesnt actually do anything its more for my own theory. As you wont have a session on the first turn to this page it goes to: signin.php which contains: <?php // ini_set("display_errors", 1); require_once('func.db.connect.php'); if(array_key_exists('submit',$_POST)) { dbConnect(); // connect to database anyways! // Do a procedure to log the user in: // Santize User Inputs $username = trim(stripslashes(mysql_real_escape_string($_POST['username']))); // cleans up with PHP first! $password = trim(stripslashes(mysql_real_escape_string(md5($_POST['password'])))); // cleans up with PHP first! $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); if(mysql_num_rows($result) == 1) { session_name("jeremyBasicLogin"); session_start(); $_SESSION['is_logged_in'] = true; $_SESSION['username'] = $username; //print_r($_SESSION); // debug purposes only! $_SESSION['time_loggedin'] = time(); // this is adding to the array (have seen the output in the SESSION vars! // call function to update the time stamp in MySQL? header("location: index.php"); } else if(mysql_num_rows($result) != 1) { $message = "You typed the wrong password or Username Please retry!"; } } else { $message = ""; } // displays the login page: echo <<<LOGIN <html> <body> <h1>Example Login</h1> <form id="login" name="login" action="{$_SERVER['PHP_SELF']}" method="post"> <label for="username">Username: </label><input type="text" id="username" name="username" value="" /><br> <label for="password">Password: </label><input type="text" id="password" name="password" value="" /><br> <input type="submit" id="submit" name="submit" value="Login" /> </form> LOGIN; echo "<p>" . $message . "</p>"; echo <<<LOGIN <p>Please Login to View and Edit Your Entries</p> <p><a href="register.php">Click Here To Signup</a><p> </body> </html> LOGIN; ?> This checks through user inputs and hopefully logs them in, when Ive inserted the data into the database itself it works, if I try and login but if a user fills in this form: signup.php: <?php //ini_set("display_errors", 1); $message =''; require_once('func.db.connect.php'); if(array_key_exists('submit',$_POST)) { dbConnect(); // connect to database anyways! // do some safe protecting of the users variables, apply it to all details! $username = trim(stripslashes(mysql_real_escape_string($_POST['username']))); // cleans up with PHP first! $email = trim(stripslashes(mysql_real_escape_string($_POST['email']))); // cleans up with PHP first! $password = trim(stripslashes(mysql_real_escape_string(md5($_POST['password'])))); // does as above but also encrypts it using the md5 function! $password2 = trim(stripslashes(mysql_real_escape_string(md5($_POST['password2'])))); // does as above but also encrypts it using the md5 function! if($username != '' && $email != '' && $password != '' && $password2 != '') { // do whatever when not = to nothing/empty fields! if($password === $password2) { // do database stuff to enter users details $sql = "INSERT INTO `test`.`users` (`id` ,`username` ,`password`) VALUES ('' , '$username', MD5( '$password' ));"; $result = mysql_query($sql); if($result) { $message = 'You may now login by clicking <a href="index.php">here</a>'; } } else { // echo out a user message says they got their 2 passwords incorrectly typed: $message = 'Pleae re enter your password'; } } else { // they where obviously where empty $message = 'You missed out some required fields, please try again'; } } echo <<<REGISTER <html> <body> <h1>Register Form</h1> <p>Please fill in this form to register</p> <form id="register" name="register" action="{$_SERVER['PHP_SELF']}" method="post"> <table> <tr> <td><label for="username">Username: </label></td> <td><input type="text" id="username" name="username" value="" /></td> </tr> <tr> <td><label for="email">Email: </label></td> <td><input type="text" id="email" name="email" value="" /></td> </tr> <tr> <td><label for="password">Password: </label></td> <td><input type="text" id="password" name="password" value="" /></td> </tr> <tr> <td><label for="password">Confirm Password: </label></td> <td><input type="text" id="password2" name="password2" value="" /></td> </tr> <tr> <td><input type="submit" id="submit" name="submit" value="Register" /></td> </tr> <table> REGISTER; echo "<p>" . $message . "</p>"; echo <<<REGISTER </form> </body> </html> REGISTER; ?> As I said when the user signs up when submitting the above form, it doesnt work, keeps coming up with a different value for the password, so I am about 99% certain its the password, but I have been maticulous about copying in the sanitize function for SQL injections and it just doesnt still work, really puzzled now. Any helps appreciated, Jeremy. I am attempting to have some links show up on my page only if a user is an admin. The way I have the user data base is user name password and rank. rank is a 1 or 2, 2 for admin. This is what I have right now as a test bed, I think the rank variable is not being passed properly but I'm not sure. Thanks in advance. This is what i have for the log in page Code: [Select] <?php //connection stuff $sql="SELECT * FROM user WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); $rank=mysql_num_rows('rank'); if($count==1){ session_start(); $_SESSION['login'] = "1"; $_SESSION['rank'] = $rank; header ("Location:index.php"); } else { $errorMessage = "Invalid Login"; session_start(); $_SESSION['login'] = ''; } ?> This is the header that will be on every page to keep the session. Code: [Select] <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); ?> <?php session_start(); if(!$_SESSION['login']){ $_SESSION['rank']; header("location:login.php"); } ?> <?php $rank=$_SESSION['rank']; ?> And this is what I have to show the link. Code: [Select] <?php if($rank<=2){ ?> <tr> <td><span class="nav"><a href="link">link</a></span><br /></td> </tr> <?php } ?> Hello fellow PHP Freaks Is there a way to assign mysql access privileges using a php script? Maybe when your registering a user and assign them a role, depending on the role, they get certain privileges on the db... I need help. Thank you in advance. Hi, I am getting frustrated beyond belief at the moment with trying to get a very simple script to run, I am using PHP 5.3.3 and MySQL 5.1 on a Win2k8 server with IIS7.5. Basically my script is connecting to a local database, running a single select query, returning those rows and building up a string from them. The problem is that I am receiving complete BS responses from PHP that the access is denied for the user being specified. This is complete rubbish since the user can connect via mysql, sqlyog, ASP.NET MVC without issue but for some bizarre reason it is not working via PHP. The code for the script is here : Code: [Select] <?php $mysql = mysql_connect('127.0.0.1:3306', 'myuser', 'mypass', 'mydatabase'); if (!$mysql) { die(mysql_error()); $content = "<nobr></nobr>"; } else { $result = mysql_query('SELECT * FROM tblEventGroup'); $content = "<nobr>"; if ($result) { while($row = mysql_fetch_assoc($result)) { $content .= "<span>"; $content .= $row['GroupName']; $content .= "</span>"; $content .= "<a href=\"../Event/EventSearch?groupid="; $content .= $row['GroupId']; $content .= "\" target=\"_blank\">Book here</a> "; } } mysql_close($mysql); $content .= "</nobr>"; } ?> I cannot for the life of me understand what the problem is, the return error is Access denied for user 'myuser'@'localhost' (using password: YES) create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Hi Guys, I can't figure this one out, in my registration code i set it to email when a user successfully registers: code: <?php if (isset($_POST['submitSignUp'])) { // Errors array() $errors = array(); // POST vars $fName = mysql_real_escape_string($_POST['fname']); $lName = mysql_real_escape_string($_POST['lname']); $email = mysql_real_escape_string($_POST['email']); $pass1 = mysql_real_escape_string($_POST['pass1']); $pass2 = mysql_real_escape_string($_POST['pass2']); $cntry = mysql_real_escape_string($_POST['cntry']); // Does passwords match if ($pass1 != $pass2) { $errors[] = "Your passwords don't match."; } // Potential errors // Empty fields if (empty($fName) || empty($lName) || empty($email) || empty($pass1) || empty($pass2)) { $errors[] = "You never filled in all the fields."; } else { // Does user exist? $result = mysql_query("SELECT * FROM `dig_customers` WHERE `email`='$email' LIMIT 1"); if (mysql_num_rows($result) > 0) { $errors[] = "The e-mail address <b>$email</b> has already been registered."; } else { // Empty for now... } } // display errors if any exist if (count($errors) > 0) { print "<div id=\"errorMsg\"><h3>Ooops! There was error(s)</h3><ol>"; foreach($errors as $error) { print "<li>$error</li>"; } print "</ol></div>"; } else { print "<div id=\"okMsg\"><p>All done :) you can now sign in.</p></div>"; // Encrypt the password before insertion $encPass = md5($pass1); // Insert into the database $q = mysql_query("INSERT INTO `dig_customers` (`id`, `password`, `password_unencrypted`, `gender`, `title`, `first_name`, `last_name`, `address`, `city`, `state_county`, `post_zip_code`, `country`, `email`, `home_number`, `mobile_number`, `news_letter`, `special_offers`, `admin_level`, `registered`) VALUES ('', '$encPass', '$pass1', 'NULL', 'NULL', '$fName', '$lName', 'NULL', 'NULL', 'NULL', 'NULL', '$cntry', '$email', 'NULL', 'NULL', 'NULL', 'NULL', 'N', NOW())"); if ($q) { // Alert on signup send_graham_email("User Has Signed Up!"); } } } ?> i moved this part: print "<div id=\"okMsg\"><p>All done you can now sign in.</p></div>"; and the INSERT query to where it is now thinking this has solved it, but i just got an email saying "user has signed up!" but when i check the stats they haven't LOL can anyone see where i have went wrong? cheers guys Graham hi i am new on php+mysql i am trying to create signup form that will: users to enter email address and the script check via ajax from MYSQL database if the email is not registered send the signup link to their email if already registered than show error you are a member. In my post.php file i have the following code // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; mysql_real_escape_string($usercheck); $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Sorry, the username is already in use."; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); die(); } The problem is it always 500s if the username is already in use. Please help me in php coding I need to open php file when i click on link <Click here> in that php file i need to collect three email id's in the form and post the form to another php file, for those emails id's i need to send email containing activation key, with the help of that link in their email inbox that user need to signup with username and password and more details ..then user can able to login to account in my client website for more actions This part is where i am kinda struck while generating activation key, i googled but no help..if any one help me appreciated thanks Danny danny_boy9988@yahoo.com heres the code for the login page ...i changed the server and username info for privacy <?php include "include/session.php"; $dbservertype='mysql'; $servername='supremeserver.com'; // username and password to log onto db server $dbusername='newlogin'; $dbpassword='new18'; // name of database $dbname='newlogin'; connecttodb($servername,$dbname,$dbusername,$dbpassword); function connecttodb($servername,$dbname,$dbusername,$dbpassword) { global $link; $link=mysql_connect ("$servername","$dbusername","$dbpassword"); if(!$link){die("Could not connect to MySQL");} mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error()); } ?> <!doctype html public "-//w3c//dtd html 3.2//en"> <html> <head> <title>LOGIN</title> <meta name="GENERATOR" content="Arachnophilia 4.0"> <meta name="FORMATTER" content="Arachnophilia 4.0"> </head> <body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000"> <?php $userid=mysql_real_escape_string($userid); $password=mysql_real_escape_string($password); if($rec=mysql_fetch_array(mysql_query("SELECT * FROM plus_signup WHERE userid='$userid' AND password = '$password'"))){ if(($rec['userid']==$userid)&&($rec['password']==$password)){ include "include/newsession.php"; echo "<p class=data> <center>Successfully,Logged in<br><br><a href='logout.php'> Log OUT </a><br><br><a href=welcome.php>Click here if your browser is not redirecting automatically or you don't want to wait.</a><br></center>"; print "<script>"; print " self.location='welcome.php';"; // Comment this line if you don't want to redirect print "</script>"; } } else { session_unset(); echo "<font face='Verdana' size='2' color=red>Wrong Login. Use your correct Userid and Password and Try <br><center><input type='button' value='Retry' onClick='history.go(-1)'></center>"; } ?> </body> </html> _________________________________________________ _________________________________________________ __ your help is much appreciated Hi everybody, I want to build a script that lets someone register with a simple form that logs all activity into a MySQL db. The thing is, I want to log all attempts to signup into the system even if they do not satisfy password strength, or the required fields criteria. In the following code, the string "email" isn't being used. The field named 'name' is what I'm using to collect the email, and the field named 'msg' is what I'm using to collect the password. I've gotten to the point where if they don't provide anything for either email or password, then it directs them to the same page and it asks them to re enter their information. but I can't seem to capture the attempt (so if they enter an email but not a pass, i still want to know what email they entered). I'm getting this error Parse error: syntax error, unexpected T_ELSE in /hermes/bosweb25c/b1454/ipg.domainname/nameofsite/contact_insert2.php on line 41 Line 41 corresponds to the line with the first "else{" I'm really not sure what to do, it seems straight forward when I think it through in my head. If pass or email field is empty, enter it into the db, and then send them back to the beginning, if pass or email field not empty, continue in script. Code: [Select] <?php define('DB_NAME', 'dbname'); define('DB_USER', 'phpchick'); define('DB_PASS', 'password'); define('DB_HOST', 'localhost'); // contact to database $connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Error , check your server connection.'); mysql_select_db(DB_NAME); //Get data in local variable $v_name=$_POST['name']; $v_email=$_POST['email']; $v_msg=$_POST['msg']; // check for null values if ($v_name=="" or $v_msg=="") $query="insert into contact(name,email,msg) values('$v_name','$v_email','$v_msg')"; mysql_query($query) or die(mysql_error()); echo " <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://site.com/signup.css\"></head> <h2>Free Registration</h2> <form action=\"contact_insert2.php\" method=\"POST\" id=\"insert\"> <table> <tr> <td >Email</td> <td ><input type=\"text\" size=40 name=\"name\"></td> </tr> <tr> <td >Password</td> <td ><input type=\"password\" size=40 name=\"msg\" ></td> </tr> You must enter an email and password. <tr> <td colspan=2 id=\"sub\"><input type=\"submit\" name=\"submit\" value=\"submit\" ></td> </tr> </Table> </form>"; else{ if (strcspn($_REQUEST['msg'], '0123456789') == strlen($_REQUEST['msg'])) echo "true"; else{ $query="insert into contact(name,email,msg) values('$v_name','$v_email','$v_msg')"; mysql_query($query) or die(mysql_error()); echo "Your message has been received"; } } ?> Hello PHP mates! I am having some doubts and I am going to share them with you so maybe someone can help. Okay, I know how to make signup and login page. And here is the problem. How to make signup page for multiple types of users? For example, type A user has its own signup form, user type B also has its own and same goes for C type of user. How can I make that? Thanks in advance PHP freaks! Hi guys, i found simple php script which allow all visitors of my web site to create free email address thru my webmail service (like yahoo,hotmail,gmail,etc) and it works great, but in last month stupid bots created lots of funny user accounts and sending SPAM emails Signup script is one file (signup.php) doing all the stuff i need (registration form,lost passwords form,etc). Now i want to put captcha code into signup.php to have captcha image cheking to prevent bots from creating more user accounts ... i`m not a php programer but i know how to change some things, but not all Signup scripts is free, so i will post it here that you can help me with this (it does not have my mysql and other information,because of security issue) - i will be happy if some of you guys put all the code i need for captcha to work with signup.php script Here is the signup.php script: Code: [Select] <?php // HMailServer New user signup Script Configuration $dbhost = "localhost"; // host of the MySQL database $dbuser = "root"; // Database username $dbpassword = ""; // Your database password $dbname = "hmail"; // the name of the database that has the hmailserver tables $webmailurl = "http://www.yurdomainname.com/webmail/login.php"; // The url to login in the webbased mail system $quota = "50"; // The mailbox free space if (strlen($_POST["pas1"]) <= 4 && IsSet($_POST["pas1"])) { $error .= "<centeR>Error: Your password must be longer than 4 characters</center>"; } else if ($_POST["pas1"] == "12345" && IsSet($_POST["pas1"])) { $error .= "<centeR>Error: Too simple password</center>"; } // Get the action if (IsSet($_POST["action"])) { $action = $_POST["action"]; } else { $action = $_GET["action"]; } // A function to check addresses, probably i will have to use it later. function normalmail($visitormail) { if(!$visitormail == "" && (!strstr($visitormail,"@") || !strstr($visitormail,"."))) { return FALSE; } else { return TRUE; } } // If there is no action, open the page for a new registration if (!IsSet($action)) { // Load the domain names and their ids into a variable $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_domains WHERE domainactive = '1' ", $db); $domains = "<select name=\"domain\">"; while ($row = mysql_fetch_array($result)) { $domainid = $row['domainid']; $domainname = $row['domainname']; $domains .= "\n<option value=\"$domainid\">$domainname</option>"; } $domains .= "\n</select>"; mysql_close(); echo " <center><b>Open a new E-Mail Account</b> <p> (*) fields are reguired.<br> <form action=\"\" name=\"registration\" method=\"post\"> <table border=\"0\"> <tr> <td>* Username: <td><input type=\"text\" name=\"username\">@<td>$domains<tr> <td>* First name: <td><input type=\"text\" name=\"firstname\"><td><tr> <td>* Last name: <td><input type=\"text\" name=\"lastname\"><td><tr> <td>* Password: <td><input type=\"password\" name=\"pas1\"><Td><tr> <td>* Password again: <td><input type=\"password\" name=\"pas2\"><Td><tr> <td>Old email Address: <td><input type=\"text\" name=\"oldmail\"><td>(in case you forgot your password)<tr> <td>* Secret question: <td><input type=\"text\" name=\"squestion\"><td><tr> <td>* Secret answe <td><input type=\"text\" name=\"sanswere\"><td><tr> <td><td> <input type=\"hidden\" name=\"action\" value=\"register\"> <input type=\"Submit\" value=\"Signup\"><td><tr></td></tr></table></table> "; } else if ($action == "register") { // Load the variables from the posting $domainid = $_POST["domain"]; $username = $_POST["username"]; $pas1 = $_POST["pas1"]; $pas2 = $_POST["pas2"]; $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $squestion = $_POST["squestion"]; $sanswere = $_POST["sanswere"]; $oldmail = $_POST["oldmail"]; // Do all the checks if ($oldmail != NULL && normalmail($oldmail) == FALSE) { $error .= "Error: Please enter a valid email address\n<br>"; } if ($squestion == NULL) { $error .= "Error: You have to enter your secret question\n<br>"; } if ($sanswere == NULL) { $error .= "Error: You have to enter your secret aswere\n<br>"; } if ($username == NULL) { $error .= "Error: You have to enter your desired username\n<br>"; } if ($domainid == NULL) { $error .= "Error: You have to choose a domain\n<Br>"; } if ($pas1 == NULL) { $error .= "Error: You have to enter your password\n<Br>"; } if ($pas1 != $pas2) { $error .= "Error: Your passwords does not match\n<Br>"; } if ($firstname == NULL) { $error .= "Error: You have to enter your first name\n<Br>"; } if ($lastname == NULL) { $error .= "Error: You have to enter your last name\n<Br>"; } //Check if the user exists for that domain $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_domains WHERE domainid = '$domainid' ", $db); $result = @mysql_fetch_array($result); $address = $username . "@" . $result['domainname']; $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$address' ", $db); $result = @mysql_fetch_array($result); if ($result['accountid'] != "") { $error .= "Error: The E-Mail address $address is already registered, please coose another username or domain\n<Br>"; mysql_close(); } if (IsSet($error)) { echo "<Center>Oops, There was some errors, please submit the form again<br>"; echo $error; } else { // Insert the new user infos into the database $passwd = md5($pas1); $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $query = "INSERT INTO hm_accounts (accountaddress, accountdomainid, accountadminlevel, accountpassword, accountactive, accountisad, accountmaxsize, accountpwencryption, accountvacationmessageon, accountoldaddress, accountfirstname, accountlastname, accountsecretque, accountsecretans) VALUES ('$address','$domainid','0','$passwd','1','0','$quota','2','0','$oldmail','$firstname','$lastname','$squestion','$sanswere')"; mysql_query($query) or die("Error: Can not query to the database"); mysql_close(); echo "<center><B>Completed!</b> <br><br> You have created an email account with us! you can use the E-Mail services eather by pop3/imap or by using the webmail system. <p>Please <A href=\"$webmailurl\">Login</a> to read or to send emails <p>Thank you $firstname $lastname for joining us"; } } else if ($action == "install") { $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); mysql_query("ALTER TABLE `hm_accounts` ADD `accountoldaddress` VARCHAR(50) NOT NULL"); mysql_query("ALTER TABLE `hm_accounts` ADD `accountfirstname` VARCHAR(50) NOT NULL"); mysql_query("ALTER TABLE `hm_accounts` ADD `accountlastname` VARCHAR(50) NOT NULL"); mysql_query("ALTER TABLE `hm_accounts` ADD `accountsecretque` VARCHAR(120) NOT NULL"); mysql_query("ALTER TABLE `hm_accounts` ADD `accountsecretans` VARCHAR(120) NOT NULL"); mysql_query("ALTER TABLE `hm_accounts` ADD `accounttmpverify` VARCHAR(120) NOT NULL"); mysql_close(); Echo "The script is istalled successfuly"; } // If the user forgot his password, this is the page to recover it. else if ($action == "forgotpass") { echo "<Center><b>Welcome to the password recovery page</b> <br><br> This page will help you to recover your lost password, if you had filled the oldmail at the registration time You will be able to recover it by using the oldmail method, else you will have to use the secret question method"; echo "<br><br><center> <table border=1 cellspacing=0 cellpadding=0> <tr><td><center>Old Email Method<tr><td> <form name=\"forgot\" action=\"\" method=\"post\"> <table border=0><tr><td> Old email<td><input type=\"text\" name=\"oldemail\"><tr> <td>Your email with us in form of (username@domain.tld) <td><input type=\"text\" name=\"current\"><tr> <input type=\"hidden\" name=\"action\" value=\"fpassoldemail\"> <td><td><input type=\"submit\" value=\"Send me Recovery code\"></tr></td> </form></td></tr></table></table> <center><p> <table border=1 cellspacing=0 cellpadding=0> <tr><td><center>Secret Question Method<tr><td> <form name=\"forgot\" action=\"\" method=\"post\"> <table border=0> <tr><td>Frist name<td><input type=\"text\" name=\"firstname\"><tr> <tr><td>Last name<td><input type=\"text\" name=\"lastname\"><tr> <td>Your email with us in form of (username@domain.tld) <td><input type=\"text\" name=\"current\"><tr> <input type=\"hidden\" name=\"action\" value=\"fpassgetquestion\"> <td><td><input type=\"submit\" value=\"Submit\"></tr></td> </form></td></tr></table></table></center>"; } // if the user submited data for the secret question method, // load the variables, and do the checks else if ($action == "fpassgetquestion") { $username = $_POST["current"]; $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; if (normalmail($username) == FALSE) { $error .= "Error: Please enter a valid ID in form of email address\n<br>"; } if ($username == NULL) { $error .= "Error: You have to enter your current ID (in form of username@domain.ltd)\n<br>"; } if ($firstname == NULL) { $error .= "Error: You have to enter your first name\n<Br>"; } if ($lastname == NULL) { $error .= "Error: You have to enter your last name\n<Br>"; } if (IsSet($error)) { echo "<Center>Oops, There was some errors, please submit the form again<br>"; echo $error; //else do the rest of the checks } else { $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username' ", $db); $result = @mysql_fetch_array($result); $questi = $result['accountsecretque']; echo "<center><b>Please answere your secret question: $questi </b>"; echo "<p><form name=\"forgot\" action=\"\" method=\"post\"> <table border=0> <input type=\"hidden\" value=\"$firstname\" name=\"firstname\"> <input type=\"hidden\" value=\"$lastname\" name=\"lastname\"> <input type=\"hidden\" value=\"$questi\" name=\"squestion\"> <input type=\"hidden\" value=\"$username\" name=\"current\"> <td>Answe <td><input type=\"text\" name=\"sanswere\"><tr> <input type=\"hidden\" name=\"action\" value=\"fpassquestion\"> <td><td><input type=\"submit\" value=\"Submit\"></tr></td> </form></td></tr></table></table></center>"; } } else if ($action == "fpassquestion") { $username = $_POST["current"]; $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $squestion = $_POST["squestion"]; $sanswere = $_POST["sanswere"]; // Do all the checks if (normalmail($username) == FALSE) { $error .= "Error: Please enter a valid ID in form of email address\n<br>"; } if ($squestion == NULL) { $error .= "Error: You have to enter your secret question\n<br>"; } if ($sanswere == NULL) { $error .= "Error: You have to enter your secret aswere\n<br>"; } if ($username == NULL) { $error .= "Error: You have to enter your current ID (in form of username@domain.ltd)\n<br>"; } if ($firstname == NULL) { $error .= "Error: You have to enter your first name\n<Br>"; } if ($lastname == NULL) { $error .= "Error: You have to enter your last name\n<Br>"; } // If there was error, stop if (IsSet($error)) { echo "<Center>Oops, There was some errors, please submit the form again<br>"; echo $error; //else do the rest of the checks } else { $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username' ", $db); $result = @mysql_fetch_array($result); // check if the information does match with the stored data if ( $result['accountlastname'] == NULL || $result['accountfirstname'] == NULL || $result['accountsecretque'] == NULL || $result['accountsecretans'] == NULL) { die("Error: Cant find infos in database for $username"); mysql_close(); } if (strtolower($result['accountlastname']) == strtolower($lastname) && strtolower($result['accountfirstname']) == strtolower($firstname) && strtolower($result['accountsecretque']) == strtolower($squestion) && strtolower($result['accountsecretans']) == strtolower($sanswere)) { echo "<b><center>Your info does match, please enter a new password for $username bellow</b>"; echo "<p><br><center> <table><tr><td> <center>Change password for $username<tr><Td> <center><table> <form name=\"forgot\" action=\"\" method=\"post\"> <tr><Td>Enter new password<td><input type=\"password\" name=\"pas1\"><Tr> <Td>Verify password<td><input type=\"password\" name=\"pas2\"><Tr> <input type=\"hidden\" value=\"$firstname\" name=\"firstname\"> <input type=\"hidden\" value=\"$lastname\" name=\"lastname\"> <input type=\"hidden\" value=\"$squestion\" name=\"squestion\"> <input type=\"hidden\" value=\"$sanswere\" name=\"sanswere\"> <input type=\"hidden\" value=\"$username\" name=\"current\"> <input type=\"hidden\" value=\"forgpassquepro\" name=\"action\"> <Td><td><input type=\"submit\" value=\"Change it\"></Tr></table></table></form></center>"; } else { echo "<b><center>Your info does NOT match</b><p> Your data does not match with the stored informations of $username, please enter the exact info"; } } } else if ($action == "forgpassquepro") { $username = $_POST["current"]; $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $squestion = $_POST["squestion"]; $sanswere = $_POST["sanswere"]; $newpassword = $_POST["pas1"]; $newpassword = md5($newpassword); if (normalmail($username) == FALSE) { die("Error"); } $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username' ", $db); $result = @mysql_fetch_array($result); // check if the information does match with the stored data if ( $result['accountlastname'] == NULL || $result['accountfirstname'] == NULL || $result['accountsecretque'] == NULL || $result['accountsecretans'] == NULL) { die("Error: Cant find infos in database for $username"); mysql_close(); } if ($_POST["pas1"] != $_POST["pas2"]) { $error = "<center><B>Your passwords does not match, please submit the form again</b></centeR>"; } if ($error != NULL) { echo $error; } else { if (strtolower($result['accountlastname']) == strtolower($lastname) && strtolower($result['accountfirstname']) == strtolower($firstname) && strtolower($result['accountsecretque']) == strtolower($squestion) && strtolower($result['accountsecretans']) == strtolower($sanswere)) { $accountid = $result['accountid']; //ok change the password $query = "UPDATE hm_accounts SET accountpassword = '$newpassword' WHERE accountid = '$accountid'"; mysql_query($query); echo "<center><b>Ok Your password has changed, sign in now with your new password, and your ID $username</b></center>"; mysql_close(); } } } // forgot password, old email method. else if ($action == "fpassoldemail") { $username = $_POST["current"]; $oldmail = $_POST["oldemail"]; // Do all the checks if (normalmail($username) == FALSE) { $error .= "Error: Please enter a valid ID in form of email address\n<br>"; } if (normalmail($oldmail) == FALSE) { $error .= "Error: Please enter a valid email address\n<br>"; } $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username'", $db); $result = @mysql_fetch_array($result); $accountid = $result['accountid']; if ($result['accountoldaddress'] == NULL) { $error .= "Error: Missing infos in the database for $username <Br>"; } if ($result['accountoldaddress'] != $oldmail) { $error .= "Error: The address $oldmail does not match with the old address of $username <Br>"; } if ($error != NULL) { echo "<Center>Oops, There was some errors, please submit the form again<br>"; echo $error; mysql_close(); } else { // in that case somehow we have to generate a random code for($x=0;$x<10;$x++) { $y = rand(0,61); $z .= $y + (($y<10) ? 48 : (($y<20) ? 21 : 10)); } $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $query = "UPDATE hm_accounts SET accounttmpverify = '$z' WHERE accountid = '$accountid'"; mysql_query($query); mysql_close(); $body = " The user account $username has this email associated with it. A Web user from " . $_SERVER['REMOTE_ADDR'] . " has just requested a Confirmation Code to change the password. Your Confirmation Code is: $z With this code you can now assign a new password at http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . "?action=fpassconfirm&addr=$username&code=$z If you cant click in the link, copy paste the URL into your browser. If you didn't asked for this, don't worry. Just delete this Email."; $body = wordwrap($body, 70); $subject = "Lost password: confirmation code"; $headers=""; $headers = 'From: ' . $username; if (mail($oldmail, $subject, $body, $headers)) { echo "<b>Message successfully sent!</b> <p>Please read the email in your old address $oldmail to get the verification code and reset your password <p>Your IP address is loged for security reasons."; } else { echo "<b>Message delivery failed!</b>"; } } } else if ($action == "fpassconfirm") { $code = $_POST["code"]; $username = $_POST["addr"]; if (!IsSet($code)) { $code = $_GET["code"]; } if (!IsSet($username)) { $username = $_GET["addr"]; } $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username' ", $db); $result = @mysql_fetch_array($result); if ($username == NULL || normalmail($username) == FALSE) { $error .= "Error: Please enter your E-mail address in the correct form<Br>"; } if ($code == NULL) { $error .= "Error: Please enter the confirmation code<br>"; } if ($result['accounttmpverify'] != $code) { $error .= "Error: You entered an invalid confirmation code. <Br>"; } if ($error != NULL) { echo "<Center>Oops, There was some errors, please submit the form again<br>"; echo $error; echo "<br><br> <form name=\"forgot\" action=\"\" method=\"post\"> <center> <table><tr> <Td>E-Mail address<td><input name=\"addr\" type=\"text\"> <tr><td>Code<td><input name=\"code\" type=\"text\"><tr> <input type=\"hidden\" value=\"fpassconfirm\" name=\"action\"> <td><td><input type=\"submit\" value=\"Submit\"></tr> </td></table></table></form></centeR> "; mysql_close(); } else { echo "<b><center>Confirmation code is valid, Please enter your new password bellow</b>"; echo "<p><br> <center><table><tr><Td> Change password for $username<tr><Td> <table><tr> <form name=\"forgot\" action=\"\" method=\"post\"> <Td>Enter new password<td><input type=\"password\" name=\"pas1\"> <Tr><Td>Verify password<td><input type=\"password\" name=\"pas2\"><Tr> <input type=\"hidden\" value=\"$code\" name=\"code\"> <input type=\"hidden\" value=\"$username\" name=\"addr\"> <input type=\"hidden\" value=\"forgpasscodepro\" name=\"action\"> <Td><td><input type=\"submit\" value=\"Change it\"></Tr></table></table></form>"; mysql_close(); } } // ok lets check the code again, and change the password. else if ($action = "forgpasscodepro") { $code = $_POST["code"]; $username = $_POST["addr"]; $newpassword = $_POST["pas1"]; $newpassword = md5($newpassword); $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbname); $result = mysql_query("SELECT * FROM hm_accounts WHERE accountaddress = '$username' ", $db); $result = @mysql_fetch_array($result); $accountid = $result['accountid']; if ($username == NULL || normalmail($username) == FALSE) { $error .= "Error: Please enter your E-mail address in the correct form<Br>"; } if ($code == NULL) { $error .= "Error: Please enter the confirmation code<br>"; } if ($result['accounttmpverify'] != $code) { $error .= "Error: You entered an invalid confirmation code. <Br>"; } if ($_POST["pas1"] != $_POST["pas2"]) { $error .= "Error: Passwords does not match. <Br>"; } if ($error != NULL) { echo $error; } else { $query = "UPDATE hm_accounts SET accountpassword = '$newpassword' WHERE accountid = '$accountid'"; mysql_query($query); echo "<b>Your password has changed!</B><br><br> now you can sign in with your new password and your ID $username"; mysql_close(); } } echo "<center><p><em><font size=\"2\">Powered by <a target=\"hmail\" href=\"http://www.hmailserver.com\">HMailServer</a> @ All rights reserved</em></font></centeR>"; ?> Tnx Hi, I have a fully pledged membership system and want to integrate my own user referral system but want some tips, advice really on the logic of it. Basically already registered users on my site will have the option to refer people, only registered users. I will try to explain my logic and what i have done so far. My current registered users table is something like Quote users (table) - id (user id) - email (user email) - password (hash of users password) - reg_date (date user registered) I have some other fields but not relevant to what I want to do and to keep things as simple as possible I left them out. I am thinking of creating a new table called referrals and for example when a registered user on my site from the users table goes to a member only page called referral.php it will display a form so they can enter an email address of someone they want to refer and it also displays the people they referred. My referral table is like this so far and not sure if it's best way to go about the database logics and php logic. my table so far looks like this: Quote referrals (table) - id (auto incremented every time a new referral (row) is added to referrals table) - referrer_uid (id of referrer, this would be the unique id of a registered user from the users table) - referred_email (email address of person who has been referred) - status (when someone is first referred default will be `referred`, if they signup to site via referral link this will update to `completed`) - created_on (date the referral was made, unix timestamp) - updated_on (date the referred person actually clicks the referral link and completes signup) Currently i added the database table above to my site on local. added some sample data for testing and created a referral.php page where there's a form so a registered member can enter a persons email and refer them to my site to signup. On referral.php there is also the total people they referred and a table showing all the people they referred as follows: Referred Email | Referred Date | Status | Completed On Now so far everything is seems fine. I have my sample (pretend referrals i made) data showing in my test account. The part i am now not sure about is this: Obviously to stop abuse i do my usual validation checks like: check to ensure the email being entered on referrals page does not exist in users table (registered member), check to ensure the email has not already been referred previously (for spam reasons) only allowed to refer an email address once and not allowed to refer someone who has previously been referred by someone else to (again for spam reasons) Now onto the tracking the referral and link building. I was first thinking this: on sign up form have a hidden field. The sign up form would do a simple check to see if isset $_GET['ref'] like signup.php?ref=something_here if it is prefill the hidden field, when user then signs up if the ref=something_here matches what's in the database then update referral to complete so the referrer knows that their friend for example signed up via their referral, unix timestamp of when referred person completed signup. Now i was going to use the email address of referred person or username of person who made the referral signup.php?ref=username or signup.php?ref=referred_email . Now what i am thinking is what would be better and i guess stop random abuse is create another column and call it referred_id; this would be a random md5 hash that is unique to that referral and it will be appended to the url like signup.php?ref=md5_hash_here. So my questions a 1) Is there anything you think i should change, improve on, alter etc ? 2) Do you think i am going about it the rite way or making a mess of it ? 3) Have i left anything out that i may have not thought of that could cause the system to be abused ? Any suggestions, feedback, help on the whole logic would be great. I coded allot of it last night and won't take me long to do the rest but need some help in terms of ensuring i am doing it the best way possible etc, the logic behind it all. Thanks for any suggestions, help, advice, tips! PHPFAN Hi there,
I'm fairly new to PHP and I'm self teaching.
I'm sure this will be out there somewhere but I can't for the life of me think of the terminology to search the net and find the solution.
I'm creating a Task Manager;
Each task can be assigned to many users at once.
I'm creating a text field in the task field, this text field will include user ids separated by commas.
I believe I can explode this data to handle each id.
However how can I build a php script that will show the user all the task assigned too them.
If it did a search LIKE in the text field. The id could be confused with others.
If someone knows the solutions I would be very greatful.
thanks for reading
I have created a button which when pressed should present the user with their details (whoever is logged in), here is the form code: <form id="form1" name="form1" method="post" action="getdetails.php"> <input type="submit" name="Get Details" value="Get Details" /> </label> </p> </form> Here is the getdetails.php file <?php mysql_connect("localhost","root",""); mysql_select_db("test"); $username = $_POST['textfield']; echo '</br>'; $query = mysql_query("SELECT * FROM membersdetails WHERE name=`$username` "); while($result = mysql_fetch_array($query)) { //display echo $result['firstname']; echo $result['surname']; } ?> Its not workin at all I have attacthed the error i am getting Any help please? In ubuntu 19.04 with php version 7.2 , i want to add mysql user with php when i run the code below get the error: SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost' I didn't set any password for root , this is php code: <?php $server = "localhost"; $dbuser = "root"; $dbpassword = ""; try { $connection = new PDO("mysql:host=$server", $dbuser, $dbpassword); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $user = 'test' . '@' . 'localhost'; $sqlQuery = "CREATE USER . $user . "; $connection->exec($sqlQuery); echo "User created successfully!"; } catch(PDOException $e){ echo $sqlQuery . "<br>" . $e->getMessage(); } $connection = null; ?>
I have a family site with a member list and a forum that both run on MySql. One of the items in the member list is the birthday. What I like to achieve is that a day or 2 before a member's birthday, a post wil be automaticly inserted in the forum, (a post that contains that this persons birthday is comming up in a few days) without any user input. I like to have this done automaticly because I don't feel like setting up a cron job for every member seperatly. There are just too many members. What I need is a script that will create a cron job or something simular the moment a new member registers and updates his profile and sets his birthday. I have members.php: <?php /********************************************************************** Filename: members.php Version: $Id: members.php 17 2007-04-09 09:40:35Z Jez $ Description: This file displays the members screen once they've logged in. **********************************************************************/ /* Members script: */ include_once("config.php"); // Check user logged in already: checkLoggedIn("yes"); doCSS(); print("Welcome to the members page <b>".$_SESSION["login"]."</b><br>\n"); print("Your password is: <b>".$_SESSION["password"]."</b><br>\n"); print("<a href=\"logout.php"."\">Logout</a>"); ?> and functions.php: <?php /********************************************************************** Filename: functions.php Description: This file contains main stock of functions. This file is automatically 'include()'d by every page that include()'s the file 'config.php'. This has the benefit that every page that includes 'config.php' will have access to all of the functions in this file. **********************************************************************/ /******************************************************\ * Function Name : connectToDB() * * Task : create connection to db * * Arguments : none * * Globals: all defined in config.php * * Returns : none, sets $link * \******************************************************/ function connectToDB() { global $link, $dbhost, $dbuser, $dbpass, $dbname; /* Database connection: The PHP function mysql_pconnect() connects to a MySQL database with the arguments it is given. mysql_pconnect() creates a persistent database connection which can save some time when a number of mysql connections are made to the same db with the same user/password/dbhost triple. Further, when the execution of the PHP script ends, the connection to the database is NOT closed. In some rare cases this can cause problems. Alternatively mysql_connect() can be used and takes the same arguments as mysql_pconnect(). However mysql_connect() does not maintain a persistent connection - every call to mysql_connect() creates a new db connection. On a busy server this can significantly increase the amount of time taken to execute queries on the db. */ ($link = mysql_pconnect("$dbhost", "$dbuser", "$dbpass")) || die("Couldn't connect to MySQL"); // select db: mysql_select_db("$dbname", $link) || die("Couldn't open db: $dbname. Error if any was: ".mysql_error() ); } // end func dbConnect(); /******************************************************\ * Function Name : newUser($login, $pass) * * Task : Create a new user entry in the users table based on args passed * * Arguments : string($login, $pass) * * Returns : int($id), $id of new user * \******************************************************/ function newUser($login, $password) { /* Creating a New User Record in the DB: In this function we create a new user record in the db. We first build a query and save it into the $query variable. The query statement says: 'Insert the value of $login and $password into the 'login' and 'password' columns in the 'users' table' */ global $link; $query="INSERT INTO users (login, password) VALUES('$login', '$password')"; $result=mysql_query($query, $link) or die("Died inserting login info into db. Error returned if any: ".mysql_error()); return true; } // end func newUser($login, $pass) /******************************************************\ * Function Name : displayErrors($messages) * * Task : display a list of errors * * Arguments : array $messages * * Returns : none * \******************************************************/ function displayErrors($messages) { /* Error Handling functions: An error handling function is useful to have in any project. This particular function takes an array of messages, and for each message displays it in a list using HTML <ul><li></li></ul> tags. */ print("<b>There were problems with the previous action. Following is a list of the error messages generated:</b>\n<ul>\n"); foreach($messages as $msg){ print("<li>$msg</li>\n"); } print("</ul>\n"); } // end func displayErrors($messages) /******************************************************\ * Function Name : checkLoggedIn($status) * * Task : check if a user is (isn't) logged in depending on $status * * Arguments : quasi(!) boolean $status - "yes" or "no" * * Returns : * \******************************************************/ function checkLoggedIn($status){ /* Function to check whether a user is logged in or not: This is a function that checks if a user is already logged in or not, depending on the value of $status which is passed in as an argument. If $status is 'yes', we check if the user is already logged in; If $status is 'no', we check if the user is NOT already logged in. */ switch($status){ // if yes, check user is logged in: // ie for actions where, yes, user must be logged in(!) case "yes": if(!isset($_SESSION["loggedIn"])){ header("Location: login.php"); exit; } break; // if no, check NOT logged in: // ie for actions where user can't already be logged in // (ie for joining up or logging in) case "no": /* The '===' operator differs slightly from the '==' equality operator. $a === $b if and only if $a is equal to $b AND $a is the same variable type as $b. for example, if: $a="2"; <-- $a is a string here $b=2; <-- $b is an integer here then this test returns false: if($a===$b) whereas this test returns true: if($a==$b) */ if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] === true ){ header("Location: members.php"); } break; } // if got here, all ok, return true: return true; } // end func checkLoggedIn($status) /******************************************************\ * Function Name : checkPass($login, $password) * * Task : check login/passwd match that stored in db * * Arguments : string($login, $password); * * Returns : array $row - array of member details on success * false on failure \******************************************************/ function checkPass($login, $password) { /* Password checking function: This is a simple function that takes the $login name and $password that a user submits in a form and checks that a row exists in the database whe the value of the 'login' column is the same as the value in $login and the value of the 'password' column is the same as the value in $password If exactly one row is returned, then that row of data is returned. If no row is found, the function returns 'false'. */ global $link; $query="SELECT login, password FROM users WHERE login='$login' and password='$password'"; $result=mysql_query($query, $link) or die("checkPass fatal error: ".mysql_error()); // Check exactly one row is found: if(mysql_num_rows($result)==1) { $row=mysql_fetch_array($result); return $row; } //Bad Login: return false; } // end func checkPass($login, $password) /******************************************************\ * Function Name : cleanMemberSession($login, $pass) * * Task : populate a session variable * * Arguments : string $login, string $pass taken from users table in db. * * Returns : none * \******************************************************/ function cleanMemberSession($login, $password) { /* Member session initialization function: This function initializes 3 session variables: $login, $password and $loggedIn. $login and $password are used on member pages (where you could allow the user to change their password for example). $loggedIn is a simple boolean variable which indicates whether or not the user is currently logged in. */ $_SESSION["login"]=$login; $_SESSION["password"]=$password; $_SESSION["loggedIn"]=true; } // end func cleanMemberSession($login, $pass) /******************************************************\ * Function Name : flushMemberSession($session) * * Task : unset session variables and destroy session * * Arguments : array $session * * Returns : true * \******************************************************/ function flushMemberSession() { /* Member session destruction function: This function unsets all the session variables initialized above and then destroys the current session. */ // use unset to destroy the session variables unset($_SESSION["login"]); unset($_SESSION["password"]); unset($_SESSION["loggedIn"]); // and use session_destroy to destroy all data associated // with current session: session_destroy(); return true; } // send func flushMemberSession() /******************************************************\ * Function Name : doCSS() * * Task : output the CSS for the screens * * Arguments : * * Returns : * \******************************************************/ function doCSS() { /* CSS Output: This function simply outputs some cascading style sheet data for markup by the user's browser. */ ?> <style type="text/css"> body{font-family: Arial, Helvetica; font-size: 10pt} h1{font-size: 12pt} </style> <?php } // end func doCSS() # function validates HTML form field data passed to it: function field_validator($field_descr, $field_data, $field_type, $min_length="", $max_length="", $field_required=1) { /* Field validator: This is a handy function for validating the data passed to us from a user's <form> fields. Using this function we can check a certain type of data was passed to us (email, digit, number, etc) and that the data was of a certain length. */ # array for storing error messages global $messages; # first, if no data and field is not required, just return now: if(!$field_data && !$field_required){ return; } # initialize a flag variable - used to flag whether data is valid or not $field_ok=false; # this is the regexp for email validation: $email_regexp="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|"; $email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; # a hash array of "types of data" pointing to "regexps" used to validate the data: $data_types=array( "email"=>$email_regexp, "digit"=>"^[0-9]$", "number"=>"^[0-9]+$", "alpha"=>"^[a-zA-Z]+$", "alpha_space"=>"^[a-zA-Z ]+$", "alphanumeric"=>"^[a-zA-Z0-9]+$", "alphanumeric_space"=>"^[a-zA-Z0-9 ]+$", "string"=>"" ); # check for required fields if ($field_required && empty($field_data)) { $messages[] = "$field_descr is a required field."; return; } # if field type is a string, no need to check regexp: if ($field_type == "string") { $field_ok = true; } else { # Check the field data against the regexp pattern: $field_ok = ereg($data_types[$field_type], $field_data); } # if field data is bad, add message: if (!$field_ok) { $messages[] = "Please enter a valid $field_descr."; return; } # field data min length checking: if ($field_ok && ($min_length > 0)) { if (strlen($field_data) < $min_length) { $messages[] = "$field_descr is invalid, it should be at least $min_length character(s)."; return; } } # field data max length checking: if ($field_ok && ($max_length > 0)) { if (strlen($field_data) > $max_length) { $messages[] = "$field_descr is invalid, it should be less than $max_length characters."; return; } } } ?> The db has an table users with id, login, password, site Question how can i get inf from "site" raw for logged user on members.php ( as a link). Pls help thanks I've started a to-do app, and everything works fine. Every user has his own unique to-do items that he can add. The only issue is that when I log-in with a user, ALL the items of all users are displayed when I'm redirect to my main page. I want to make it as so every user has his own page where only the to-do items he has created are visible, not every item from every user. I'm a total beginner with PHP so I'm sorry if this is a stupid question. This is my todomain.php code <?php require 'db_conn.php'; require 'config.php'; session_start(); // If the session variable is empty, this // means the user is yet to login // User will be sent to 'login.php' page // to allow the user to login if (!isset($_SESSION['id'])) { $_SESSION['msg'] = "You have to log in first"; header('location: login.php'); } // Logout button will destroy the session, and // will unset the session variables // User will be headed to 'login.php' // after loggin out if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['id']); header("location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset= "UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="css/bootstrap-grid.min.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <a href="index.php?logout='1'" style="color: black;"> Click here to Logout </a> <?php if (isset($_SESSION['success'])) : ?> <div class="error success" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); echo $_SESSION["username"] ?> </h3> </div> <?php endif ?> <title>TODO App</title> <script src="https://kit.fontawesome.com/d72928d9b9.js" crossorigin="anonymous"></script> </head> <body> <div class="container m-5 p-2 rounded mx-auto bg-light shadow"> <!-- App title section --> <div class="row m-1 p-4"> <div class="col"> <div class="p-1 h1 text-primary text-center mx-auto display-inline-block"> <i class="fa fa-check bg-primary text-white rounded p-2"></i> <u>My Todo-s</u> </div> </div> </div> <!-- Create todo section --> <form action="app/add.php" method="POST" autocomplete="off"> <div class="row m-1 p-3"> <div class="col col-11 mx-auto"> <div class="row bg-white rounded shadow-sm p-2 add-todo-wrapper align-items-center justify-content-center"> <div class="col"> <input class="form-control form-control-lg border-0 add-todo-input bg-transparent rounded" type="text" name="title" placeholder="Add new .."> </div> <div class="col-auto m-0 px-2 d-flex align-items-center"> <label class="text-secondary my-2 p-0 px-1 view-opt-label due-date-label d-none">Due date not set</label> <i class="fa fa-calendar my-2 px-1 text-primary btn due-date-button" data-toggle="tooltip" data-placement="bottom" title="Set a Due date"></i> <i class="fa fa-calendar-times-o my-2 px-1 text-danger btn clear-due-date-button d-none" data-toggle="tooltip" data-placement="bottom" title="Clear Due date"></i> </div> <div class="col-auto px-0 mx-0 mr-2"> <button type="submit" class="btn btn-primary">Add</button> </div> </div> </div> </div> </form> <?php $todos=$conn->query("SELECT * FROM todos ORDER BY id ASC"); ?> <div class="row mx-1 px-5 pb-3 w-80"> <div class="col mx-auto"> <?php while($todo=$todos->fetch(PDO::FETCH_ASSOC)){ ?> <!-- Todo Item 1 --> <div class="row px-3 align-items-center todo-item rounded"> <?php if($todo['checked']){ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>" checked /> <h2 class="checked"><?php echo $todo['title'] ?> </h2> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> </div> </div> <?php } else{ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>"/> <h2><?php echo $todo['title'] ?></h2> <?php } ?> <div class="col-auto m-1 p-0 d-flex align-items-center"> <h2 class="m-0 p-0"> <i class="fa fa-square-o text-primary btn m-0 p-0 d-none" data-toggle="tooltip" data-placement="bottom" title="Mark as complete"></i> </h2> </div> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> <h5 class="m-0 p-0 px-2"> <i class="fa fa-pencil text-info btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Edit todo"></i> </h5> <h5 class="m-0 p-0 px-2"> <i class="remove-to-do fa fa-trash-o text-danger btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Delete todo" id="<?php echo $todo['id']; ?>"></i> </h5> </div> <div class="row todo-created-info"> <div class="col-auto d-flex align-items-center pr-2"> <i class="fa fa-info-circle my-2 px-2 text-black-50 btn" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Created date"></i> <label class="date-label my-2 text-black-50"><?php echo $todo['date_time'] ?></label> </div> </div> </div> </div> <?php } ?> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js"></script> <script src="js/myjs.js" ></script> <script src="js/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $(".remove-to-do").click(function(e){ const id = $(this).attr('id'); $.post('app/remove.php', { id: id }, (data) => { if(data){ $(this).parent().parent().parent().parent().hide(300); } } ); }); $(".check-box").click(function(e){ const id = $(this).attr('data-todo-id'); $.post('app/checking.php', { id: id }, (data) => { if(data!='error'){ const h2= $(this).next(); if(data === '1'){ h2.removeClass('checked'); }else{ h2.addclass('checked'); } } } ); }); }); </script> </body> </html>
|