PHP - When I Click Login It Says Error
When i press login i get Fatal error: Call to a member function query() on a non-object in /home/a5347792/public_html/login.php on line 15
<?php $dbConnection['username'] = "root"; $dbConnection['password'] = ""; $dbConnection['host'] = "localhost"; $dbConnection['db'] = "joke"; if(isset($_POST['rbLgn'])) { $login = true; if(isset($_POST['username'])) { $username = $_POST['username']; } if(isset($_POST['password'])) { $password = $_POST['password']; } if(isset($username) && isset($password)) { $query = $db->query("SELECT * FROM `users` WHERE `username`='{$username}' AND `password`='{$password}' LIMIT 1"); if($query->num_rows > 0) { echo "User found - logging in."; } else { echo "User not found, credentials: " . $username . " | " . $password; } } } ?> Edited by mac_gyver, 25 October 2014 - 10:21 AM. code tags when posting code please Similar TutorialsCan someoneplease help, I need to setup an error page like IF Username and Password are wrong then show an error also if there is no username or password in the fields and I just click LOGIN, I get a blank page?! Can someone please help me here or point me to a relevant tutorial? thanks here is my page: http://www.retroandvintage.co.uk/default.php here is my code: Code: [Select] <?php session_start(); include_once("config.php"); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); /* Login script: This script does the following: Checks that the user is NOT already logged in - if they are they are redirected to the members page by the 'checkLoggedIn()' function. Checks if the login form has been submitted - if so, the 'login' and 'password' fields are checked to ensure they are of the correct format and length. If there are any problems here an error is added to the $messages array and then the script executes the 'doIndex()' function - this function basically outputs the main 'index' page for this script - ie the login form. If there are no problems with the previous step, the 'login' and 'password' field data is passed to the 'checkPass' function to check that an entry exists in the 'users' table for that login/password pair. If nothing is returned from the 'checkPass()' function, an error is added to the $messages array and the 'doIndex()' function is called as above. If a row of data is returned from the 'users' table, the data is passed to the 'cleanMemberSession()' function - which initializes session variables and logs the user in. The user is then forwarded to the members page. If the form hasn't yet been submitted, then the 'doIndex()' function is called and the login page is displayed. */ // Check user not logged in already: checkLoggedIn("no"); // Page title: $title="Member Login Page"; // if $submit variable set, login info submitted: if(isset($_POST["submit"])) { // // Check fields were filled in // // login must be between 4 and 15 chars containing alphanumeric chars only: field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 4, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 4, 15); // if there are $messages, errors were found in validating form data // show the index page (where the messages will be displayed): if($messages){ doIndex(); // note we have to explicity 'exit' from the script, otherwise // the lines below will be processed: exit; } // OK if we got this far the form field data was of the right format; // now check the user/pass pair match those stored in the db: /* If checkPass() is successful (ie the login and password are ok), then $row contains an array of data containing the login name and password of the user. If checkPass() is unsuccessful however, $row will simply contain the value 'false' - and so in that case an error message is stored in the $messages array which will be displayed to the user. */ if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { // login/passwd string not correct, create an error message: $messages[]="Incorrect login/password, try again"; } /* If there are error $messages, errors were found in validating form data above. Call the 'doIndex()' function (which displays the login form) and exit. */ if($messages){ doIndex(); exit; } /* If we got to this point, there were no errors - start a session using the info returned from the db: */ cleanMemberSession($row["rsUser"], $row["rsPass"]); // and finally forward user to members page (populating the session id in the URL): header("Location: main.php"); } else { // The login form wasn't filled out yet, display the login form for the user to fill in: doIndex(); } /* This function displays the default 'index' page for this script. This consists of just a simple login form for the user to submit their username and password. */ function doIndex() { /* Import the global $messages array. If any errors were detected above, they will be stored in the $messages array: */ global $messages; /* also import the $title for the page - note you can normally just declare all globals on one line - ie: global $messages, $title; */ global $title; } // drop out of PHP mode to display the plain HTML: ?> <!doctype html> <html> <head> <title>List of Pubs and Bars in the UK</title> <meta name="description" content="Pubs and bars in the UK, nightlife for food and drink" /> <meta name="keywords" content="Pubs, bars, List, uk, nightlife, drinking, drinks, beer, lager, food" /> <meta name="Content-Language" content="en-gb" /> <meta name="robots" content="FOLLOW,INDEX" /> <meta name="revisit-after" content="2 days" /> <meta name="copyright" content="jbiddulph.com" /> <meta name="author" content="John Biddulph - Professional web site design and development in the south of england mainly worthing and brighton" /> <meta name="distribution" content="Global" /> <meta name="resource-type" content="document" /> <link rel="stylesheet" type="text/css" href="css/reset.css" /> <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.6.custom.css" title="default" /> <link rel="alternate stylesheet" type="text/css" href="css/south-street/jquery-ui-1.8.6.custom.css" title="1" /> <link rel="alternate stylesheet" type="text/css" href="css/redmond/jquery-ui-1.8.6.custom.css" title="2" /> <script type="text/javascript" src="js/stylechanger.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script> <script type="text/javascript"> $(function(){ // Accordion $("#accordion").accordion({ header: "h3" }); // Tabs $('#tabs').tabs(); // Dialog $('#dialog').dialog({ autoOpen: false, width: 600, buttons: { "Ok": function() { $(this).dialog("close"); }, "Cancel": function() { $(this).dialog("close"); } } }); // Dialog Link $('#dialog_link').click(function(){ $('#dialog').dialog('open'); return false; }); // Datepicker $('#datepicker').datepicker({ inline: true }); //hover states on the static widgets $('#dialog_link, ul#icons li').hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ); }); </script> <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> </head> <body> <?php if($messages) { displayErrors($messages); }?> <header> <div id="title"> <h1>My Pub Space <a href="#" onClick="setActiveStyleSheet('default'); return false;"><img src="images/0.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('1'); return false;"><img src="images/1.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('2'); return false;"><img src="images/2.gif" width="15" height="15" border="0" alt="css style" /></a> <span> <form method="post" class="textbox" action="search.php"> Town/City: <input type="text" size="26" class="searchbox" value="" name="rsTown" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="images/upArrow.png" style="position: relative; top: -36px; left: 105px; z-index:1;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> <input type="image" src="images/go.png" height="30" with="30" value="GO" /> </form> </span> </h1> </div> </header> <nav> <ul> <li class="selected"><a href="default.php">Home</a></li> <li><a href="#">Pubs</a></li> <li><a href="#">Members</a></li> <li><a href="#">Events</a></li> <li><a href="register.php">Register</a></li> </ul> </nav> <section id="intro"> <header> <h2>Your social guide to going down the pub, online!</h2> </header> <p>Stuck in town with nowhere to go? Not sure if up the road or down the street is best? Need to be somewhere warm, cosy and friendly. Need a drink?....<br />You've come to the right place, mypubspace has it all!</p> <img src="images/pub.jpg" alt="pub" /> </section> <div id="content"> <div id="mainContent"> <section> <article class="blogPost"> <header> <h2>Pubs and Bars UK Listing</h2> </header> <?php $tableName="pubs"; $targetpage = "default.php"; $limit = 20; $query = "SELECT COUNT(*) as num FROM $tableName"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages['num']; $stages = 3; $page = mysql_escape_string($_REQUEST['page']); if( isset($_REQUEST['page']) && ctype_digit($_REQUEST['page']) ) { $page = (int) $_GET['page']; $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM $tableName LIMIT $start, $limit"; $result = mysql_query($query1); // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <div id="accordion"> <?php while($row = mysql_fetch_array($result)) { echo '<div><h3><a href=\"#\">'.$row['rsPubName'].'</a></h3><div>'.$row['rsAddress'].'<br />'.$row['rsTown'].', '.$row['rsCounty'].'<br />'.$row['rsPostCode'].'<br /><br />Region: '.$row['Region'].'<br /><br />Telephone: '.$row['rsTel'].'</div></div>'; } ?> </div> </article> </section> </div> <aside> <section> <header> <h3>Members Login Area</h3> </header> <form method="post" class="textbox" action="<?php print $_SERVER["PHP_SELF"]; ?>"> Username: <br /> <input type="text" class="textbox" name="rsUser" value="<?php print isset($_POST["rsUser"]) ? $_POST["rsUser"] : "" ; ?>"> Password: <br /> <input type="password" class="textbox" name="rsPass"> <br /> <br /> <input name="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="submit" value="Login"> <br /> </form> <ul> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="register.php">Sign up</a></span></button></li> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="forgot.php">Forgot Password</a></span></button></li> </ul> </section> <section> <header> <h3>Quick Search</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </aside> </div> <footer> <div> <section id="about"> <header> <h3>About</h3> </header> <p>My Pub Space is one of the largest and newest UK Pubs and Bars Listing sites online. It is not just a list of pubs, we have added a touch of interactive social pubbing experience online! Once registered, you can view information on pubs in your area, write reviews, organise your evenings out!</p> </section> <section id="blogroll"> <header> <h3>Links</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> <section id="popular"> <header> <h3>Popular</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </div> </footer> </body> </html> I keep getting an error code when running my php, it states: Parse error: syntax error, unexpected $end in W:\www\blog\login.php on line 33 Line 33 is </html> Code: [Select] <?php mysql_connect ("localhost", "root", ""); mysql_select_db("blog"); ?> <html> <head> <title>Login</title> </head> <body> <?php if(isset($_POST['submit'])){ $name = $_POST['name']; $pass = $_POST['password']; $result = mysql_query("SELECT * FROM users WHERE name='$name' AND pass='$pass'"); $num = mysql_num_rows($result); if($num == 0){ echo "Bad login, go <a href='login.php'>back</a>"; }else{ session_start(); $SESSION ['name'] = $name; header("Location: admin.php"); } ?> <form action='login.php' method='post'> Username: <input type='text' name='name' /><br /> Password: <input type='password' name='password' /><br /> <input type='submit' name='sumbit' value='Login!' /> </form> </body> </html>Can any one advise me whats wrong? I have dynamic images that have the "Like" button, it's basically like a wishlist. The way I want it to work is that when a user is not logged in, the 'Like' button will navigate them to a login popup (which I already made). I've been hacking at this for about 4 hours now.. Throwing the towel in! Any feedback or suggestions please: I'm calling a function like so: <!--START :: Run report and update records --> <p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!--<input type="hidden" name="post_var">--> <input type="submit" name="runUpdate" value="Run Update"> </form> </p> <?php if (isset($_POST['runUpdate'])) { updateRecords(); }; ?> <!--END :: Run report and update records --> Here are the function details: <?php function updateRecords() { // START :: Query to replace matches mysql_query("UPDATE orig_codes_1a AS a JOIN old_and_new_codes_1a AS b ON concat(a.orig_code_1, a.orig_code_2) = concat(b.old_code_1, b.old_code_2) SET a.orig_code_1 = b.new_code_1, a.orig_code_2 = b.new_code_2") or die(mysql_error()); // END :: Query to replace matches echo "<p><table border='1' cellpadding='3' width='100%'>"; echo "<tr> <th>Updated Code 1</th> <th>Updated Code 2</th> </tr>"; // START :: While loop - keeps getting the next row until there are no more to get while($row = mysql_fetch_array($result)) { //START :: If to find matching criteria class it w/ bg color if ($row['orig_code_1'] < '10000') { $changedClass = "changedClassCSS"; } else { $changedClass = ""; }; //END :: If to find matching criteria class it w/ bg color //START :: Print out the contents of each row into a table echo "<tr><td class=\"$changedClass\">"; echo $row['orig_code_1']; echo "</td><td class=\"$changedClass\">"; echo $row['orig_code_2']; echo "</td>"; } echo "</table></p>"; //END :: Print out the contents of each row into a table // START // //echo "$tableOutput"; // END // }; ?> I'm getting this error: Notice: Undefined variable: result in C:\wamp\www\php_practice\apps\records_updater_2\functions.php on line 27 Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\wamp\www\php_practice\apps\records_updater_2\functions.php on line 27 Now what I don't understand is 1) This script works fine (even though the $result is not defined) when all of the code is in one file not being called as a function. And 2) Why the hell would it work as in number 1?? Please please please tell me what I am doing wrong here! ok so when user get there email or password wrong are they just submit with filling anything out they go to login.php?login_failed but it gives me This webpage has a redirect loop Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects. Code: [Select] <?php session_start(); $email = $_SESSION['email']; ?> <?php $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); if(!empty($email) && isset($email) &&!empty($password) && isset($password)){ $password = md5("$password"); require "includes/init/db_con.php"; $query = mysql_query("SELECT * FROM users WHERE email = '$email'"); $numrows = mysql_num_rows($query); if($numrows != 0){ $row = mysql_fetch_assoc($query); $dbemail = $row ['email']; $dbpassword = $row ['password']; if($dbemail === $email && $dbpassword === $password){ $_SESSION['email'] = $dbemail; header("location: http://localhost/control/home.php"); }else { header('Location: login.php?login_failed'); } }else { header('Location: login.php?login_failed'); } }else { header('Location: login.php?login_failed'); } ?> <?php require "includes/overall/header.php";?> <?php if($_GET['login_failed']){ echo "Login Box will appear with messages"; } ?> <?php require "includes/overall/footer.php";?> Hi
I'm getting this error but i'm sure the file is there, this is my code where i'm having this problem
elseif($_POST["page"] == "users_login") { $user_utilizador = trim(strip_tags($_POST['email'])); $user_password = trim(strip_tags($_POST['passwd'])); $encrypted_md5_password = md5($user_password); $validate_user_information = mysql_query("select * from `utilizador` where `utilizador` = '".mysql_real_escape_string($user_utilizador)."' and `password` = '".mysql_real_escape_string($encrypted_md5_password)."'"); echo $validate_user_information; if(mysql_num_rows($validate_user_information) == 1) { $get_user_information = mysql_fetch_array($validate_user_information); $_SESSION["VALID_USER_ID"] = $user_utilizador; $_SESSION["USER_FULLNAME"] = strip_tags($get_user_information["nome"]); echo 'index.php?uid='.$_SESSION["USER_FULLNAME"].'&'; echo 'login_process_completed_successfully=yes'; } else { echo '<br><div class="info">Desculpe, a informação fornecida está errada. Corrije-a por favor. Obrigado.</div><br>'; } }So after the login process it should open the index.php I have try with header(Location: index,php) and the details are displayed in the same page as the login... any help please? Thanks Hey php masters ! i ran into a problem while making my login page, im new to php so please dont rage at me the code that i think gives the problem is this: if ($numrows!=0) { while ($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } if ($username==$dbusername&&$password==$dbpassword) { echo "du er logget ind $username" } else echo "Adgangskoden er Forkert"; } else die("Denne burger findes ikke"); } else die("Angiv venligst brugernavn og adgangskode"); ?> Hope you can help me - MinG Hi, well i don't get an error from PHP but it says the username or password is incorrect
Login script
<?php require 'connect.php'; error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); ini_set('memory_limit', '-1'); include 'footer.php'; if(isset($_POST['submit'])) { session_start(); if(!$_POST['username'] OR !$_POST['password']) { echo "Please make sure you enter both a username and password!"; exit(); } $username = trim($_POST['username']); $password = trim($_POST['password']); $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); $stmt = $conn->prepare("SELECT username,password,user_level,active FROM usrs_usr WHERE username=? AND password=?"); $stmt->bind_param("ss", $username, $password); $stmt->execute(); $row = $stmt->fetch(); $userlevel = $row['user_level']; $active = $row['active']; if($stmt->num_rows > 0) { if($row['user_level'] == 1) { $_SESSION['user_level'] = 1; $_SESSION['active'] = 1; $_SESSION['loggedIn'] = 1; echo "<meta http-equiv='refresh' content=0;admin.php>"; exit(); } else if($row['user_level'] == -1) { $_SESSION['user_level'] = -1; $_SESSION['active'] = 0; $_SESSION['loggedIn'] = 0; echo "<meta http-equiv='refresh' content=0;banned.php>"; exit(); } $_SESSION['user_level'] = 0; $_SESSION['active'] = 1; $_SESSION['loggedIn'] = 1; echo "<meta http-equiv='refresh' content=0;index.php>"; exit(); } else { die("#~ Username or password is incorrect ~#"); } } ?> Hello! I started to have problems on my admin login page. I see 3 warnings and below that, my login (but is not working now). Here´s what you see on https://www.bariloche.esp.br/administrator/login https://fonts.googleapis.com A PHP Error was encounteredSeverity: Warning Message: session_start(): Cannot send session cookie - headers already sent by (output started at /home/bariloch/public_html/administrator/index.php:2) Filename: Session/Session.php Line Number: 143 Backtrace:
File: /home/bariloch/public_html/administrator/application/controllers/Login.php
File: /home/bariloch/public_html/administrator/index.php Severity: Warning Message: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/bariloch/public_html/administrator/index.php:2) Filename: Session/Session.php Line Number: 143 Backtrace:
File: /home/bariloch/public_html/administrator/application/controllers/Login.php
File: /home/bariloch/public_html/administrator/index.php Severity: Warning Message: Cannot modify header information - headers already sent by (output started at /home/bariloch/public_html/administrator/index.php:2) Filename: helpers/url_helper.php Line Number: 564 Backtrace:
File: /home/bariloch/public_html/administrator/application/views/login.php
File: /home/bariloch/public_html/administrator/application/controllers/Login.php
File: /home/bariloch/public_html/administrator/index.php I don't know how to solve this error;
Parse error: syntax error, unexpected '$db' (T_VARIABLE)
code:
I had a success page redirect after the login...but the login happens even if the username and password is not entered. you can check it in colonialcasa.org here's the code for the login.php page ( i have obviously changed the server name, database and password for privacy reasons ) <? /*simple checking of the data*/ if(isset($_POST['login']) & isset($_POST['pass'])) { /*Connection to database logindb using your login name and password*/ $db=mysql_connect('servername','login','password') or die(mysql_error()); mysql_select_db('mpahost_logindb'); /*additional data checking and striping*/ $_POST['login']=mysql_real_escape_string(strip_tags(trim($_POST['login']))); $_POST['pass']=mysql_real_escape_string(strip_tags(trim($_POST['pass']))); $q=mysql_query("SELECT * FROM login WHERE login='{$_POST['login']}' AND pass='{$_POST['pass']}'",$db) or die(mysql_error()); /*If there is a matching row*/ if(mysql_num_rows($q) > 0) { $_SESSION['login'] = $_POST['login']; $login='Welcome back '.$_SESSION['login']; } else { $login= 'Wrong login or password'; } mysql_close($db); } /*Use of Sessions*/ if(!session_id()) header("Location: advocates.html"); // success page. put the URL you want header("Cache-control: private"); //avoid an IE6 bug (keep this line on top of the page) $login='NO data sent'; //you may echo the data anywhere in the file echo $login; ?> I have created a PHP & MySql login but its not working. If I put the right email/password still its showing "Wrong Username or Password" everytime. Bacause I'm beginner to this I don't really know how to solve this issue. Thanks in advance. Here is my coding <?php // Start PHP session at the beginning session_start(); // Create database connection using config file include_once("connection.php"); // If form submitted, collect email and password from form if (isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; // Check if a user exists with given username & password $result = mysqli_query($conn, "select 'Email', 'Password' from tblstudent where Email='$email' and Password='$password'"); // Count the number of user/rows returned by query $user_matched = mysqli_num_rows($result); // Check If user matched/exist, store user email in session and redirect to sample page-1 if ($user_matched > 0) { $_SESSION["email"] = $email; header("location: welcome.php"); } else { echo "User email or password is not matched <br/><br/>"; } } ?> Edited May 4 by Barand code tags added Hi, Im using the code below to check a users username and password is ligit before adding their username to their session. <?php $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("hiddenbid", $con); $username = mysql_real_escape_string($_POST['username']); $password = md5($_POST['password']); $mysql = mysql_query("SELECT * FROM users WHERE name = '{$username}' AND password = '{$password}'"); if(mysql_num_rows($mysql)=1){ $_SESSION['USERID'] = $username; print "<b>Welcome</b>, you are signed in as " . $_SESSION['USERID'] . "."; print "<br /><br />Redirecting..."; header ("location:index.php"); } else{ header ("location:signin.php"); } ?> Anyway, it doesnt work as I get the following error: Fatal error: Can't use function return value in write context in C:\Program Files\Abyss Web Server\htdocs\signinconfirmer.php on line 35 Any ideas what is causing this please? Also can I add a pause after the redirect message before it takes the user to the index.php page? Thanks in advance. Hi all, I've got a website, which used to work ... I have a login script which did log each user in fine, but now for some odd reason its not loggin them in, I've looked over the script quite a few times but carnt see why its not loggin then it as it use to. <?php session_start(); include_once"includes/config.php"; if (strip_tags($_GET['logout']) == "yes"){ session_destroy(); }elseif (isset($_SESSION['username'])){ header("Location: index2.php"); exit(); } if ($_POST['Submit'] && strip_tags($_POST['username']) && strip_tags($_POST['password'])){ $username = mysql_real_escape_string(addslashes(strip_tags($_POST['username']))); $password = md5(addslashes(strip_tags($_POST['password']))); $select = mysql_query("SELECT * FROM users WHERE online > '$timenow' ORDER by rank desc"); $num = mysql_num_rows($select); $date = gmdate('Y-m-d h:i:s'); $ip = $REMOTE_ADDR; ///check INFO $sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1"); $login_check = mysql_num_rows($sql); $inf = mysql_fetch_object($sql); if ($login_check == "0"){ $message="<table width='30%' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center'>Error</td> </tr> <tr> <td align='center'>You could not be logged in.</td> </tr> <table><br />"; }elseif ($login_check != "0"){ if ($login_check > "0"){ if ($inf->status == "Banned"){ $encoded=md5(strtolower($username)); header("Location: banned.php?banned=$username&encoded=$encoded"); exit(); } session_register('username'); $_SESSION['username'] = $inf->username; $timestamp = time()+20; $get = mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1"); $got = mysql_fetch_object($get); $loginnumber = $got->loginnumber+1; mysql_query("UPDATE users SET online='$timestamp' WHERE username='$username'"); mysql_query("UPDATE users SET lastlogin='$date' WHERE username='$username'"); mysql_query("UPDATE users SET l_ip='$ip' WHERE username='$username'"); mysql_query("UPDATE users SET loginnumber='$loginnumber' WHERE username='$username'"); header("Location: index2.php"); } else { $message= "<table width='30%' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center'>Error</td> </tr> <tr> <td align='center'>You could not be logged in.</td> </tr> <table><br />"; }}} ?> <html> <head> <title>Login </title> <link href='style.css' rel='stylesheet' type='text/css'> </head> <body class='body'> <form action='' method='post' name='form1'> <?php echo ($message); ?> <table width='702' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center' colspan='2'>Welcome To Speed-Drive</td> </tr> <tr> <td align='center' colspan='2'><img src='images/banner.png'></td> </tr> <tr> <td class='header' align='center' colspan='2'>Speed-drive Login</td> </tr> <tr> <td width='50%' align='right'>Username:</td><td width='50%' align='left'><input name="username" class='input' type="text" maxlength="15" id="username"></td> </tr> <tr> <td width='50%' align='right'>Password:</td><td width='50%' align='left'><input name="password" class='input' type="password" maxlength="30" id="password"></td> </tr> <tr> <td colspan='2' align='center' class='omg'><input type="submit" class='button' name="Submit" value="Submit"></td> </tr> <tr> <td class='header' align='center' colspan='2'>Help</td> </tr> <tr> <td align='center' colspan='2'><a href='register.php'>Register</a> .|. <a href='lost.php'>Lost Password</a> .|. <a href='tos.php'>TOS</a></td> </tr> <tr> <td align='center' colspan='2'><br /><font color='pink'><strong><h3>This website is currently <u></font><font color='red'>closed</font><font color='pink'></u>!<br /><br />You will <u></font><font color='red'>Not</font><font color='pink'></u> be able to Register untill the website is completed.<br /><br /></font></h3> Thank you for understanding.</strong></td> </tr> </table> </form> </body> </html> Is there a small error in the script or is the Script fine? Thanks for all the help given. Code: [Select] <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $username = $_POST['username']; $_POST['pass'] = md5($_POST['pass']); $password = $_POST['pass']; if (isset($_POST["submit"])) { $log1 = "SELECT * FROM regis WHERE username = '$username'"; $login1 = mysql_query($log1); $log2 = "SELECT * FROM regis WHERE password = '$password'"; $login2 = mysql_query($log2); $log3 = "SELECT * FROM regis WHERE username = '$username' AND password = '$password'"; $login3 = mysql_query($log3); $row = mysql_fetch_array($login3); $number = mysql_num_rows($login3); if($login1==FALSE) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('This.$username.is not available.')</SCRIPT>"); } if($login2==FALSE) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('This.$password.is incorrect.')</SCRIPT>"); } if ($number == 0) { print "This user does not exist in our database. <a href=registration.php><input type='button' value='Register'></a>"; } if ($number > 0) { $_SESSION['username'] = $row['username']; $_SESSION['password'] = $row['password']; $_SESSION['userlevel'] = $row['userlevel']; $_SESSION['is_logged_in'] = 1; if($_SESSION['userlevel']==1) { $_SESSION['is_logged_in'] = 1; header("Location: form2.php"); } else if($_SESSION['userlevel']== 0) { $_SESSION['is_logged_in'] = 1; header("Location: form3.php"); } } } else { ?> <html> <head> <script type="text/javascript"> function a() { var x = document.login.username.value; var y = document.login.pass.value; if(x==""&& y=="") { alert("Please insert all message!"); return false; } if(x=="") { alert("Please insert an username!"); return false; } if(y=="") { alert("Please insert an password!"); return false; } } </script> </head> <body> <center> <table border="0" align="center"> <form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return a()"> <tr><td colspan=2><center><h1>Login</h1></center></td></tr> <tr><td>Username:<input type="text" name="username" maxlength="40"></td></tr> <tr><td>Password:<input type="password" name="pass" maxlength="50"></td></tr> <tr align=center><td><input type="button" value="Register" ONCLICK="window.location.href='registration.php'"></a> <input type="submit" name="submit" value="Login"></td> </tr> </form> </center> </body> <?php } ?> this is login code as im want it show the error if i put any username or password error but instead it will directly show this error "if ($number == 0) { print "This user does not exist in our database. <a href=registration.php><input type='button' value='Register'></a>"; } " but im want to show this if($login1==FALSE) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('This.$username.is not available.')</SCRIPT>"); } if($login2==FALSE) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('This.$password.is incorrect.')</SCRIPT>"); } error first. may i know which code or if statement im put wrong Hi There I have a simple cms system that I have built but for some reason the login script wont let me login to the cms. Strange thing is the script seems to works on the original database but when I changed the details to a new db it doesnt work. I have made the necessary changes for the connecting to the db etc but it just wont let me login. Can anyone help The url is drmonlinemarketing.com/cms2/loginadmin.php try login with username demo password test thanks shalli Hi Everyone, Just wondered if someone could quickly help me out, im building a simple login system for my website but having a little bit of trouble, the error i keep getting is: Quote Cannot modify header information - headers already sent by (output started at /home/sites/cuju8.com/public_html/include.php:18) in /home/sites/cuju8.com/public_html/login.php on line 12 I have done some research but cant find the answer to this, my login script is as follows: Code: [Select] <?php require_once('include.php'); $error = ''; $form = $_POST['submit']; $email = $_POST['email']; $password = $_POST['password']; if( isset($form) ) { if( isset($email) && isset($password) && $email !== '' && $password !== '' ) { $sql = mysql_query("SELECT * FROM `usersystem` WHERE email='$email' and password='$password';"); if( mysql_num_rows($sql) != 0 ) { //success $_SESSION['logged-in'] = true; [b]header('Location: members.php');[/b] exit; } else { $error = "Incorrect login info"; } } else { $error = 'All information is not filled out correctly';} } ?> I think its the header location code thats causing the problem but im not sure where to move it too. If anyone could help i would really appreciate it. Cheers When I log in on my web-site it takes me to a php login-check page This is the error code that I am getting; Quote Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\xampp\htdocs\login-check.php on line 26 This is the php code that i am using; Code: [Select] <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="deliverpizza"; // Database name $tbl_name="customer, admin, staff"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $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 $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_privelage.php"); } else { } ?> I have tried to create a basic login form. When I enter the username and password I get this error Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in login.php on line 10 Code: [Select] <?php require("connection.php"); if($_SERVER["REQUEST_METHOD"] == "POST") { $username=mysql_real_escape_string($_POST['username']); $password=mysql_real_escape_string($_POST['password']); $password=md5($password); $sql="SELECT id FROM user WHERE username='$username' and password='$password'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1) { header("location: dashboard.php"); } else { $error="Invalid username or password"; } } ?> <form action="login.php" method="POST"> <table class="ltext"> <tr> <td> Username </td> <td> <input type="text" name="usename" class="input" /> </td> </tr> <tr> <td> Password </td> <td> <input type="password" name="password" class="input" /> </td> </tr> </tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <input type="submit" value="Login" name="submit" class="input" /> <input type="reset" value="Clear" name="clear" class="input" /> </td> </tr> </table> </form> I can't figure out why I am getting that error message does anyone have any ideas? |