PHP - Need Some Suggestions On Exception Handling And Redirect To An Error Page
Hi guys, I'm reviewing a piece of small web application and the current application does not have any error / exception handling capability. If there is any error, it would simply show an error message followed by die;.
I'm planning to implement a simple exception handling class to handle the errors. What I'm thinking is a simple redirect when an error is being caught together with an error code that correspond to an error message in a simple flat text file. The error page will then show an error message that corresponds to the code. Here's what I have so far. Would appreciate if the PHP experts here would give simple pointers to enhance it. <?php class MyException extends Exception {} try { throw new MyException("error.php"); } catch (MyException $e) { $file = $e->getMessage(); header("Location: $file?e=1"); } ?> This is what I have on my error.php page <?php $errorcode = $_GET['e']; function getErrorMessage($errorcode) { $errors = file("english.txt"); foreach ($errors as $error) { list ($key,$value) = explode(",",$error,2); $errorArray[$key] = $value; } return $errorArray[$errorcode]; } echo "Test <br />"; echo getMessageMap($errorcode); ?> As you can see here, exception class would redirect user to error.php if an error is caught together with a GET variable on the URL. On error.php page, it would GET the error code and then run it through a function to get the error message of the corresponding error code and then echos it out. Was wondering if this is a good practice? My ultimate goal here is to avoid displaying the error message itself on private includes file. Thank you in advance for your suggestions. Similar TutorialsGett an error from some custom code I inherited in a WordPress installation. Here is the error... Code: [Select] Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (--) at position 0 (-): Unexpected character' in /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php:27 Stack trace: #0 /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php(27): DateTime->__construct('--') #1 /home2/history8/public_html/bee/wp-includes/plugin.php(395): bee_teachers('') #2 /home2/history8/public_html/bee/wp-admin/admin.php(151): do_action('bee_teachers', Array) #3 {main} thrown in /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php on line 27 Here is the code... Code: [Select] <?php $teachers = $wpdb->get_results("SELECT * FROM bee_teachers,bee_postmeta WHERE bee_teachers.statebee=bee_postmeta.post_id and meta_key='regional_date' ORDER BY meta_value ASC"); $today = new DateTime(); foreach ($teachers as $teacher): $site = get_post($teacher->statebee)->post_title; $date = new DateTime($teacher->meta_value); // this is line 27, mentioned in the error if($date<$today) $style=' style="color:#999"'; else $style=''; ?> If I remm out these lines, the query works, just no styling difference based upon date... Code: [Select] $date = new DateTime($teacher->meta_value); // this is line 27, mentioned in the error if($date<$today) $style=' style="color:#999"'; else $style=''; Thoughts? Hello All, I am building a web based data entry project for my University Recycling Department 1) In the first level the user will enter the number of "rows" that he has to enter it can be any number form 4- 10 . Each row will contain "Vendor Name","Date","Net Recycled Weight" 2) Depending on the number of rows entered by the user I am generating a table structure that has 2.1) A <select> containing vendor names(I am querying for this and then storing the result in an Associative Array and then parsing it for select in every way) 2.2) A text box for the date 2.3) A text box for the Net Recycled Weight ------------------------------------------------ Here is the logic I have implemented so far <html> <head></head> <body> <form name = "form1" method = "post"> <select>HERE THE USER CAN SELECT THE NUMBER OF ROWS HE WANTS TO ENTER</select> <input type = "submit" value = "submit1" name = "submit1"> </form> <body> </html> <?php if(submit1 has been clicked ) { //HERE I AM GENERATING A DYNAMIC FORM BASED ON THE NUMBER OF ROWS COUNT <form name = "form2" method = "post"> echo <table> echo <tr> echo<td>VENDOR</td> echo<td>DATE</td> echo<td>NET RECYCLED WEIGHT</td> echo </tr> for(IT ITERATES TILL I GENERATE THE NUMBER OF ROWS THAT HAS TO BE ENTERED) { I AM GENERATING ROWS HERE } echo <input type = "submit" name = "submit2" value = "submit2"> echo</table> </form> HOW CAN I ACCESS THE POST METHOD OF FORM 2 } ?> MY PROBLEM --------------- I WANT TO KNOW THE FOLLOWING 1) It this the correct way to do it 2) how can I access the data entered in each dynamic row as I have to validate it and then enter the data in MySql 3) I am not sure how I will access the submit button event of the dynamically generated form I hope I can get some help Thanks, Marisha Hello all,
Appreciate if you folks could pls. help me understand (and more importantly resolve) this very weird error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ASC, purchase_later_flag ASC, shopper1_buy_flag AS' at line 3' in /var/www/index.php:67 Stack trace: #0 /var/www/index.php(67): PDO->query('SELECT shoplist...') #1 {main} thrown in /var/www/index.php on line 67
Everything seems to work fine when/if I use the following SQL query (which can also be seen commented out in my code towards the end of this post) :
$sql = "SELECT shoplist.*, store_master.store_name, item_master.item_name FROM shoplist, store_master, item_master WHERE shoplist.store_id = store_master.store_id AND shoplist.item_id = item_master.item_id";However, the moment I change my query to the following, which essentially just includes/adds the ORDER BY clause, I receive the error quoted above: $sql = "SELECT shoplist.*, store_master.store_name, item_master.item_name FROM shoplist, store_master, item_master ORDER BY purchased_flag ASC, purchase_later_flag ASC, shopper1_buy_flag ASC, shopper2_buy_flag ASC, store_name ASC) WHERE shoplist.store_id = store_master.store_id AND shoplist.item_id = item_master.item_id";In googling for this error I came across posts that suggested using "ORDER BY FIND_IN_SET()" and "ORDER BY FIELD()"...both of which I tried with no success. Here's the portion of my code which seems to have a problem, and line # 67 is the 3rd from bottom (third last) statement in the code below: <?php /* $sql = "SELECT shoplist.*, store_master.store_name, item_master.item_name FROM shoplist, store_master, item_master WHERE shoplist.store_id = store_master.store_id AND shoplist.item_id = item_master.item_id"; */ $sql = "SELECT shoplist.*, store_master.store_name, item_master.item_name FROM shoplist, store_master, item_master ORDER BY FIND_IN_SET(purchased_flag ASC, purchase_later_flag ASC, shopper1_buy_flag ASC, shopper2_buy_flag ASC, store_name ASC) WHERE shoplist.store_id = store_master.store_id AND shoplist.item_id = item_master.item_id"; $result = $pdo->query($sql); // foreach ($pdo->query($sql) as $row) { foreach ($result as $row) { echo '<tr>'; print '<td><span class="filler-checkbox"><input type="checkbox" name="IDnumber[]" value="' . $row["idnumber"] . '" /></span></td>';Thanks This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=358486.0 In drive.php
public function insert($postBody, $optParams = array()) I have set an SQL field as unique so that duplicates can't be entered, however rather then having the page error out and show the Error: Duplicate entry 'entry' for key 'field' I would like to be able to have a little div appear and say something like "this entry already exists" I already have it set to show that the item has been added but I have no idea were to start to make this work. Any ideas? Thanks, Jim 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 Hi, I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP. Look at this function for example: public function deleteFileFromDisk($fileNameToBeDeleted) { $handle = unlink($fileNameToBeDeleted); if (!$handle) { $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted."; } else { $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted."; } return $result; } Is this the correct way of doing it, or I can do better than this? Let me add some details of what I'm achieving... I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch, stop all the process and send an e-mail with the error. Here are the object interactions: $testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'); $testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName()); $testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.'); $testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv'); $testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv'); $testar_classe->deleteDataFromTable('tabela1'); $testar_classe->deleteDataFromTable('tabela2'); $testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1'); $testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2'); $testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName()); $testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv'); $testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this? Best Regards. Hi I'm completely new to error handling in PHP and wanted to ask whether I'm doing it right and, if not, what the right way would look like class DBConnection { public function execute($sql) { $query = @pg_query($this->dbconn, $this->prepare($sql)); try { if (!$query) { throw new DBException(); } } catch (DBException $e) { echo "Query execution failed"; exit; } } } I have a prepared statement that returns an Article from my database. It then binds the results-set to variables. Most of the fields in the query are "required", so I *assume* that I am guaranteed to always get values back for those fields... Is that presumptuous? Here is a snippet of my code... // Execute query. mysqli_stmt_execute($stmt); // Store results. mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==1){ // Article was Found. $articleExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $articleID, $title, $description, $keywords, $heading, $subHeading, $publishedOn, $author, $body, $referenceListing, $endnoteListing); // Fetch record. mysqli_stmt_fetch($stmt); // Close prepared statement. mysqli_stmt_close($stmt); // ???? Is it sufficient to have code like this... Code: [Select] <title><?php echo $title; ?></title> ...or do I need more error-handling?? Hope that makes sense?! Thanks, Debbie My script displays results until I hit an error. I continually get fatal timeout errors that I am unable to handle or ignore. Yes I googled and found the custom error handler AND the simpler try/catch. Still cant figure it out... It has been 1 hour of playing with this without success so I have to ask . Please help. thanks : ) Code: [Select] try { if(($result=shell_exec("$commandLine")) == false) { echo "------>error"; throw new Exception; } else { echo "---->good"; } } catch (Exception $e) { echo "@@@__>exception caught"; } Hello everyone, quick description of 'error handling' so that everyone understands the solution i am seeking. let php and the database handle the error is not an appropriate answer here. find out what i mean: using xampp, go to a login screen of your website, then turn off the database before submitting the login data. the connection will be attempted then fail. the browser will display its own error page which is white bg with a message. this is ridiculous. i made a custom handler that allows me to ignore this failure and show my own website with an error message. now how can i detect an error with a select or update statement? i am not a db designer, so i really don't know how to do it. what say i fetch filed['testmyerror'] and it doesn't exist or there is a problem. how do i write php code that is used to ignore this problem and display my own message. naturally i will log the error and/or log and send email to myself. anyone able to help? just a tip in the right direction? Thank you very much, i appreciate this forum and its members always. Hopefully there is a simple solution to this. I have a form that when submitted sends a message to an email address from the form. A customer fills it out, so there is no single one email address. However, half of the time, the retards that use this form dont know their own email address and dont bother to put the .net at the end of it. or they misspell it. The other half of the time they dont even bother to put the @ and the domain. They still think this is AOL for some god unknown reason. And I cant account for all the ways that they can not figure out how to fuck up their email address, so an email-validator doesnt work because they can even beat that and still manage to break it. For example, one guy named Mike continues to put the first half of his email in as Miek or Mik or just spelled completely wrong, and the 550 error that comes up when he puts that garbage in, which is most of the time (I think the guy is blind or something) is because his email address doesnt exist on the mail server because he cant spell it right, when on the off chance he actually does get the @domain.com in the end. I really hate my retard customers. So my simple little form blows up on them. But what I am trying to do is to have something like this if(@mail(args)) { //success, I'll call them back shortly } else { //youre a retard, please put in your email address correctly } However, the error handling isnt working. mail() is supposed to return FALSE if it encounters an error, an error that I'd rather put in an error log and not display to the customer, however, the error suppressor doesnt work. Any Suggestions? Hi. I'm trying to display all the missing fields (errors) when the user hits SUBMIT. My logic: IF there is NO EMAIL THAN add $errortrack array = $errormsg[EMAIL] IF there is NO OLDPASSWORD THAN add $errortrack array = $errormsg[OLDPASS] and so on. At the end, Print ALL the Error messages on the form using <?php foreach ( $errortrack as $key => $value) { echo "<dt>$key:</dt>"; } ?> The only thing it prints out is "0:" ever though there should be other errors. What am I missing? Site Link http://www.fusionfashionhair.com/newpassform.php My PHP Code: <?php session_start(); ?> <?php $submit = $_POST['submit']; // Form Data $email = $_POST['email']; $password_old = $_POST['password_old']; $password_new = $_POST['password_new']; $password_new_con = $_POST['password_new_con']; $errorcount = 0; $errormsg['Email'] = "Email Entered is Invalid"; $errormsg['OldPass'] = "Old Password Entered is Incorrect"; $errormsg['NewPass'] = "New Password Entered is Incorrect"; $errormsg['NewPassCon'] = "New Confirmed Password Entered is Incorrect"; $errormsg['SecCode'] = "Security Code is Incorrect"; $errormsg['NoErr'] = "No Errors, Continue"; $errortrack = array ($errormsg['NoErr']); if ($_POST[submit]){ if ($errorstop = "go") { $errorstop="go"; while ($errorstop<>"stop") { // check for existance if ($email) { echo "True - Continue 1"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['Email']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_old) { echo "True - Continue 2"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['OldPass']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_new) { echo "True - Continue 3"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['NewPass']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_new_con) { echo "True - Continue 4"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['NewPassCon']); $errorcount++; $errorstop="stop"; } $errortrack = array ($errormsg="EVERYTHING IS OK"); $errorstop="stop"; }//End While Loop } else { while($errorcount>=0) { // Test display all error messages echo "<p>----------</p>"; echo "<p>Error Count = '$errorcount'</p>"; } die ("PLEASE FILL IN ALL FIELDS"); } } ?> My Form Code with the PRINT ERROR: Code: [Select] <form action='newpassform.php' method='post' id="regform"> <fieldset> <legend>Change Password</legend> <p><?php foreach ( $errortrack as $key => $value) { echo "<dt>$key:</dt>"; } ?></p> <p> <label for='email'>Email:</label> <input name='email' type='text' maxlength="25" value='<?php echo $email; ?>'/> </p> <p> <label for='password_old'>Old Password:</label> <input name='password_old' type='password' maxlength="32" /> </p> <p> <label for='password_new'>New Password:</label> <input name='password_new' type='password' maxlength="32"/> </p> <p> <label for='password_new_con'>Confirm Password:</label> <input name='password_new_con' type='password' maxlength="32"/> </p> <p><span class="required">*</span> Note, username and password are case sensitive</p> <p>Forgot your password? <a href="forgot_password.php">Click Here</a></p> <p>Login <a href="login.php">Here</a></p> <h2>Security Check</h2> <p>Enter letters below exactly how they are displayed. Letter are case sensitive. </p> <br /> <img src="captcha.class.php?usefile=1" /> <!--OR--> <!--<img src="image.php" />--> <input id='user_code' name='user_code' type='text' size='10' > <p> </p> <input class="reset" type='reset' value='Cancel' name='reset'> <input class="submit" type='submit' value='Continue' name='submit'> </fieldset> </form> <!--End of Form--> Has anyone seen a decent database class for nicely wrapping up all the PDO functions? Ideally I'm after an example to handle database errors properly, insert/update/select queries, prepared statements and transactions. I've had a crack at writing my own and it's a bit messy with error handling everywhere. Maybe I need to put that in a separate class or something. E.g. here's how I'd do a database update: $db = new Database(); // In page controller $params['type'] = $type; $params['details'] = $details; $query = 'insert into site_logs (type, details) values (:type, :details)'; $result = $db->preparedUpdate($query, $params); // returns false if error or # of rows if successful Just some examples would be great and I'll re-factor my one to make it better. Thanks! Hey guys i was wondering if someone could help or guide me. I have been messing around with php for quite some months now to the stage where i can code pretty much what i need to. but recently i started using paypals IPN and during testing i realised some problems arise for example when testing and people buying things say the payment failed due to a line not executing in your script for what ever reason, the person has lost their money yet you have gained it and they are lost. Take this code below for example: public function insertIntoDatabase($firstName,$lastName,$emailAddress,$merchant,$code,$database,$gameNumber) { $year = date("Y"); // Check what database we need to submit too:: $sql = "INSERT INTO playerGame (playerFirstName, playerLastName, playerEmailAddress, playerAccountType, playerCode, playerGameDate, playerGameNumber) VALUES (?,?,?,?,?,?,?)"; $stmt = $this->conn->prepare($sql); $stmt->bind_param('ssssssi',$firstName,$lastName,$emailAddress,$merchant,$code,$year,$gameNumber); $stmt->execute(); $stmt->close(); return true; } this is called on success the paypal IPN script. But what happens if this fails to execute? I suppose i could wrap it in a variable on the other side and test it if($task) { echo "code executed"; } but what happens if this fails ? of am i just being paranoid ? hope someone can help dont want to be ripping people off =] Thanks! Hello, If I have an index file with: date_default_timezone_set('GMT'); error_reporting(E_ALL | E_STRICT); abstract class A { abstract public static function YesIReallyMeanAbstractStatic(); } class B extends A { public static function YesIReallyMeanAbstractStatic() { } } This will not error. However if I have: date_default_timezone_set('GMT'); error_reporting(E_ALL | E_STRICT); require('class_a_in_a_different_file.php'); // Or use __autoload() to do the same. class B extends A { public static function YesIReallyMeanAbstractStatic() { } } This will throw the error: "Static function A::YesIReallyMeanAbstractStatic() should not be abstract" I know abstract statics are debatable... but it makes no sense to me for it to be allowed in the first example but disallowed in other. So I was wondering if this is a bug? Or is there something else going on here? I assume the parser is evaluating the included file and then throwing the error which doesn't happen if both classes are in the same file as they can then be evaluated altogether. I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! Hello. I have a web page that has several operations on it, and I'm not sure the best way to design it. This is a subscription page were a user can choose different renewal plans. Before a certain date, the user can "renew" for a certain lower price (operation #1), or he/she can "upgrade" for a certain lower price (operation #2). After a certain date, the user can choose from one of three plans (operation #3, #4, or #5). The way I have things design for the "after" part is just creating a form for each one, so that when a user chooses one of them, then I can take the appropriate actions. My question is this... 1.) Is it okay to have five forms on the one web page to more clearly delineate each request/operation? 2.) Or should I create one form, and then assign a hidden form value to each button so I know how to handle the selection?
Edited July 25, 2020 by SaranacLake This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=351056.0 |