PHP - Good Php Error Handling Involving Paypal
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! Similar TutorialsSome help would be great here. The following snippets work, but I am unable to figure out how to activate the error message "You did not select a name for editing". Both of the other error codes work but if I input 'given' and 'family' and forget to select the relevant radio button, the error message doesn't work. No other problems with the code. Code: [Select] <html> <table> <?php // Query member data from the database $query1 = mysql_query("SELECT userId FROM users WHERE managerId='".$recid."' AND userGroup='".$group2."' ORDER BY userId ASC"); while($row1 = mysql_fetch_array($query1)) { $firstGroup .=$row1['userId']. ' <input type="radio" name="snames" value="'.$row1['userId'].'" /> ' . " <br /><br>"; } ?> <form method="post" enctype="multipart/form-data" action="<?PHP echo $_SERVER["PHP_SELF"]; ?>"> <tr> <td><?php echo $firstGroup;?></td> <td><input type="text" name="given" value="" /><p> <input type="text" name="family" value="" /><p> <input type="submit" value="submit" name="Send Data"></form></td> </tr> </table> </html Here are the error messages and their activation method. Code: [Select] <?php // Process the form if it is submitted if ($_POST['snames']) { $snames = $_POST['snames']; $family = preg_replace("/[^A-Za-z0-9]/", ".", $_POST['family']); $given = preg_replace("/[^A-Za-z0-9]/", ".", $_POST['given']); //next section deals with error messaging $errorMsg = "ERROR:"; if(!$snames) { $errorMsg .= "--- You did not select a name for editing."; } else if(!$family) { $errorMsg .= "--- You did not enter a family name."; } else if(!$given) { $errorMsg .= "--- You did not enter a given name."; } else { exit(); } }// close if post echo $errorMsg; ?> 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 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 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; } } } 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. 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 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. 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--> 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? 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. 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! 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. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=351056.0 Hi there.... I am facing problem regarding credit card transaction ....an error i am keep on getting "Security header is not valid"....i searched for that but all are saying that its because of using "wrong credentials"...but i have gone through all my docs....i think i am using the right one......anyone there to help me out please....i really need it to get done.........thanxx..... problem showing date posted from a form into MYSQL using the php code. Date shows as 0000-00-00 and not the value submitted from the form. Thank you for any help Code: [Select] $sql="INSERT INTO Results (RunnerID, EventID, Date, FinishTime, Position, CategoryID, AgeGrade, PB) VALUES ('$_POST[RunnerID]','$_POST[EventID]','$_POST[Date]','$_POST[FinishTime]','$_POST[Position]','$_POST[CategoryID]','$_POST[AgeGrade]','$_POST[PB]')"; if (!mysql_query($sql,$connection)) { die('Error: ' . mysql_error()); } echo "<h1> Success! Saving data: </h1>"; mysql_close($connection); ?> <html> <head> <title>Submitted</title> </head> <body> <br /> <?php echo "RunnerID=" . $_POST["RunnerID"]; ?><br /> <?php echo "EventID=" . $_POST["EventID"]; ?><br /> <?php echo "Date=" . $_POST["Date"]; ?><br /> <?php echo "FinishTime=" . $_POST["FinishTime"]; ?><br /> <?php echo "Position=" . $_POST["Position"]; ?><br /> <?php echo "CategoryID=" . $_POST["CategoryID"]; ?><br /> <?php echo "AgeGrade=" . $_POST["AgeGrade"]; ?><br /> <?php echo "Personal best=" . $_POST["PB"]; ?><br /> </body> </html> I'm building a query that searches by database and returns matching (or almost matching) terms. That part isn't the problem- I have it up and working. The problem is that I'm trying to narrow down the search results, and it's not working. Here's the query that works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); Here's the query that DOESN'T works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE type='Cars' AND name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); What I'm trying to do is say "give me all the results from type:Cars. Instead, it ignores the WHERE type='Cars' statement, and returns results for all types. It frustrates me because I use the same exact query in a thousand other places, and it works everywhere else. For example: Code: [Select] $sql = "SELECT * FROM auctions WHERE type='Boats' AND state='$v4' ORDER BY $v1 $v2"; works just fine. I'm not exactly an expert on any of this, but I can see no logical reason why this works, but the Search code doesn't. They appear in all ways identical, at least as far as query structure goes. Can anyone spot where I screwed up? Thanks! Kyle Hello there, I'm having a problem displaying money correctly with php. I have a field called "balance" with the type float(10,2), in this field I have a number store as "34.55" which I can go in and look at within phpmyadmin but when I echo this value on the front-end of the site it is displayed as "34.549999237061" Can someone please help? Regards. Hey Guys,
Been coding PHP for a while but I always wonder about the right way of doing things. I am building an online community which I want to display to members and non-members. With this each screen will have options that are available for members only. I have set up session variables once a user logged in but its getting really old having to nest if statements on ISSET then again to check the values in the variables if it is set. See example below.
Question 1. Is it ok to session_start(); for all site visitors?
Question 2. If Q.1 is ok then is it ok to set all the session variables upfront with blank values as placeholders. This would eliminate the need for ISSET.
if (ISSET($_SESSION['On'])) { if (in_array($GroupID, $_SESSION['Groups'])) { $IsMember = 1; } else {$IsMember = 0;} } else {$IsMember = 0;}Just wanted to get your thoughts on this. Thank you, Jeremy Hi, I have an HTML form created using Dreamweaver and now I need a script to handle the form processing. Basically what I need is for the form data received from the webpage to be organized in an email and then sent to me. I would also like to display a thank you message in the browser so the user knows it was received. I was planning to do this using CGI but a colleague suggested that CGI is old school and nowadays a developer would use PHP for this task. Is PHP the right solution for this project? The examples I have found so far always include the HTML for the form and the script needed to handle it in one file. In my case, I have an HTML form already in place and need it to work with a script to perform the email function. I know I need to set "Action=" on my webpage to point to the PHP script but what would the code look like if no HTML is needed? I hope this makes sense... Thanks for your help! Rob |