Jump to content

Search the Community

Showing results for tags 'login'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hello, im a new user here. Im now working on a project called student attendance management sytem. I have doing all the necessary tables in database which is admin, lecturer, student, parent, attendance and grade. Ok so im now working on a 1st page which is a login page. Right now i have finished the coding and what im gonna ask u all is how to make sure that when i clicked 'login', it not only detect the admin table but all of other tables? <html> <head> <title> Login Form </title> </head> <body> <form method='post' action='login.php'> <table width='400' border='5' align='center'> <tr> <td align='center' colspan='5'><h1>Login Form</h1></td> </tr> <tr> <td align='center'>Username:</td> <td><input type='text' name='username' /></td> </tr> <tr> <td align='center'>Password:</td> <td><input type='password' name='pass' /></td> </tr> <tr> <td colspan='5' align='center'><input type='submit' name='login' value='Log In' /></td> </tr> </table> </form> </body> </html> <?php mysql_connect("localhost","root",""); mysql_select_db("student_attendance"); if(isset($_POST['login'])){ $username = $_POST['username']; $password = $_POST['pass']; $check_user = "select * from admin where username='$username' AND pass='$password'"; $run = mysql_query($check_user); if(mysql_num_rows($run)>0){ echo "<script>alert('You are logged in')</script>"; } else { echo "<script>alert('username or password is incorrect!')</script>"; } } ?>
  2. This problem is for real PHP freaks. I do not post in forums unless I really can't find a solution. I have been bugged by this for days now. Here it is. I have a page signup.php among other pages on the website. Once you logout from logout.php all session is destroyed and all cookies are deleted. you can visit the website as a visitor after logging out. I visited all pages to make sure I was really logged out. Everything is normal up till here. However, when I click on signup again which call signup.php, the old session becomes suddenly alive and you are logged in again as if you had never logged out. I have never faced this problem before and I have made many websites using PHP. I have tested and found that session is already there when the page loads and values are not formed by any variable or function manipulation. I am using hostgator shared hosting. Please guyz help me out. I am not sure what I am doing wrong here.
  3. I need to create a main portal/front page that allows user to login into the main page. Then from there they can login into other system automatically. All the other system are in php but might be using different frameworks. I'm sure whether I conveyed what I needed, but an example is like Google, I set Google Search as my main page. When I sign in to the page, from there I can go into GMail, GPlus, Youtube, Maps etc without signing in again So basically I need a system/portal where I can 1) manage user logins 2) single login/authentication to other system module (something like Google) 3) have basic functions like a notice board and form submissions 4) and of cource in PHP I'm currently looking at Joomla (first time exploring it), but I'm not sure whether this or other CMS can handle this. Or maybe not CMS but other kind of system for this kind of need.
  4. I need to create a main portal/front page that allows user to login into the main page. Then from there they can login into other system automatically. All the other system are in php but might be using different frameworks. I'm sure whether I conveyed what I needed, but an example is like Google, I set Google Search as my main page. When I sign in to the page, from there I can go into GMail, GPlus, Youtube, Maps etc without signing in again So basically I need a system/portal where I can 1) manage user logins 2) single login/authentication to other system module (something like Google) 3) have basic functions like a notice board and form submissions 4) and of cource in PHP I'm currently looking at Joomla (first time exploring it), but I'm not sure whether this or other CMS can handle this. Or maybe not CMS but other kind of system for this kind of need.
  5. Hi There, I am trying to make a login system with PHP and I have made one but I can't see the problem, it just keeps taking me back to login.php. All files involved attached. Many Thanks for Your Help in Advance. includes.zip
  6. this expire system wont work.. whats wrong with it? When you login: (login page) <?php session_start(); $_SESSION['start'] = time(); $_SESSION['expire'] = $_SESSION['start'] + (3600); ?> The page you goto after you login: (logged in page) <?php session_start(); $now = time(); if($now > $_SESSION['expire']) { session_destroy(); echo "session expired!"; } else { echo $myusername; } ?> When im at the logged in page, and i refresh it just says "session expired!"
  7. I'm trying to create a login script but I can't figure out how to pull the data out of a $_COOKIE and how cookies work with $_SESSION. Basically I have this //pull data from database $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; //store in the database strip for sql injection $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); //query database, check to see if username and password exist there / encrypt $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password=SHA('$mypassword')"; $result=mysql_query($sql); $count=mysql_num_rows($result); //if it exists, register the session with the username nad password, then set a cookie if($count==1) { $_SESSION("myusername"); $_SESSION("mypassword"); setcookie("username","$myusername",0); header("location:cookietest.php"); } else { echo "Wrong Username or Password"; } Then inside my cookietest.php.. if(isset($_SESSION['username'])) echo "session varible set and "; else echo "session varibale not set and "; if(isset($_COOKIE['username'])) echo "cookie is set"; else echo "cookie is not set"; Even thogh I can see int he browser that the cookie was created I get "session varible not set and cookie is not set"
  8. I keep running into this problem on a few of my scripts now. I am putting together a signup and login form. (i know basic stuff). I have managed to create the signup and it is inserting and displaying information from my database and table. I can successfully connect as well. The warning that I am getting is : Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/content/80/11355280/html/login.php on line 30 Line 30 is BOLD mysql_connect("$host", "$username", "$password");mysql_select_db("$db_name"); $wcdname=mysql_real_escape_string($_POST['wcdname']); $pword=mysql_real_escape_string($_POST['pword']); $sql="SELECT * FROM $tbl_name WHERE username='$wcdname' and password='$pword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("wcdname"); session_register("pword"); (line 30) header("location:login_complete.html"); } else { echo "Wrong Username or Password"; } ?> If I change anything on line 30 It gives me the same warning but jumps back to line 26. It is displaying the ELSE echo for Wrong Username and Password. However the username and password is correct. I am having the same problem on a few other scripts I am trying. I have also had a problem with the way I was connecting. Im not sure if its best to define the variables or to just make a connection without them. I dont know if that could be the reason I am getting an error as well. I am registered through godaddy. Thank you if you can help me, sorry for being a noob.
  9. i get ''password doesn't match.'' when i register me on my site This is the PHP code: <?php mysql_connect("localhost", "root", "kingk980327rr") or die(mysql_error()); mysql_select_db("php") or die(mysql_error()); if(isset($_POST['login'])){ if(empty($_POST['username']) or empty($_POST['password'])){ echo "Fields cannot be left empty"; }else{ $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string(sha1($_POST['password'])); $valid = mysql_query("SELECT * From users WHERE username='".$username."' and password='".$password."'"); if(mysql_num_rows($valid) == 1){ mysql_query("UPDATE Users SET online='1' WHERE username='".$username."'"); header("location: me.php"); }else{ echo "Password / username isn't correct."; } } } ?> <?php if(isset($_POST['register'])){ if(empty($_POST['rusername']) or empty($_POST['rpassword']) or empty($_POST['crpassword'])){ echo "Fields cannot be empty"; }else{ $do = mysql_query("SELECT * From users WHERE username='".mysql_real_escape_string($_POST['rusername'])."'"); if(mysql_num_rows($do) == 1){ echo "Users busy."; }else{ $rusername = mysql_real_escape_string($_POST['rusername']); $password = mysql_real_escape_string(sha1($_POST['rpassword'])); $rpassword = $_POST['rpassword']; if($password == $rpassword){ mysql_query("INSET INTO users (username, password) VALUES ('$rusername','$rpassword')"); echo "Account created."; }else{ echo "password doesn't match."; } } } } ?> and this is the html register form: <form method="post"> Användarnamn:<input type="text" placeholder="Ditt användarnamn" class="mywidth1" name="rusername"><br /> Lösenord:<input type="password" placeholder="Ditt lösenord" class="mywidth2" name="rpassword"><br /> Verifiera lösenord: <input type="password" placeholder="Skriv lösenordet igen" class="mywidth" name="crpassword"><br /> <input type="submit" class="regbutton" value="" name="register"> </form> And this is the HTML login form: <form method="post"> Användarnamn: <input type="text" placeholder="Namn" class="loginde" name="username"><br /> Lösenord: <input type="password" placeholder="Lösenord" class="loginde1" name="password"><br /> <input type="submit" class="login" value="" name="login"> </form><br /><br /> Hope someone can help me :/
  10. I am trying to login to the website in the below example. This script logs in using a username and password but then is directed to a page with a security question. This is where the problem is, I am unable to POST my answer on this page. The result of my output is just the page with the security question. $username = 'XXXX'; $password = 'XXXX'; $loginUrl = 'https://www.dandh.ca/v4/dh'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $loginUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, 'Login='.urlencode($username).'&PW='.urlencode($password).'&Request=Login&formName=Login&jsEnabled=0&queryString=&Platform=Full&btLogin='.urlencode('Log In')); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies.txt"); curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); // process main login curl_setopt($ch, CURLOPT_POSTFIELDS, 'securityAnswer=XXXX&Request=postForm&formName=loginChallengeValidation&btContinue=Continue'); echo curl_exec($ch); // process security question curl_close($ch); Here is the source code of the security question HTML form: <form name="securityForm" id="secForm" method="post" action="/v4/dh"> <input type="hidden" name="Request" value="postForm"><input type="hidden" name="formName" value="loginChallengeValidation"> <table border="0" align="center" cellpadding="10" cellspacing="0"> <tr> <td><span style="font-weight:bold;">Security Response</span> <br> <p> Please answer the following security question. Once the answer is confirmed you can continue. </p> <p style="margin-left: 20px;"> Question: What is the name of your best friend from childhood?</p> <p style="margin-left: 20px;"> Answer: <input type="text" id="securityAnswer" name="securityAnswer" size="50" maxlength="50"> </p> <p style="margin-left: 20px;"> <input type="submit" name="btContinue" value="Continue"> </p> <p> <i>If you do not know the answer to the security question, please email <a href="mailto:passwords@dandh.com">passwords@dandh.com</a> and they will send you a temporary password. <a href="/v4/dh?Request=postForm&formName=LogOut">Click here</a> to return to login page.</i> </p> </td> </tr> </table> </form>
  11. I would like to be able to login to facebook without being there so I can post to facebook from rss files and a database. I can retrieve the access token using curl and I can see the feed. I want to able to post messages using either the api or better still using curl
  12. Hi guys, I am back with another login twister. Earlier i tried to create a yahoo like login system which ensured that a given user was logged in only on one machine even if that user tried to do a multiple login from same or different machines. So after a great deal of effort and with a lot of support from the forum i decided it would be best to not allow a second , the new login, at all if the user was logged in. So the new login fails saying that the user is already logged in. I am now using a sliding jquery login panel that i picked up from the net and i tried and implement this new logic and guess what ? I ran into another issue. So the panel works fine. I'll put the login procedure in steps; 1. I input the username and password and I login. The initial screen provides the username and password and a login button. Also a registration form for a new login registration. The display shows Guest for user. 2. The user logs in & is greeted by his 'username' that it picks from a database. When the panel is expanded it now opens to a new page ( say PAGE 1) which has two hyperlinks: a) to play a movie and b) to logout. 3. Both work fine. So far so good. 4. Now I run the login page again in a new tab and because an instance of it is already running, it opens on PAGE 1 which has the two hyperlinks a) movie and b) to logout. Since the panel is running sessions and since i am running the two on the two tabs of a browser, the sessions would ensure that the session values are the same for the instances in both tabs. 5. Now I logout from the 2nd (newer) tab. ( actually since there are two instances running on the two tabs of the same browser I can logout of either.) The sessions is destroyed and the logout page is displayed. Since the sessions are destroyed, they must be destroyed from both instances. At this point of time the first instance / tab is still showing the PAGE1 as it should but it is now a dead session. However now when i press the a) option, the hyperlink to a movie, it plays !!!!! WHY should the movie play when the session is destroyed. 6. So in effect, while i am effectively logged out because of a logout command in one of the two tabs of the browser, the hyperlink to the movie in the other tab is still active. which is a great flaw i think. I mean it should not behave like that. So does anyone have any idea why this is happening and how it may be over come?? A bit of code showing that which makes the PAGE 1 <div class="left"> <h1>Members panel</h1> <p>You can put member-only data here</p> <a href="registered.php">View a special member page</a> <p>- or -</p> <a href="?logoff">Log off</a> </div> registered.php actually runs a movie - the a) option - or the user can logoff - the b) option Please HELP, stuck on this one again.
  13. Hello, I am brand new to this forum so I am not sure if I am posting in the right place but I will give it a shot: I have been making PHP Classes for a while and thinking about giving away/selling them. I currently have a Flat file database Class that allows you to turn a text file into a table within a database. The queries are easy for example: select('FROM users WHERE username=hello');. This Flatfile Database contains many of the same functions as mysql. I decided to make this as i see mysql is being discontinued in the next version of PHP. Another class i have created is a login class. Setup is easy of course, all you have to do it simply include the main file(all in a folder called Login) and then wherever you want it simple past this code: new gLogin();. TADA you have a login. Please post any questions, concerns, or requests for new classes. Thank you, gamble
  14. Hello, okay, so I need some help, before i start i must warn you that i'm not very good at explaining. Using a WYSIWYG Web Builder i have built a website with a membership system. Now when i make an account with the membership system, and enter the password 'htmlforums' it will show '2810bd8735116c769d9d4f6d6b53c3e1' in my mySQL database. Now I have also downloaded a forum script and have linked the two to the same database. The only problem is that the user password is different and therefore both don't work with one user. If make an account with the same password using the forums script it will show '2a9e532f806c272ecb01d58c503bc9a96f7b3ad8' in my mySQL database under passowrd. So both use a different system to login, but if i manually change the password's in the database (swap them) they will work, (as in with password one (2810bd8735116c769d9d4f6d6b53c3e1), i can sign in to the site and if i change it password 2 (2a9e532f806c272ecb01d58c503bc9a96f7b3ad8) i can sign in to the forum) so i'm not far off. I have very little knowledge of how they work, so can someone help me to get them both generating and accepting the same password. P.S I can't edit the code from the WYSIWYG web builder, as it generates it automatically. Here is the code for the login page by the WYSIWYG Web Builder. <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_name'] == 'loginform') { session_start(); $success_page = isset($_SESSION['page_from'])?$_SESSION['page_from']:'/../../library/'; $error_page = basename(__FILE__); $mysql_server = 'localhost'; $mysql_username = '???????'; $mysql_password = '???????'; $mysql_database = '???????'; $mysql_table = 'USERS'; $crypt_pass = md5($_POST['password']); $found = false; $fullname = ''; $db = mysql_connect($mysql_server, $mysql_username, $mysql_password); if (!$db) { die('Failed to connect to database server!<br>'.mysql_error()); } mysql_select_db($mysql_database, $db) or die('Failed to select database<br>'.mysql_error()); $sql = "SELECT password, fullname, active FROM ".$mysql_table." WHERE username = '".mysql_real_escape_string($_POST['username'])."'"; $result = mysql_query($sql, $db); if ($data = mysql_fetch_array($result)) { if ($crypt_pass == $data['password'] && $data['active'] != 0) { $found = true; $fullname = $data['fullname']; } } mysql_close($db); if($found == false) { header('Location: '.$error_page); exit; } else { if (session_id() == "") { session_start(); } $_SESSION['username'] = $_POST['username']; $_SESSION['fullname'] = $fullname; $rememberme = isset($_POST['rememberme']) ? true : false; if ($rememberme) { setcookie('username', $_POST['username'], time() + 3600*24*30); setcookie('password', $_POST['password'], time() + 3600*24*30); } header('Location: '.$success_page); exit; } } $username = isset($_COOKIE['username']) ? $_COOKIE['username'] : ''; $password = isset($_COOKIE['password']) ? $_COOKIE['password'] : ''; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login</title> <meta name="description" content="Login page for Techyoucation.com"> <meta name="keywords" content="techyoucation, tutorials, technology, under construction,"> <meta name="author" content="Aled Daniel Evans"> <meta name="categories" content="Technology, Tutorials"> <link rel="shortcut icon" href="icon.ico"> <link rel="stylesheet" href="Site.css" type="text/css"> <link rel="stylesheet" href="index.css" type="text/css"> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="wb.stickylayer.min.js"></script> <script type="text/javascript" src="jquery.effects.core.min.js"></script> <script type="text/javascript" src="jquery.effects.blind.min.js"></script> <script type="text/javascript" src="jquery.effects.bounce.min.js"></script> <script type="text/javascript" src="jquery.effects.clip.min.js"></script> <script type="text/javascript" src="jquery.effects.drop.min.js"></script> <script type="text/javascript" src="jquery.effects.explode.min.js"></script> <script type="text/javascript" src="jquery.effects.fold.min.js"></script> <script type="text/javascript" src="jquery.effects.highlight.min.js"></script> <script type="text/javascript" src="jquery.effects.pulsate.min.js"></script> <script type="text/javascript" src="jquery.effects.scale.min.js"></script> <script type="text/javascript" src="jquery.effects.shake.min.js"></script> <script type="text/javascript" src="jquery.effects.slide.min.js"></script> <script type="text/javascript" src="../../searchindex.js"></script> <script type="text/javascript"> <!-- var features = 'toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,status=no,left=,top=,width=,height='; var searchDatabase = new SearchDatabase(); var searchResults_length = 0; var searchResults = new Object(); function searchPage(features) { var element = document.getElementById('search_box_keyword'); if (element.value.length != 0 || element.value != " ") { var value = unescape(element.value); var keywords = value.split(" "); searchResults_length = 0; for (var i=0; i<database_length; i++) { var matches = 0; var words = searchDatabase[i].title + " " + searchDatabase[i].description + " " + searchDatabase[i].keywords; for (var j = 0; j < keywords.length; j++) { var pattern = new RegExp(keywords[j], "i"); var result = words.search(pattern); if (result >= 0) { matches++; } else { matches = 0; } } if (matches == keywords.length) { searchResults[searchResults_length++] = searchDatabase[i]; } } var wndResults = window.open('about:blank', '', features); setTimeout(function() { var html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Search results<\/title><\/head>'; html = html + '<body style="background-color:#FFFFFF;margin:0;padding:2px 2px 2px 2px;">'; html = html + '<span style="font-family:Arial;font-size:13px;color:#000000">'; for (var n=0; n<searchResults_length; n++) { html = html + '<b><a style="color:#0000FF" target="_parent" href="'+searchResults[n].url+'">'+searchResults[n].title +'<\/a><\/b><br>Description:' + searchResults[n].description + '<br>Keywords:' + searchResults[n].keywords +'<br><br>\n'; } if (searchResults_length == 0) { html = html + 'No results'; } html = html + '<\/span>'; html = html + '<\/body><\/html>'; wndResults.document.write(html); },100); } return false; } // --> </script> <script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script> <script src="cookieControl-5.1.min.js" type="text/javascript"></script> <script type="text/javascript">//<![CDATA[ cookieControl({ introText:'<p>This site uses some unobtrusive cookies to store information on your computer.</p>', fullText:'<p>Some of these cookies are essential to make our site work and have already been set. Others help us to improve by giving us some insight into how the site is being used or help to improve the experience of using our site but will only be set if you consent.</p><p>By using our site you accept the terms of our <a href="http://www.whatnews.co.uk/privacy">Privacy Policy</a></p>', position:'left', // left or right shape:'triangle', // triangle or diamond theme:'light', // light or dark startOpen:true, autoHide:3000, subdomains:true, protectedCookies: ['analytics', 'twitter'], //list the cookies you do not want deleted ['analytics', 'twitter'] consentModel:'implicit', onAccept:function(){ccAddAnalytics()}, onReady:function(){}, onCookiesAllowed:function(){ccAddAnalytics()}, onCookiesNotAllowed:function(){}, countries:'United Kingdom,Netherlands' // Or supply a list ['United Kingdom', 'Greece'] }); function ccAddAnalytics() { jQuery.getScript("http://www.google-analytics.com/ga.js", function() { var GATracker = _gat._createTracker(''); GATracker._trackPageview(); }); } //]]> </script> <script type="text/javascript" src="./wwb8.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#FB-Over a").hover(function() { $(this).children("span").stop().fadeTo(200, 0); }, function() { $(this).children("span").stop().fadeTo(200, 1); }) $("#G-Over a").hover(function() { $(this).children("span").stop().fadeTo(200, 0); }, function() { $(this).children("span").stop().fadeTo(200, 1); }) $("#T-Over a").hover(function() { $(this).children("span").stop().fadeTo(200, 0); }, function() { $(this).children("span").stop().fadeTo(200, 1); }) $("#YT-Over a").hover(function() { $(this).children("span").stop().fadeTo(200, 0); }, function() { $(this).children("span").stop().fadeTo(200, 1); }) $("#Layer3").stickylayer({orientation: 1, position: [0, 0], delay: 0}); $("#RollOver1 a").hover(function() { $(this).children("span").stop().fadeTo(500, 0); }, function() { $(this).children("span").stop().fadeTo(500, 1); }) $("#header_inc_layer1").stickylayer({orientation: 2, position: [0, 0], delay: 0}); var $search = $('#search_box_form'); var $searchInput = $search.find('input'); var $searchLabel = $search.find('label'); if ($searchInput.val()) { $searchLabel.hide(); } $searchInput.focus(function() { $searchLabel.hide(); }).blur(function() { if (this.value == '') { $searchLabel.show(); } }); $searchLabel.click(function() { $searchInput.trigger('focus'); }); }); </script> <!--[if lt IE 7]> <style type="text/css"> img { behavior: url("pngfix.htc"); } </style> <![endif]--> <!-- no cache headers --> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="no-cache"> <meta http-equiv="Expires" content="-1"> <meta http-equiv="Cache-Control" content="no-cache"> <!-- end no cache headers --> </head> <body> <div id="container"> <div id="wb_Shape1" style="position:absolute;left:3px;top:74px;width:994px;height:412px;z-index:66;"> <img src="images/img0010.png" id="Shape1" alt="" style="border-width:0;width:994px;height:412px;"></div> <div id="wb_Text1" style="position:absolute;left:33px;top:103px;width:102px;height:29px;z-index:67;text-align:left;"> <span style="color:#2A2B30;font-family:Arial;font-size:24px;"><strong>Login</strong></span></div> <hr id="Line1" style="margin:0;padding:0;position:absolute;left:30px;top:155px;width:933px;height:1px;z-index:68;"> <div id="wb_Text2" style="position:absolute;left:30px;top:166px;width:76px;height:12px;text-align:justify;z-index:69;"> <span style="color:#D9D9D9;font-family:Arial;font-size:9.3px;">PLEASE LOGIN</span></div> <div id="wb_loginform" style="position:absolute;left:336px;top:218px;width:322px;height:214px;z-index:70;"> <form name="loginform" method="post" action="<?php echo basename(__FILE__); ?>" id="loginform"> <input type="hidden" name="form_name" value="loginform"> <div id="wb_Text6" style="position:absolute;left:45px;top:118px;width:91px;height:16px;z-index:58;text-align:left;"> <span style="color:#666666;font-family:Arial;font-size:13px;">Remember me</span></div> <input type="checkbox" id="rememberme" name="rememberme" value="on" style="position:absolute;left:23px;top:117px;z-index:59;"> <input type="submit" id="login_button" name="login" value="Log In" style="position:absolute;left:92px;top:148px;width:138px;height:33px;z-index:60;"> <div id="wb_Shape2" style="position:absolute;left:23px;top:16px;width:283px;height:40px;z-index:61;"> <img src="images/img0011.png" id="Shape2" alt="" style="border-width:0;width:283px;height:40px;"></div> <div id="wb_Shape3" style="position:absolute;left:23px;top:66px;width:283px;height:40px;z-index:62;"> <img src="images/img0012.png" id="Shape3" alt="" style="border-width:0;width:283px;height:40px;"></div> <input type="text" id="username" style="position:absolute;left:23px;top:16px;width:280px;height:38px;line-height:38px;z-index:63;" name="username" value="<?php echo $username; ?>Username" autocomplete="off"> <input type="password" id="password" style="position:absolute;left:23px;top:66px;width:280px;height:38px;line-height:38px;z-index:64;" name="password" value="<?php echo $password; ?> Password" autocomplete="off"> <div id="wb_Text3" style="position:absolute;left:83px;top:185px;width:160px;height:16px;z-index:65;text-align:left;"> <span style="color:#2A2B30;font-family:Arial;font-size:13px;"><strong>Not a member? <a href="./../register/index.php" class="Bold_Grey">Register</a></strong></span></div> </form> </div> <div id="wb_Extension1" style="position:absolute;left:0px;top:0px;width:100px;height:100px;z-index:72;"> </div> </div> <div id="Layer2" style="position:fixed;text-align:center;left:0px;top:0px;right:0px;height:56px;z-index:73;" title=""> <div id="Layer2_Container" style="width:994px;position:relative;margin-left:auto;margin-right:auto;text-align:left;"> <div id="wb_Header_Master_Page" style="position:absolute;left:0px;top:0px;width:991px;height:56px;z-index:13;"> <div id="Layer3" style="position:absolute;text-align:right;left:0px;top:0px;width:220px;height:56px;z-index:11;" title=""> <div id="Layer3_Container" style="width:220px;position:relative;margin-left:auto;margin-right:auto;text-align:left;"> <div id="RollOver1" style="position:absolute;overflow:hidden;left:0px;top:5px;width:219px;height:47px;z-index:0"> <a href="./../../index.html" target="_top"> <img class="hover" alt="" src="images/techyoucation_grey.png" style="left:0px;top:0px;width:219px;height:47px;"> <span><img alt="" src="images/full_logo.png" style="left:0px;top:0px;width:219px;height:47px"></span> </a> </div> </div> </div> <div id="header_inc_layer1" style="position:absolute;text-align:right;left:561px;top:0px;width:430px;height:56px;z-index:12;" title=""> <div id="header_inc_layer1_Container" style="width:430px;position:relative;margin-left:auto;margin-right:auto;text-align:left;"> <div id="signup" style="position:absolute;overflow:hidden;left:231px;top:8px;width:86px;height:41px;z-index:2"> <a href="./../register/index.php"> <img class="hover" alt="" src="images/signup-hover.png" style="left:0px;top:0px;width:86px;height:41px;"> <span><img alt="" src="images/signup-off.png" style="left:0px;top:0px;width:86px;height:41px"></span> </a> </div> <div id="wb_login" style="position:absolute;left:329px;top:8px;width:86px;height:41px;z-index:3;"> <a href="./index.php" onclick="ShowObject('login_dialog', 1);return false;"><img src="images/login-small.png" id="login" alt="" border="0" style="width:86px;height:41px;"></a></div> <div id="wb_search_dark_bg" style="position:absolute;left:134px;top:8px;width:86px;height:41px;z-index:4;"> <img src="images/search.png" id="search_dark_bg" alt="" border="0" style="width:86px;height:41px;"></div> <div id="wb_Search-g" style="position:absolute;left:169px;top:8px;width:51px;height:41px;visibility:hidden;z-index:5;"> <img src="images/img0007.gif" id="Search-g" alt="" style="border-width:0;width:51px;height:41px;"></div> <div id="wb_search-w" style="position:absolute;left:17px;top:8px;width:152px;height:41px;visibility:hidden;z-index:6;"> <img src="images/img0008.gif" id="search-w" alt="" style="border-width:0;width:152px;height:41px;"></div> <div id="wb_Search_show" style="position:absolute;left:192px;top:17px;width:22px;height:22px;z-index:7;"> <a href="#" onclick="ShowObjectWithEffect('wb_search-w', 1, 'slideright', 500);ShowObject('wb_Search-g', 1);ShowObjectWithEffect('search_layer', 1, 'slideright', 500);ShowObject('wb_search_click', 1);return false;"><img src="images/icon-search-da7ca298c043e217cdaced7a129fef8f.png" id="Search_show" alt="" border="0" style="width:22px;height:22px;"></a></div> <div id="search_layer" style="position:absolute;text-align:left;visibility:hidden;left:32px;top:7px;width:149px;height:36px;z-index:8;" title=""> <div id="wb_search_box" style="position:absolute;left:0px;top:7px;width:149px;height:27px;z-index:1;"> <form action="" name="search_box_form" id="search_box_form" accept-charset="UTF-8" onsubmit="return searchPage(features)"> <input type="text" id="search_box_keyword" style="position:absolute;left:0px;top:0px;width:149px;height:27px;line-height:27px;;" name="SiteSearch1" value=""> <label id="search_box_label" style="position:absolute;left:0px;top:7px;" for="search_box_keyword">Search this website</label> </form> </div> </div> <div id="wb_search_click" style="position:absolute;left:192px;top:17px;width:21px;height:21px;visibility:hidden;z-index:9;"> <a href="#" onclick="searchPage();return false;"><img src="images/icon-search-da7ca298c043e217cdaced7a129fef8f.png" id="search_click" alt="" border="0" style="width:21px;height:21px;"></a></div> </div> </div> </div> </div> </div> <div id="footer_layer" style="position:absolute;text-align:center;left:0px;top:494px;width:100%;height:258px;z-index:74;" title=""> <div id="footer_layer_Container" style="width:994px;position:relative;margin-left:auto;margin-right:auto;text-align:left;"> <div id="wb_footer_master_page" style="position:absolute;left:0px;top:0px;width:994px;height:257px;z-index:29;"> <div id="Layer" style="position:absolute;text-align:center;left:1px;top:0px;width:99%;height:257px;z-index:28;" title=""> <div id="Layer_Container" style="width:993px;position:relative;margin-left:auto;margin-right:auto;text-align:left;"> <div id="wb_logo-g" style="position:absolute;left:0px;top:12px;width:219px;height:47px;z-index:14;"> <a href="./../../under_construction/index.html"><img src="images/techyoucation%20grey.png" id="logo-g" alt="" border="0" style="width:219px;height:47px;"></a></div> <div id="wb_mission-text" style="position:absolute;left:6px;top:72px;width:250px;height:48px;text-align:justify;z-index:15;"> <span style="color:#808080;font-family:Arial;font-size:13px;">We are on a mission, that mission is to teach everyone with the passion to learn Technology.</span></div> <hr id="devide" style="margin:0;padding:0;position:absolute;left:8px;top:121px;width:222px;height:1px;z-index:16;"> <div id="wb_copyright-text" style="position:absolute;left:6px;top:172px;width:250px;height:48px;text-align:justify;z-index:17;"> <span style="color:#808080;font-family:Arial;font-size:13px;">© Techyoucation 2013 All trademarks and logos are the property of their respective owners!</span></div> <div id="wb_get-in" style="position:absolute;left:751px;top:7px;width:235px;height:32px;z-index:18;text-align:left;"> <span style="color:#000000;font-family:Arial;font-size:13px;"><strong><a href="./../../under_construction/contact_us/index.html" class="Bold_Grey">Get In Touch </a></strong></span><span style="color:#808080;font-family:Arial;font-size:13px;"><strong><a href="./../../under_construction/contact_us/index.html" class="Bold_Grey">→</a></strong></span><span style="color:#000000;font-family:Arial;font-size:13px;"><strong><br><a href="./../../legal/index.php" class="Bold_Grey">Privacy Policy / Terms Of Service</a></strong></span></div> <div id="wb_vision-logo" style="position:absolute;left:318px;top:12px;width:162px;height:60px;z-index:19;"> <a href="http://secure.thevisionworld.com/aff.php?aff=092" target="_top"><img src="images/VisionHelpdeskLogo.png" id="vision-logo" alt="" border="0" style="width:162px;height:60px;"></a></div> <div id="wb_Vision" style="position:absolute;left:286px;top:72px;width:230px;height:64px;text-align:justify;z-index:20;"> <span style="color:#808080;font-family:Arial;font-size:13px;">We would like to thank vision HelpDesk for supporting us with our mission by supplying us with a free copy of their amazing script.</span></div> <div id="wb_Navaldesigns" style="position:absolute;left:286px;top:152px;width:230px;height:48px;text-align:justify;z-index:21;"> <span style="color:#808080;font-family:Arial;font-size:13px;">We would also like to thank George <a href="http://www.dbtechnosystems.com/" class="Top_Nav">(Navaldesign)</a> for helping us with the membership system on this site.</span></div> <div id="FB-Over" style="position:absolute;overflow:hidden;left:38px;top:134px;width:29px;height:29px;z-index:22"> <a href="https://www.facebook.com/techyoucation"> <img class="hover" alt="" src="images/icon-facebook-new-7fd375259239b05ac8f42657988e351f-over.png" style="left:0px;top:0px;width:29px;height:29px;"> <span><img alt="" src="images/icon-facebook-new-7fd375259239b05ac8f42657988e351f.png" style="left:0px;top:0px;width:29px;height:29px"></span> </a> </div> <div id="G-Over" style="position:absolute;overflow:hidden;left:78px;top:134px;width:29px;height:29px;z-index:23"> <a href="https://plus.google.com/b/113434853007695128940/113434853007695128940/posts"> <img class="hover" alt="" src="images/icon-googleplus-f9e3bf613ef1807f53cc7e3c34fb9b1a-over.png" style="left:0px;top:0px;width:29px;height:29px;"> <span><img alt="" src="images/icon-googleplus-f9e3bf613ef1807f53cc7e3c34fb9b1a.png" style="left:0px;top:0px;width:29px;height:29px"></span> </a> </div> <div id="T-Over" style="position:absolute;overflow:hidden;left:118px;top:134px;width:29px;height:29px;z-index:24"> <a href="https://twitter.com/techyoucation"> <img class="hover" alt="" src="images/icon-twitter-new-47502fddb8222a283378a21e5b421c2d-over.png" style="left:0px;top:0px;width:29px;height:29px;"> <span><img alt="" src="images/icon-twitter-new-47502fddb8222a283378a21e5b421c2d.png" style="left:0px;top:0px;width:29px;height:29px"></span> </a> </div> <div id="YT-Over" style="position:absolute;overflow:hidden;left:158px;top:134px;width:29px;height:29px;z-index:25"> <a href="http://www.youtube.com/techyoucation"> <img class="hover" alt="" src="images/icon-youtube-a442f16454bb0a8fe31df4f93b5d8aa2-over.png" style="left:0px;top:0px;width:29px;height:29px;"> <span><img alt="" src="images/icon-youtube-a442f16454bb0a8fe31df4f93b5d8aa2.png" style="left:0px;top:0px;width:29px;height:29px"></span> </a> </div> <!-- Twitter Follow --> <div id="twitter" style="position:absolute;left:587px;top:6px;width:154px;height:47px;z-index:26"> <a href="https://twitter.com/techyoucation" class="twitter-follow-button" data-show-count="false">Follow @techyoucation</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></div> <div id="wb_HTML-image" style="position:absolute;left:610px;top:58px;width:99px;height:139px;z-index:27;"> <img src="images/html5_logo_small.png" id="HTML-image" alt="" border="0" style="width:99px;height:139px;"></div> </div> </div> </div> </div> </div> </body> </html> and here is the login code for the forum. <?php //signin.php include 'connect.php'; include 'header.php'; echo '<h3>Sign in</h3><br />'; //first, check if the user is already signed in. If that is the case, there is no need to display this page if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true) { echo 'You are already signed in, you can <a href="signout.php">sign out</a> if you want.'; } else { if($_SERVER['REQUEST_METHOD'] != 'POST') { /*the form hasn't been posted yet, display it note that the action="" will cause the form to post to the same page it is on */ echo '<form method="post" action=""> Username: <input type="text" name="username" /><br /> Password: <input type="password" name="password"><br /> <input type="submit" value="Sign in" /> </form>'; } else { /* so, the form has been posted, we'll process the data in three steps: 1. Check the data 2. Let the user refill the wrong fields (if necessary) 3. Varify if the data is correct and return the correct response */ $errors = array(); /* declare the array for later use */ if(!isset($_POST['username'])) { $errors[] = 'The username field must not be empty.'; } if(!isset($_POST['password'])) { $errors[] = 'The password field must not be empty.'; } if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/ { echo 'Uh-oh.. a couple of fields are not filled in correctly..<br /><br />'; echo '<ul>'; foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */ { echo '<li>' . $value . '</li>'; /* this generates a nice error list */ } echo '</ul>'; } else { //the form has been posted without errors, so save it //notice the use of mysql_real_escape_string, keep everything safe! //also notice the sha1 function which hashes the password $sql = "SELECT id, username, userlevel FROM USERS WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . sha1($_POST['password']) . "'"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'Something went wrong while signing in. Please try again later.'; //echo mysql_error(); //debugging purposes, uncomment when needed } else { //the query was successfully executed, there are 2 possibilities //1. the query returned data, the user can be signed in //2. the query returned an empty result set, the credentials were wrong if(mysql_num_rows($result) == 0) { echo 'You have supplied a wrong user/password combination. Please try again.'; } else { //set the $_SESSION['signed_in'] variable to TRUE $_SESSION['signed_in'] = true; //we also put the id and username values in the $_SESSION, so we can use it at various pages while($row = mysql_fetch_assoc($result)) { $_SESSION['id'] = $row['id']; $_SESSION['username'] = $row['username']; $_SESSION['userlevel'] = $row['userlevel']; } echo 'Welcome, ' . $_SESSION['username'] . '. <br /><a href="index.php">Proceed to the forum overview</a>.'; } } } } } include 'footer.php'; ?> It looks like you many need the header two... <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="A short description." /> <meta name="keywords" content="put, keywords, here" /> <title>PHP-MySQL forum</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <div id="blog"> <div id="header"><a href="http://techyoucation.com" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Logo','','images/techyoucation grey.png',1)"><img src="images/full logo.png" alt="techyoucation logo" width="219" height="47" id="Logo" /></a></div> <body> <h1><br></h1> <div id="wrapper"> <div id="menu"> <a class="item" href="/forum/index.php">Home</a> - <a class="item" href="/forum/create_topic.php">Create a topic</a> - <a class="item" href="/forum/create_cat.php">Create a category</a> <div id="userbar"> <?php if($_SESSION['signed_in']) { echo 'Hello <b>' . htmlentities($_SESSION['username']) . '</b>. Not you? <a class="item" href="signout.php">Sign out</a>'; } else { echo '<a class="item" href="signin.php">Sign in</a> or <a class="item" href="signup.php">create an account</a>'; } ?> </div> </div> <div id="content"> Thanks in advance Aled
  15. I've written a basic php application with a login feature, using $_SESSION, but it times out after 20 minutes, how can I change the length of a session? Either in php on the page or in the php files whichever is simpler.
  16. I hope I am posting in the appropriate place. Although I didn't create this code I did write it while following along with the phpacademy 44 video tutorial on Register & Login. Next I followed the 6 video tutorial on creating a "Remember Me" cookie in order to bypass the login. Unfortunately these 2 series were not designed to go together so I am left with a very complex login system via "Register & Login" and no understanding of how to implement the "Remember Me" feature. Before I go uploading any code or copying & pasting anything I would like to throw out a general question as I've posted this on several message boards & PHP Forums so far to no avail - Is there anyone here who has implemented a "Remember Me" feature into the "Register & Login" series presented by phpacademy? This might be a simple exercise within any other login system but this one seems to have left everyone stumped so far. I will gladly upload any files or make any informatio available if anyone is interested. Otherwise it is a lot work only to risk looking like someone who is asking for handouts.
  17. Hey all, new to PHPfreaks, seems like a very active site. Anyhow, I'm having an issue with this login script. It works just fine for me in chrome and safari, but in firefox and ie it does nothing, not even spit out an error. I'm not sure what's going wrong here, I'm thinking something with the header function. <?php session_start(); include 'dbcon.php'; $err = array(); foreach($_GET as $key => $value) { $get[$key] = filter($value); //get variables are filtered. } if ($_POST['doLogin']=='Login') { foreach($_POST as $key => $value) { $data[$key] = filter($value); // post variables are filtered } $user_email = $data['usr_email']; $pass = $data['pwd']; if (strpos($user_email,'@') === false) { $user_cond = "user_name='$user_email'"; } else { $user_cond = "user_email='$user_email'"; } $result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM adminusers WHERE $user_cond AND `banned` = '0' ") or die (mysql_error()); $num = mysql_num_rows($result); // Match row found with more than 1 results - the user is authenticated. if ( $num > 0 ) { list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result); if(!$approved) { //$msg = urlencode("Account not activated. Please check your email for activation code"); $err[] = "Account not activated."; //header("Location: login.php?msg=$msg"); //exit(); } //check against salt if ($pwd === PwdHash($pass,substr($pwd,0,9))) { if(empty($err)){ // this sets session and logs user in session_start(); session_regenerate_id (true); //prevent against session fixation attacks. // this sets variables in the session $_SESSION['user_id']= $id; $_SESSION['user_name'] = $full_name; $_SESSION['user_level'] = $user_level; $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); //update the timestamp and key for cookie $stamp = time(); $ckey = GenKey(); mysql_query("update adminusers set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error()); //set a cookie if(isset($_POST['remember'])){ setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/"); } header("Location: ../index.php"); exit (); } } else { //$msg = urlencode("Invalid Login. Please try again with correct user email and password. "); $err[] = "Invalid Login. Please try again with correct user email and password."; //header("Location: login.php?msg=$msg"); } } else { $err[] = "Error - Invalid login. No such user exists"; } } ?> <script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#logForm").validate(); }); </script>
  18. Hi all, first post here so please bear with me. I chose to try and reach out to the internet community for help on this one because it is over my head. I currently have a bootstrap based HTMl website. I would like to add a login system so my employees can access restricted pages in order to download company matierals. I have the html and css for a login popup already created but I have no idea what to do for the php backend to make it function. I understand that I need to point it to a mySQL database along with various php code. Idealy, I want to create usernames for the employees to keep things simple and consistent. I don't neccesairly need an admin panel because I can simply hard code the material download links into the restricted page. Any help would be appreciated. here is a link to my site - www.youngexplosives.com
  19. Hi, recently I've created a login form and I've used the salt method (which I've not really used before) and everything is working great apart from the login. Basically what happens is I can login with any password. So if my password was 'hello1234' and I put 'fndsjnmfosd' it would state that as correct; try it yourself at www.harvy.info Sign up and then try to login, you'll see that you can enter any password and it'll see that as correct. Thanks. Login proccess (What happens when you try to login) <?php include 'dbConfig.php'; include 'functions.php'; sec_session_start(); if(isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; if(login($email, $password, $mysqli) == true) { header('Location: member.php?id='); } else { header('Location: login.php?error=1'); } } else { echo 'Invalid Request'; } ?>
  20. Hello all. This is my first post in a php forum. Thanks, in advance, for any help. This code: <?php // database table 'users' is setup with the following fields: // first_name, last_name, user_name, password $db_hostname = "localhost"; $db_username = "root"; $db_password = ""; $db_name = "justinalba_module3_db"; //connection to the database $dbc = @mysqli_connect($db_hostname, $db_username, $db_password, $db_name) or die("Unable to connect to MySQL"); $sql = "INSERT INTO user (name_first, name_last, name_username, password) VALUES ('Sam', 'Row', 'samrow', 'pw123')"; mysqli_query ($dbc, $sql) or die("Problem executing query"); echo "Rows inserted: ", mysqli_affected_rows($dbc), "<br><br>"; $rowcount = 0; $q = mysqli_query($dbc, "select * from user"); while ($dbc = mysqli_fetch_row($q)) { $rowcount++; for ($k=0; $k<count($dbc); $k++){ echo " $dbc[$k] "; } echo "<br>"; } echo "<p> A total of $rowcount rows<br>"; ?> works perfectly...then I add it to a function: function register(){ if(isset($_POST['submitRegistration'])) $username=$_POST['username']; $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $password=$_POST['password2']; { if($_POST['username']=="") { echo "Please type username"; } elseif (!preg_match("/^[a-zA-Z1-9]+$/", $username)) //checks for illegal characters, succcess! { echo 'Use alphanumeric characters only.'; } elseif (strlen($username) < 6 || strlen($username) > 15) // checks length of username { echo "Username must be 6 to 15 characters"; } elseif($_POST['password1']==""|$_POST['password2']=="") { echo "Please type password"; } elseif($_POST['password1']!=$_POST['password2']) { echo "Uh-oh. Your passwords don't match."; } else { $username=$_POST['username']; $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $password=$_POST['password2']; $dbc = @mysqli_connect($db_hostname, $db_username, $db_password, $db_name) or die("Unable to connect to MySQL"); $sql = "INSERT INTO user (id, name_first, name_last, name_username, password) VALUES ('', '$firstName', '$lastName', '$username', '$password')"; mysqli_query ($dbc, $sql) or die("Problem executing query"); echo "Rows inserted: ", mysqli_affected_rows($dbc), "<br><br>"; $rowcount = 0; $q = mysqli_query($dbc, "select * from user"); while ($dbc = mysqli_fetch_row($q)) { $rowcount++; for ($k=0; $k<count($dbc); $k++){ echo " $dbc[$k] "; } echo "<br>"; } echo "<p> A total of $rowcount rows<br>"; } } } and I get the "die("Unable to connect to MySQL")" error. Any thoughts? I know I restated several variables inside the whatif statement. I was just trying to see what the problem was. Thanks, JA. module3_2.php registration.php localhost.sql.zip
  21. Hi, I'm trying to make a login form for my website, but I can't seem to get my head around this problem, basically it keeps returning this row error and I'm not too sure why? Really need some help on this, thanks. (Excuse my sloppy coding; just trying to get the basics to work atm) LOGIN.PHP <?php session_start(); include "dbConfig.php"; if ($_SERVER['REQUEST_METHOD'] == "POST") { $username = trim($_POST['username']); $password = trim ($_POST['password']); $query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1"; $result = mysql_query($query) or die(mysql_error()); if(!$result) { die("Wrong username or password."); } elseif(!mysql_num_rows($result)) { die("No user found by that username."); } else { Header("Location: memberstest.php"); exit(); } } ?> <form action="login.php" method="POST"> Username:<br> <input class="login_form" type="text" name="username" id="username" maxlength="20"> <br><br> Password:<br> <input class="login_form" type="password" name="password" id="password" maxlength="50"> <br><br> <button type="submit" name="submit" class="InputButton">Login</button> </form> REGISTER.PHP <?php session_start(); define('SALT_CHARACTERS', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'); function generate_salt() { $salt = ''; for($i = 0; $i < 21; $i++) { $salt .= substr(SALT_CHARACTERS, mt_rand(0, strlen(SALT_CHARACTERS) - 1), 1); } return $salt; } $errors = array(); if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password'])){ require_once 'dbConfig.php'; $firstname = trim($_POST['firstname']); $lastname = trim($_POST['lastname']); $username = trim($_POST['username']); $email = trim($_POST['email']); $password = $_POST['password']; if($firstname == '') { $errors[] = 'Please enter your firstname.'; header("location: register.php?r=error"); } if($lastname == '') { $errors[] = 'Please enter your lastname.'; header("location: register.php?r=error"); } if($email == '') { $errors[] = 'Please enter an email address.'; header("location: register.php?r=error"); } if($username == '') { $errors[] = 'Please enter a username.'; header("location: register.php?r=error"); } if($password == '') { $errors[] = 'Please enter a password.'; header("location: register.php?r=error"); }elseif(strlen($password) < 6) { $errors[] = 'Your password must be at least 6 characters long.'; header("location: register.php?r=error"); } if(count($errors) === 0) { $passwordHash = crypt($password, '$2y$12$' . generate_salt()); $query = "INSERT INTO users(firstname, lastname, username, email, password) VALUES('$firstname', '$lastname', '$username', '$email', '$passwordHash')"; $result = mysql_query($query) or die(mysql_error()); if ($result) { header("location: register.php?r=success"); exit(); } else { die("Query failed"); } } } ?>
  22. Hi all, I am going bald on this one. I wonder what could be wrong. I could login to my local server but cant login in a live server! thanks all <?php if(isset($_POST['login'])){ $tbl_name="reg_users"; // Define $myusername and $mypassword $username=$_POST['username']; $password=$_POST['password']; // To protect MySQL injection $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); if($username == ''){ echo "<font color='red' size='-2'><b>Pls Enter User ID</b></font>"; } if($password == ''){ echo "<font color='red' size='-2'><b>Pls Enter Password</b></font>"; }else{ $crypt_pass = md5($password); //check for existance of username and password $sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$crypt_pass'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register username and password and redirect to login page" $_SESSION['username'] = $username; $_SESSION['password'] = $password; header("location: ../folder/filename.php"); exit(); } else { //if no match found, echo out error message echo "<font color='red' size='2'><b>Invalid User ID or Password</b></font><br>"; } } } ob_end_flush(); ?>
  23. Hi, I'm trying to create a Login & Register form which will create a profile for that user but I'm getting a lot of problems and I can't seem to figure out why it's not working correctly? I've created a post on the forums before about this problem but the problem was never resolved, I am new to PHP hence my noobieness. Basicly the problem at the moment is when I try to login it gives me a 'Wrong details error' which is expressed like so: elseif(!mysql_num_rows($r)) { $errorMsg = "* Sorry, couldn't log you in. Wrong login information."; } As far as the register form goes, it works fine to my knowledge as it's adding users to the database when they register and it's encrypting their passwords by using the crypt(); function. I'll link the Login form, the register form and the dbConfig below but I'll replace any sensitive details with '-HIDDEN-' for safety. I would really appreshiate if someone could help me out on this one cause I've been stuck with this problem for quite a while now and I can't figure it out, thanks a lot Register.php <?php include ("dbConfig.php"); if ($_SERVER['REQUEST_METHOD'] == "POST") { $usernameSQL = mysql_real_escape_string($_POST['username']); $emailSQL = mysql_real_escape_string($_POST['email']); $passwordSQL = mysql_real_escape_string($_POST['password']); $passwordSQL = crypt('$password'); $q = "INSERT INTO -HIDDEN-(username, email, password)VALUES('$usernameSQL', '$emailSQL', '$passwordSQL')"; $r = mysql_query($q); header("Location: register.php?op=thanks"); } ?> <form action="?op=reg" method="POST"> Username:<br><font color="red">*</font><input class="GeneralForm" type="text" name="username" id="username" maxlength="20"><br> <br> Email:<br><font color="red">*</font><input class="GeneralForm" type="text" name="email" id="email" maxlength="50"><br> <br> Password:<br><font color="red">*</font><input class="GeneralForm" type="password" name="password" id="password" maxlength="50"><br> <br> <input type="checkbox" name="tick"><font color="gray" size="3"> I agree to the Terms of Use<br> <br> <button type="submit" name="submit" class="InputButton" value="Submit">Submit</button> </form> <br><font size="2" color="gray">* You can edit details on your profile when you login!</font> Login.php <?php session_start(); include "dbConfig.php"; $errorMsg = ""; if ($_GET["op"] == "fail") { $errorMsg = "* You need to be logged in to access the members area!"; } if ($_SERVER['REQUEST_METHOD'] == "POST") { $username = trim($_POST["username"]); $password = trim($_POST["password"]); if (empty($username) || empty($password)) { $errorMsg = "* You need to provide a username & password."; } else { $usernameSQL = mysql_real_escape_string($username); $passwordSQL = crypt('$password'); $q = "SELECT id FROM -HIDDEN- WHERE username='{$usernameSQL}' AND password='{$passwordSQL}' LIMIT 1"; $r = mysql_query($q) or die("Error: " . mysql_error() . "<br>Query: " . $q); if(!$r) { //Error running query $errorMsg = "* Wrong username or password."; } elseif(!mysql_num_rows($r)) { //User not found $errorMsg = "* Sorry, couldn't log you in. Wrong login information."; } else { // Login good, create session variables and redirect $_SESSION["valid_id"] = $obj->id; $_SESSION["valid_user"] = $username; $_SESSION["valid_time"] = time(); // Redirect to member page header("Location: members.php"); } } } ?> <form action="?op=login" method="POST"> Username:<br> <input class="GeneralForm" type="text" name="username" id="username" maxlength="20" value="<?php echo htmlentities($usernameSQL); ?>"> <br><br> Password:<br> <input class="GeneralForm" type="password" name="password" id="password" maxlength="50"> <br><br> <button type="submit" name="Submit" class="InputButton" value="Login">Login</button> <h1 class="FailLoginState"><?php echo $errorMsg; ?></h1> </form> dbConfig.php <? $host = "-HIDDEN-"; $user = "-HIDDEN-"; $pass = "-HIDDEN-"; $db = "-HIDDEN-"; $ms = mysql_pconnect($host, $user, $pass); if ( !$ms ) { echo "Error connecting to database.\n"; } mysql_select_db($db); ?>
  24. Hi all, I was hoping someone could help me with something I wish to create. I wish to creating something like a login page but instead of name and password, you use a 'Customer Number' which searches the 'Customer' database to see if the entered customer number exists, and if it does, redirect into the system to another page which outputs all the data relating to that customer number, e.g. Customer number: 900800700 Customer Name: James May Customer Purchase Date: 12/08/2012 Location: London, England etc. I want to get whatever has been entered into the box and return the data above and more, but have no idea how i'd go about doing this. Any help that you guys could give would be lovely.
  25. Hello all. I've download and install a script register and login by php. the script is working well. i have plan to make 2-3 pages which diffirent each pages, and when the user/client login they will redirect to his own pages. please help me how to coded the script because i am newbie at php code.this is the code of that script. login.php <?PHP require_once("include/membersite_config.php"); if(isset($_POST['submitted'])) { if($fgmembersite->Login()) { $fgmembersite->RedirectToURL("login-home.php"); } } ?> <?php include_once ('include/header.php') ; ?> <!-- Form Code Start --> <div id='fg_membersite'> <form id='login' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'> <fieldset > <legend>Login</legend> <input type='hidden' name='submitted' id='submitted' value='1'/> <div class='short_explanation'>* required fields</div> <div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div> <div class='container'> <label for='username' >User Name *:</label><br/> <input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" /><br/> <span id='login_username_errorloc' class='error'></span> </div> <div class='container'> <label for='password' >Password *:</label><br/> <input type='password' name='password' id='password' maxlength="50" /><br/> <span id='login_password_errorloc' class='error'></span> </div> <div class='container'> <input type='submit' name='Submit' value='Submit' /> </div> membership-config.php <?PHP require_once("class.phpmailer.php"); require_once("formvalidator.php"); class FGMembersite { var $admin_email; var $from_address; var $name; var $company; var $address; var $country; var $state; var $postal; var $phone; var $fax; var $email; var $website; var $situ; var $ip; var $pwd; var $database; var $tablename; var $connection; var $rand_key; var $error_message; //-----Initialization ------- function FGMembersite() { $this->sitename = 'gosulawesi.com'; $this->rand_key = '0iQx5oBk66oVZep'; } function InitDB($host,$uname,$pwd,$database,$tablename) { $this->db_host = $host; $this->username = $uname; $this->pwd = $pwd; $this->database = $database; $this->tablename = $tablename; } function SetAdminEmail($email) { $this->admin_email = $email; } function SetWebsiteName($sitename) { $this->sitename = $sitename; } function SetRandomKey($key) { $this->rand_key = $key; } //-------Main Operations ---------------------- function RegisterUser() { if(!isset($_POST['submitted'])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; } function ConfirmUser() { if(empty($_GET['code'])||strlen($_GET['code'])<=10) { $this->HandleError("Please provide the confirm code"); return false; } $user_rec = array(); if(!$this->UpdateDBRecForConfirmation($user_rec)) { return false; } $this->SendUserWelcomeEmail($user_rec); $this->SendAdminIntimationOnRegComplete($user_rec); return true; } function Login() { if(empty($_POST['username'])) { $this->HandleError("UserName is empty!"); return false; } if(empty($_POST['password'])) { $this->HandleError("Password is empty!"); return false; } $username = trim($_POST['username']); $password = trim($_POST['password']); if(!isset($_SESSION)){ session_start(); } if(!$this->CheckLoginInDB($username,$password)) { return false; } $_SESSION[$this->GetLoginSessionVar()] = $username; return true; } function CheckLogin() { if(!isset($_SESSION)){ session_start(); } $sessionvar = $this->GetLoginSessionVar(); if(empty($_SESSION[$sessionvar])) { return false; } return true; } function UserFullName() { return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:''; } function UserEmail() { return isset($_SESSION['email_of_user'])?$_SESSION['email_of_user']:''; } function LogOut() { session_start(); $sessionvar = $this->GetLoginSessionVar(); $_SESSION[$sessionvar]=NULL; unset($_SESSION[$sessionvar]); } function EmailResetPasswordLink() { if(empty($_POST['email'])) { $this->HandleError("Email is empty!"); return false; } $user_rec = array(); if(false === $this->GetUserFromEmail($_POST['email'], $user_rec)) { return false; } if(false === $this->SendResetPasswordLink($user_rec)) { return false; } return true; } function ResetPassword() { if(empty($_GET['email'])) { $this->HandleError("Email is empty!"); return false; } if(empty($_GET['code'])) { $this->HandleError("reset code is empty!"); return false; } $email = trim($_GET['email']); $code = trim($_GET['code']); if($this->GetResetPasswordCode($email) != $code) { $this->HandleError("Bad reset code!"); return false; } $user_rec = array(); if(!$this->GetUserFromEmail($email,$user_rec)) { return false; } $new_password = $this->ResetUserPasswordInDB($user_rec); if(false === $new_password || empty($new_password)) { $this->HandleError("Error updating new password"); return false; } if(false == $this->SendNewPassword($user_rec,$new_password)) { $this->HandleError("Error sending new password"); return false; } return true; } function ChangePassword() { if(!$this->CheckLogin()) { $this->HandleError("Not logged in!"); return false; } if(empty($_POST['oldpwd'])) { $this->HandleError("Old password is empty!"); return false; } if(empty($_POST['newpwd'])) { $this->HandleError("New password is empty!"); return false; } $user_rec = array(); if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec)) { return false; } $pwd = trim($_POST['oldpwd']); if($user_rec['password'] != md5($pwd)) { $this->HandleError("The old password does not match!"); return false; } $newpwd = trim($_POST['newpwd']); if(!$this->ChangePasswordInDB($user_rec, $newpwd)) { return false; } return true; } //-------Public Helper functions ------------- function GetSelfScript() { return htmlentities($_SERVER['PHP_SELF']); } function SafeDisplay($value_name) { if(empty($_POST[$value_name])) { return''; } return htmlentities($_POST[$value_name]); } function RedirectToURL($url) { header("Location: $url"); exit; } function GetSpamTrapInputName() { return 'sp'.md5('KHGdnbvsgst'.$this->rand_key); } function GetErrorMessage() { if(empty($this->error_message)) { return ''; } $errormsg = nl2br(htmlentities($this->error_message)); return $errormsg; } //-------Private Helper functions----------- function HandleError($err) { $this->error_message .= $err."\r\n"; } function HandleDBError($err) { $this->HandleError($err."\r\n mysqlerror:".mysql_error()); } function GetFromAddress() { if(!empty($this->from_address)) { return $this->from_address; } $host = $_SERVER['SERVER_NAME']; $from ="noreply@$host"; return $from; } function GetLoginSessionVar() { $retvar = md5($this->rand_key); $retvar = 'usr_'.substr($retvar,0,10); return $retvar; } function CheckLoginInDB($username,$password) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } $username = $this->SanitizeForSQL($username); $pwdmd5 = md5($password); $qry = "Select name, ip, email from $this->tablename where username='$username' and password='$pwdmd5' "; $result = mysql_query($qry,$this->connection); if(!$result || mysql_num_rows($result) <= 0) { $this->HandleError("Error logging in. The username or password does not match"); return false; } $row = mysql_fetch_assoc($result); $_SESSION['name_of_user'] = $row['name']; $_SESSION['email_of_user'] = $row['email']; return true; } function ResetUserPasswordInDB($user_rec) { $new_password = substr(md5(uniqid()),0,10); if(false == $this->ChangePasswordInDB($user_rec,$new_password)) { return false; } return $new_password; } function ChangePasswordInDB($user_rec, $newpwd) { $newpwd = $this->SanitizeForSQL($newpwd); $qry = "Update $this->tablename Set password='".md5($newpwd)."' Where id_user=".$user_rec['id_user'].""; if(!mysql_query( $qry ,$this->connection)) { $this->HandleDBError("Error updating the password \nquery:$qry"); return false; } return true; } function GetUserFromEmail($email,&$user_rec) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } $email = $this->SanitizeForSQL($email); $result = mysql_query("Select * from $this->tablename where email='$email'",$this->connection); if(!$result || mysql_num_rows($result) <= 0) { $this->HandleError("There is no user with email: $email"); return false; } $user_rec = mysql_fetch_assoc($result); return true; } function SendUserWelcomeEmail(&$user_rec) { $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($user_rec['email'],$user_rec['name']); $mailer->Subject = "Welcome to ".$this->sitename; $mailer->From = $this->GetFromAddress(); $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n". "Welcome! Your registration with ".$this->sitename." is completed.\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending user welcome email."); return false; } return true; } function SendAdminIntimationOnRegComplete(&$user_rec) { if(empty($this->admin_email)) { return false; } $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($this->admin_email); $mailer->Subject = "Registration Completed: ".$user_rec['name']; $mailer->From = $this->GetFromAddress(); $mailer->Body ="A new user registered at ".$this->sitename."\r\n". "Name: ".$user_rec['name']."\r\n". "Email address: ".$user_rec['email']."\r\n"; if(!$mailer->Send()) { return false; } return true; } function GetResetPasswordCode($email) { return substr(md5($email.$this->sitename.$this->rand_key),0,10); } function SendResetPasswordLink($user_rec) { $email = $user_rec['email']; $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($email,$user_rec['name']); $mailer->Subject = "Your reset password request at ".$this->sitename; $mailer->From = $this->GetFromAddress(); $link = $this->GetAbsoluteURLFolder(). '/resetpwd.php?email='. urlencode($email).'&code='. urlencode($this->GetResetPasswordCode($email)); $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n". "There was a request to reset your password at ".$this->sitename."\r\n". "Please click the link below to complete the request: \r\n".$link."\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { return false; } return true; } function SendNewPassword($user_rec, $new_password) { $email = $user_rec['email']; $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($email,$user_rec['name']); $mailer->Subject = "Your new password for ".$this->sitename; $mailer->From = $this->GetFromAddress(); $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n". "Your password is reset successfully. ". "Here is your updated login:\r\n". "username:".$user_rec['username']."\r\n". "password:$new_password\r\n". "\r\n". "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { return false; } return true; } function ValidateRegistrationSubmission() { //This is a hidden input field. Humans won't fill this field. if(!empty($_POST[$this->GetSpamTrapInputName()]) ) { //The proper error is not given intentionally $this->HandleError("Automated submission prevention: case 2 failed"); return false; } $validator = new FormValidator(); $validator->addValidation("name","req","Please fill in Name"); $validator->addValidation("company","req","Please fill in Company Name"); $validator->addValidation("address","req","Please fill in Company address"); $validator->addValidation("country","req","Please fill in Country"); $validator->addValidation("state","req","Please fill in state"); $validator->addValidation("postal","req","Please fill in postal"); $validator->addValidation("phone","req","Please fill in phone"); $validator->addValidation("fax","req","Please fill in fax"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("website","req","Please fill in website"); if(!$validator->ValidateForm()) { $error=''; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { $error .= $inpname.':'.$inp_err."\n"; } $this->HandleError($error); return false; } return true; } function CollectRegistrationSubmission(&$formvars) { $formvars['name'] = $this->Sanitize($_POST['name']); $formvars['company'] = $this->Sanitize($_POST['company']); $formvars['address'] = $this->Sanitize($_POST['address']); $formvars['country'] = $this->Sanitize($_POST['country']); $formvars['state'] = $this->Sanitize($_POST['state']); $formvars['postal'] = $this->Sanitize($_POST['postal']); $formvars['phone'] = $this->Sanitize($_POST['phone']); $formvars['fax'] = $this->Sanitize($_POST['fax']); $formvars['email'] = $this->Sanitize($_POST['email']); $formvars['website'] = $this->Sanitize($_POST['website']); $formvars['situ'] = $this->Sanitize($_POST['situ']); $formvars['ip'] = $this->Sanitize($_SERVER['REMOTE_ADDR']); } function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($formvars['email'],$formvars['name']); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $mailer->Body ="Hello ".$formvars['name']."\r\n\r\n". "Thanks you for registering with ".$this->sitename."\r\n". "You will receive username and password after authentication.\r\n". "This message is computer generated. Please do not reply.\r\n". "\r\n". "Thank You,\r\n". "Vifa Holiday Group \r \n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; } function GetAbsoluteURLFolder() { $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://'; $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']); return $scriptFolder; } function SendAdminIntimationEmail(&$formvars) { if(empty($this->admin_email)) { return false; } $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($this->admin_email); $mailer->Subject = "New registration: ".$formvars['name']; $mailer->From = $this->GetFromAddress(); $mailer->Body ="A new user registered at ".$this->sitename."\r\n". "Name: ".$formvars['name']."\r\n". "Email address: ".$formvars['email']."\r\n". "UserName: ".$formvars['username']; if(!$mailer->Send()) { return false; } return true; } function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,'email')) { $this->HandleError("This email is already registered"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; } function IsFieldUnique($formvars,$fieldname) { $field_val = $this->SanitizeForSQL($formvars[$fieldname]); $qry = "select username from $this->tablename where $fieldname='".$field_val."'"; $result = mysql_query($qry,$this->connection); if($result && mysql_num_rows($result) > 0) { return false; } return true; } function DBLogin() { $this->connection = mysql_connect($this->db_host,$this->username,$this->pwd); if(!$this->connection) { $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct"); return false; } if(!mysql_select_db($this->database, $this->connection)) { $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct'); return false; } if(!mysql_query("SET NAMES 'UTF8'",$this->connection)) { $this->HandleDBError('Error setting utf8 encoding'); return false; } return true; } function Ensuretable() { $result = mysql_query("SHOW COLUMNS FROM $this->tablename"); if(!$result || mysql_num_rows($result) <= 0) { return $this->CreateTable(); } return true; } function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR( 128 ) NOT NULL ,". "company VARCHAR( 64 ) NOT NULL ,". "address VARCHAR( 16 ) NOT NULL ,". "country VARCHAR( 16 ) NOT NULL ,". "state VARCHAR( 32 ) NOT NULL ,". "postal VARCHAR(32) NOT NULL ,". "phone VARCHAR(32) NOT NULL ,". "fax VARCHAR(32) NOT NULL ,". "email VARCHAR(32) NOT NULL ,". "website VARCHAR(32) NOT NULL ,". "situ VARCHAR(32) NOT NULL ,". "ip VARCHAR(50) NOT NULL ,". "PRIMARY KEY ( id_user )". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; } function InsertIntoDB(&$formvars) { $insert_query = 'insert into '.$this->tablename.'( name, company, address, country, state, postal, phone, fax, email, website, situ, ip ) values ( "' . $this->SanitizeForSQL($formvars['name']) . '", "' . $this->SanitizeForSQL($formvars['company']) . '", "' . $this->SanitizeForSQL($formvars['address']) . '", "' . $this->SanitizeForSQL($formvars['country']) . '", "' . $this->SanitizeForSQL($formvars['state']) . '", "' . $this->SanitizeForSQL($formvars['postal']) . '", "' . $this->SanitizeForSQL($formvars['phone']) . '", "' . $this->SanitizeForSQL($formvars['fax']) . '", "' . $this->SanitizeForSQL($formvars['email']) . '", "' . $this->SanitizeForSQL($formvars['website']) . '", "' . $this->SanitizeForSQL($formvars['situ']) . '", "' . $this->SanitizeForSQL($formvars['ip']) . '" )'; if(!mysql_query( $insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; } function SanitizeForSQL($str) { if( function_exists( "mysql_real_escape_string" ) ) { $ret_str = mysql_real_escape_string( $str ); } else { $ret_str = addslashes( $str ); } return $ret_str; } /* Sanitize() function removes any potential threat from the data submitted. Prevents email injections or any other hacker attempts. if $remove_nl is true, newline chracters are removed from the input. */ function Sanitize($str,$remove_nl=true) { $str = $this->StripSlashes($str); if($remove_nl) { $injections = array('/(\n+)/i', '/(\r+)/i', '/(\t+)/i', '/(%0A+)/i', '/(%0D+)/i', '/(%08+)/i', '/(%09+)/i' ); $str = preg_replace($injections,'',$str); } return $str; } function StripSlashes($str) { if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return $str; } } ?> Thanks so much and apologize for my bad englsih..
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.