PHP - Handling Errors And Invalid Login
Hi,
I've inherited some html/php code (lucky me) and it's been years since i've played with it so I'm quite rusty. Anyway, I have a fairly bog standard login process and wish to simply display some text on the login page if the login detail is invalid and possibly log the error to a log file too. here's the index.php file...the login stuff is at the bottom Code: [Select] <?php $dir = dirname(__FILE__); require_once "$dir/ot/ot.php"; ot::include_view('header', array('account' => null)) ?> <html> <head> <title>Welcome to ....</title> </head> <body style="font-size: 14pt; font-family=verdana;"> <div><img src="OTLogo1.bmp"/><h1> Welcome to ...</h1> </div> <?php if (!empty($account)): ?> <div style="border-bottom: 1px dotted #AAA; padding-bottom: 2px; margin-bottom: 10px;"> <div style="float: left"> <?php $mtime = (int)@file_get_contents(otDB_DIR."/updated"); $date = date("d/m/Y", $mtime); $time = date("G:i", $mtime); if ($mtime > 0) { echo "Last Updated $date at $time"; } ?> </div> <div style="float: right">Welcome, <?php echo $account->email;?> - <a href="?page=home">Home</a> - <?php ot::include_view('logout_link')?></div> <div style="clear: both"></div> </div> <?php if (ot::is_admin()) { ot::include_view('admin_page'); } else { ot::include_view('user_page'); } ?> <?php else: ?> <p>Please login below.</p> <?php ot::include_view('login_form')?> <?php endif; ?> </body> </html> here's login_form.php Code: [Select] <form action='<?php echo $_SERVER['REQUEST_URI']?>' method='post' > <fieldset> <legend>Login</legend> <p>Email:<br/><input type='text' name='email' /></p> <p>Password:<br/><input type='password' name='pwd' /></p> <!-- <p><input type='submit' name='do_login' value='Login' /> <input type='submit' name='do_reset_password' value='Reset Password' /></p> --> <p><input type='submit' name='do_login' value='Login'/> </p> </fieldset> </form> and here's the function do_login (contained in ot.php..a php function file) Code: [Select] public static function do_login(&$err="") { $adb = ot::db('account'); $e = self::post('email'); $p = self::post('pwd', '', false); if (self::post('do_login') && $e && $p) { $ao = self::account_from('email', $e); if ($ao) { if (self::validate_login($e, $p, $ao)) { $_SESSION['id'] = $ao->id; return $ao; } } $err = "Invalid email or password"; return false; } } I'm unclear if the do_login fails as to how that ($err) is fed back to the web pages. Any assistance would be greatly appreciated. Similar TutorialsThis doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) Whats the best way to handle database errors. I been using ob_start() stuff to run the code and if a database connection error occurs an variable $error turns to 1 and it displays the error code instead of the normal page that should be displayed when no errors occur. It works but I want to know if there is any better way to manage a db connection error while running a script. Also, how do you manage a problem when like 3 queries are ran to setup a new user account and the last one fails because the db connection drops or something, how would you go about handling a 2/3 query successful? I'm really stuck on how to manage errors if a db connection fails after the first connection is successful. I have an application that loads several xml files, and then outputs some of the data from the file. The problem is that every once in a while, the service that provides the xml file does maintenance (or has an error in the file), and my application gives a "Fatal error: Call to a member function children() on a non-object in..."
I would like to handle the error differently, by displaying "unavailable" instead of the error. I know that this is usually not the appropriate way of handling errors, because there is a reason for a fatal error.
Any ideas on how to appropriately handle this error?
// Node 217 (GGB) $xml = simplexml_load_file("http://services.my511.org/traffic/API_KEY_REMOVED_FOR_EXAMPLE"); foreach($xml->children() as $traveltime) { $ggb = "$traveltime->currentTravelTime"; } echo "GGB:" , $ggb , " Minutes"; I am writing an API for clients to use to integrate with an server API I have written and it will be used in a variety of different environments and used by people with varying coding styles (hopefully), I was just wondering how I should handle errors? I was going to throw an exception, but what if people don't use a try / catch ? Should I return false to allow them to handle an error? private function _request($uri) { if ( ini_get('allow_url_fopen') ) { $this->_response = file_get_contents($uri); return false; } if ( function_exists('curl_init') ) { $ch = curl_init($uri); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $this->_response = curl_exec($ch); curl_close($ch); return false; } throw new Exception('Allow URL fopen disabled and cURL disabled'); } Also, any scenarios where the above would fail to return a result (apart from the obvious lol) Thanks, Andy Hi I have a login script that allows the user to store info into a cookie if he doesn't want to be bothered by entering is password and other login credentials. however I read somewhere that's not smart to leave a cookie with your pass on your pc. Therefore I want to ask your opionion on how to adapt the below mentioned script so that's safe to store delicate information in a cookie Code: [Select] <?php include("config.php"); if(isset($_SESSION['user_id'])) { // Inloggen correct, updaten laatst actief in db $sql = "UPDATE gebruikers SET lastactive=NOW() WHERE id='".$_SESSION['user_id']."'"; mysql_query($sql); }else{ if(isset($_COOKIE['user_id'])) { $sql = "SELECT wachtwoord,status FROM gebruikers WHERE id='".$_COOKIE['user_id']."'"; $query = mysql_query($sql); $rij = mysql_fetch_object($query); $dbpass = htmlspecialchars($rij->wachtwoord); $dbstatus = htmlspecialchars($rij->status); if($dbpass == $_COOKIE['user_password']) { $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['user_status'] = $dbstatus; }else{ setcookie("user_id", "", time() - 3600); setcookie("user_password", "", time() - 3600); echo "Cookies incorrect. Cookies verwijderd."; header("Location: inloggen.php"); } }else{ header("Location: inloggen.php"); } } ?> this is the concerning table Code: [Select] CREATE TABLE IF NOT EXISTS `gebruikers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `naam` varchar(50) NOT NULL DEFAULT '', `wachtwoord` varchar(50) NOT NULL DEFAULT '', `status` char(1) NOT NULL DEFAULT '0', `email` varchar(100) NOT NULL DEFAULT '', `actief` char(1) NOT NULL DEFAULT '0', `actcode` varchar(15) NOT NULL DEFAULT '', `lastactive` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; Code: [Select] <?php ob_start(); session_start(); require_once ("functions.php"); $returnurl = urlencode(isset($_GET["returnurl"])?$_GET["returnurl"]:""); if($returnurl == "") $returnurl = urlencode(isset($_POST["returnurl"])?$_POST["returnurl"]:""); $do = isset($_GET["do"])?$_GET["do"]:""; $do = strtolower($do); switch($do) { case "": if (checkLoggedin()) {include("usernav.php");?> <h3>User Logged In</h3> <p>This is the members only area.</p> <?php } else {?> <a name="User Panel"></a> <h1>User Panel</h1> <h3>User Login</h3> <form name="login" action="login.php?do=login" method="POST" onsubmit="return aValidator();"> <input type="hidden" name="returnurl" value="<?$returnurl?>"> <table cellPadding=3 width=225 border=1> <tr> <td colSpan=2> <center> <p><b>Members-Only Area!</b></font></p> </center></td></tr> <tr> <td align=center width=70>Username:</td> <td><input type="text" name="username"></td></tr> <tr> <td align=center width=70>Password:</td> <td><input type="password" name="password"></font></td></tr> <tr> <td align=middle colspan=2> <input type="submit" name="submit" value="Login"></td></tr> <td align=middle colSpan=2> <input type="checkbox" name="remme" value="on"> Remember me for the next time I visit</td> </form></table></td> <?php } break; case "login": $username = isset($_POST["username"])?$_POST["username"]:""; $password = isset($_POST["password"])?$_POST["password"]:""; if ($username=="" or $password=="" ) { echo "<h1>Username or password is blank</h1>";//this does not show when the input(s) are blank clearsessionscookies(); header("location: index.php?returnurl=$returnurl"); } else { if(confirmuser($username,$password)) { createsessions($username,$password); if ($returnurl<>"") header("location: $returnurl"); else { header("Location: index.php"); } } else { echo "<h1>Invalid Username and/Or password</h1>";//this message does not show when the user login invalid clearsessionscookies(); header("location: index.php?returnurl=$returnurl"); } } break; case "logout": clearsessionscookies(); header("location: index.php"); break; } ?> What maybe the case, could anyone help me with this? Thanks Ted. hi im having trouble with my login script i keep getting the errors Deprecated: Function session_register() is deprecated in C:\wamp\www\login.php on line 53 Deprecated: Function session_register() is deprecated in C:\wamp\www\login.php on line 57 Deprecated: Function session_register() is deprecated in C:\wamp\www\login.php on line 61 i just wanted to knw wot they mean the page styll runs ok, is there any way i can make it work Code: [Select] $sql = mysql_query("SELECT * FROM myMembers WHERE email='$email' AND password='$pass' AND email_activated='1'"); $login_check = mysql_num_rows($sql); if($login_check > 0){ while ($row = mysql_fetch_array($sql)){ $id = $row["id"]; session_register('id'); $_SESSION['id'] = $id; $firstname = $row["firstname"]; session_register('firstname'); $_SESSION['firstname'] = $firstname; $email = $row["email"]; session_register('email'); $_SESSION['email'] = $email; mysql_query("UPDATE myMembers SET last_log_date=now() WHERE id='$id'"); $my_msg="Hello $firstname, you have succesfully logged in"; //print "return_msg=$my_msg&id=$id&firstname=$firstname"; } // close while } else{ $my_msg="Error Your Password Or Email Did Not Match"; // print "return_msg=$my_msg"; exit(); } } also im having trouble with my my_msg variable it does not seem to show up i keep gettin error Hi i followed a guid to create a login area to my site however i believe its a little outdated and therefore not working, i have done a little bit but being quite new i cannot find all the problems at the moment i have: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a9855336/public_html/checklogin.php on line 12 here is my script line 12 is marked <?php $host="*************"; // Host name $username="a9855**6_root"; // Mysql username $password="************"; // Mysql password $db_name="****3***36_mail; // Database name // Connect to server and select databse. mysql_connect($host, $username, $password) mysql_select_db($db_name); // username and password sent from form $myusername=$_POST['myusername']; // line 12 $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); // encrypt password $encrypted_mypassword=md5($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_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_success.php"); } else { echo "Wrong Username or Password"; } ?> if you help please tell me the error so i can learn to debug scripts myself in the future thanks blink359 How do I display the actual errors in IIS 7.5? If I miss a semicolon, I get: "HTTP Error 500.0 - Internal Server Error" absolutely useless. In prior versions, I could see the line and get to the PHP error. How do I display PHP errors? I've added: set_ini('display_errors', '1'); but it doesn't help. How can I prevent someone from making an ivalid selection in a form? Lets say I had a select dropdown box and someone saved the HTML source from the browser, changed an item in the list, and changed the action to point back to my server eg. action="testsite.com/index.php". Then they open the file and try to submit the form.
hi i need help an idea how can i separate members from admins since i dont know how to create login form i used tutorial ( http://www.youtube.com/watch?v=4oSCuEtxRK8 ) (its session login form only that i made it work other tutorials wre too old or something) how what i want to do is separate members and admins because admin need more rights to do now i have idea but dont know will it work like that what i want to do is create additional row in table named it flag and create 0 (inactive user) 1 (member) 2 (admin) will that work? and how can i create different navigation bars for users and admins? do you recommend that i use different folders to create it or just script based on session and flag? Dont understand why...my database is displayed correctly but cant seem to add edit delete etc, I just get the error above. Any clues please Code: [Select] function conectar_bd($nombre_bd=$reg->getConf("Nombre bd"), $host=$reg->getConf("Host bd"), $usuario=$reg->getConf("Usuario bd") ) { Whats wrong with this code? it dont work. I have a class (P3TElement) that extends the DOMElement class in PHP. In there i have a public variable "attributes" which is an array, and an method named add_attribute($attr), the argument is a different class (P3TAttribute). However I am getting an error when trying to use it. The exact error is: Warning: P3TElement::add_attribute() [p3telement.add-attribute]: Invalid State Error in D:\www\p3textract\extract.php on line 110 Please see the code: http://pastebin.com/CbsM9V5W This class is supposed to extract .p3t (ps3 themes) files, and is a direct port of the python equivalent found at http://p3textractor.googlecode.com/svn/trunk/p3textractor.py Could you please help me fix this? thanks in advance, Hosh putenv('GDFONTPATH=C:\Windows\Fonts') ; Hi, I've been looking at this for a couple of hours and it's killing me a little inside. I've butchered a few pieces of code from various sources together and come up with this. I understand how it's supposed to work (or i'm pretty sure i do) but the foreach statement is giving me the following error: Warning: Invalid argument supplied for foreach() /document/etc/etc on line 80 Obviously the offending statement is this one: Code: [Select] <?php // Check if button name "Submit" is active, do this if($_SERVER['REQUEST_METHOD'] == "POST") { foreach($_POST['id'] as $id) { $update="UPDATE users SET firstname='" . $_POST["firstname".$id] . "', lastname='" . $_POST["lastname".$id] . "', email='" . $_POST["email".$id] . "', password='" . $_POST["password".$id] . "', adminid='" . $_POST["adminid".$id] . "' WHERE id='" . $id . "'"; $result = mysql_query($update); echo "Updated"; } } ?> Not a clue what the problem is atm. If someone could either tell me or point me in the right direction i'd appreciate it/ Reece Hi I have a couple of phpbb forums on my web space. One is randomly throwing people off and it is getting far worse. I have traced down the issue to the IP address. Phpbb stores the IP address and session id and checks that they match. If not it throws the user out. The session ids seem to be there OK, but the IP addresses aren't. When it causes a problem the IP address seems to be returned as "::" (yes, 2 colons). I have used the following routine to try and obtain a relevant IP address and it to returns "::" Code: [Select] function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } Any ideas? All the best Keith Hello, Am writing a script that involves user input. Take an example: a user fills in a wrong username or password at the page login.php, my login processor (processor.php) detects it, how is the error "WRONG USERNAME OR PASSWORD" supposed to be transferred back to login.php. So far I have been using a session variable to transfer the error but am sure there is a better way to do this without displaying the error on processor.php itself. Thanx in advance |