PHP - Catch Warnings
Is there any way to catch warnings without defining a warning handler?
Example: try { $settings = parse_ini_file( 'main.ini' ); } catch( ErrorException $e ) { throw new ErrorException('No main configuration file found for webiste', '0003'); } Only ends up throwing a warning if the file doesn't exist. I want to catch it and throw an error. Similar Tutorialsok people sorry but its late, and I'm tired and I can't figure this out maybe I just need a break? I'm getting some warnings here, first here is my code: Code: [Select] <?php echo"<?xml version=\1.0\"encoding=\UFT-8\"\x3f>"; echo"\n"; ?> <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"lang="en"> <head> <title>Assignment 7: Making Space, Part 3</title> <meta name="author" content="Jim Cozzy"/> </head> <body> <h1> Assignment 7: Making Space, Part 3 </h1> <?php echo "<h2>Today is ".date('l, F d, Y')."</h2>"; ?> <?php //calculate the area of an equilateral triangle function calcTriangle($cVal) { $halfSide = $cVal/2; $otherSide = sqrt(($cVal*$cVal) - ($halfSide*$halfSide)); $areaValue = $otherSide * $halfSide; echo "<p>The area of an equilateral triangle whose sides are {$cVal} is {$areaValue}.</p>\n"; } $yeah = (isset($_POST['vfld']))?$_POST['vfld']:''; if (isset($_POST['submit'])) { if ($_POST['submit'] == "Clear") { $yeah = ""; } elseif ($_POST['submit'] == "Calculate") { if (!eregi(square|circle|triangle, $yeah)) { echo "<p>Sorry I forgot to mention the the shape needs to be a Square, Circle, or a Triangle.</p>". "<p>Please return and try again.</p>"; exit; } }} ?> <form method="post" action="makingspace3.php" id="form1" name=form1"> <p> Write down a shape and a number and I will compute the area for: <input type="text" id="vfld" name="vfld" value="<?php echo $yeah; ?>"/> </p> <p> After you have done this click calcualte to see results </p> <p> <input type="submit" name="submit" value="Calculate" /> <input type="submit" name="submit" value="Clear" /> </p> </form> <div id="footer"> <pre>This page written by: <cite>James Cozzy</cite> ©2011 and beyond</pre> </div> </body> </html> so when I enter something wrong into my form like ggggg I want it to print an error which it does, but it also says what am I missing???? Notice: Use of undefined constant square - assumed 'square' in /studfs1/homepage/CISS-225/makingspace3.php on line 49 Notice: Use of undefined constant circle - assumed 'circle' in /studfs1/homepage/CISS-225/makingspace3.php on line 49 Notice: Use of undefined constant triangle - assumed 'triangle' in /studfs1/homepage/CISS-225/makingspace3.php on line 49 Okay I have been trying to work out this problem for 3 months I am not the type of person to give up but I have tried everything. I was first not able to connect to my database live with my form but I did a change from ($cxn,$sql) to ($sql,$link) since then I was able to download to phpmyadmin in Google Chrome and no other site. But in Google Chrome I get a message about global registry Warning: Unknown on line 0. all other sites give me a Warning line 116 MySql Link is Here is my coding can someone help I have only been using PHP and I know someone is out there with much more knowledge than I have. This is the first page with the codes but it does not go to the second page which I will paste after this one. Any help would make my year better. Code: [Select] <php @session_start(); switch (@$_POST['Button']) { case "Login1": include "Connections/connect_to_mysql.php"; $sql = "SELECT id FROM Members WHERE id= '$_POST[fusername]'"; $result = mysql_query($sql) or die("Query died: fusername"); $num = mysql_num_rows($result); if($num > 0) //login name was found { $sql = "SELECT id FROM Members WHERE id='$_POST[fusername]' AND password=md5('$_POST[fpassword])'"; $result2 = mysql_query($sql) or die("Query died: fpassword"); $num2 = mysql_num_rows($result2); if($num2 > 0) //password matches { $_SESSION['email1']="yes"; $_SESSION['id'] = $_POST['fusername']; $sql = "INSERT INTO Members (id,loginTime) VALUES ('$_SESSION[id]',NOW())"; $result = mysql_query($sql) or die("Query died: insert"); header("Location: New_member.php"); } else //password does not match { $message_1="The username, '$_POST[fusername]' exists, but you have not entered the correct password! Please try again."; $fusername=strip_tags(trim($_POST['fusername'])); include("login_form.php"); } } else //username not found { $message_1 = "The username you entered does not exist! Please try again."; include("login_form.php"); } break; case "Register": /* Check for blanks */ foreach($_POST as $field => $value) { if($field != "fax") { if(empty($value)) { $blanks[] = $field; } else { $good_data[$field] = strip_tags(trim($value)); } } } if(isset($blanks)) { $message_2 = "The following fields are blank. Please enter the required information: "; foreach($blanks as $value) { $message_2 .="$value, "; } extract($good_data); include("login_form.php"); exit(); } /* validate data */ foreach($_POST as $field => $value) { if(preg_match("/name/i",$field) and !preg_match("/user/i",$field) and !preg_match("/log/i",$field)) { if (!preg_match("/^[A-Za-z' -]{1,50}$/",$value)) { $errors[] = "$value is not a valid name. "; } } if(preg_match("/email/i",$field)) { if(!preg_match("/^.+@.+\\..+$/",$value)) { $errors[]="$value is not a valid email addr."; } } } //end if not empty foreach($_POST as $field => $value) { $$field = strip_tags(trim($value)); } if(@is_array($errors)) { $message_2 = ""; foreach($errors as $value) { $message_2 .= $value." Please try again<br />"; } include("login_form.php"); exit(); } // end if errors are found /* check to see if username already exists */ include_once"Connections/connect_to_mysql.php"; $link = @mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); @mysql_select_db("$db_name") or die ("Query died:"); $sql = "SELECT id FROM Members WHERE id='$id'"; $result = mysql_query($sql) or die("Query died: id."); $num = mysql_num_rows($result); if($num > 0) { $message_2 = "$id already used. Select another User Name."; include("login_form.php"); exit(); } // end if username already exists else // Add new member to database { $sql = "INSERT INTO Members (id,sign_up_date,username password,firstName,lastName,email) VALUES ('$id',NOW(),,md5('$password'), '$username','$firstName','$lastName','$email')"; mysql_query($sql); $_SESSION['email1']="yes"; $_SESSION['id'] = $username; /* send email to new Customer */ $emess = "You have successfully registered. "; $emess .= "Your new username and password a "; $emess .= "\n\n\t$username\n\t"; $emess .= "$password\n\n"; $emess .= "We appreciate your interest. \n\n"; $emess .= "If you have any questions or problems,"; $emess .= " email ebermylove@gmail.com"; $subj = "Your new customer registration"; # $mailsend=mail ("$email","$subj","$emess"); } break; default: include("login_form.php"); } ?> <php session_start(); if (@$_SESSION['auth'] != "yes") { header("Location: login.php"); exit(); include("dogs.inc"); $link = mysqli_connect($host,$user,$password,$dbname) or die("Couldn't connect to server."); $sql = "SELECT firstName, lastName FROM `Members` WHERE id='{$_SESSION['id']}'"; $result = mysqli_query($sql,$link) or die("Couldn't execute query"); $row = mysqli_fetch_assoc($result); extract($row); } echo "<html> <head><title>New Member Welcome</title></head> <body> <h2 style='margin-top: .7in; text-align: center'> Welcome $firstName </h2>\n"; ?> <p>Your new Member accounts lets you enter the members only section of our web site. You'll find special discounts, a profile of matches, live advise for experts, and much more.</p> <p>Your new Member ID and password were emailed to you. Store them carefully for future use.</p> <div style="text-align: center"> <p style="margin-top: .5in; font-weight: bold"> Glad you could join us!</p> <form action="member_page.php" method="post"> <input type="submit" value="Enter the Members Only Section"> </form> <form action="profile.php" method="post"> <input type="submit" value="Go to Main Page"> </form> </div> </body> </html> Howdy, this one is killing me! Hope some of the genius here will rub off on me. Very simple example of what is happening: Base.php Code: [Select] class Base_Model //class autoloaded { protected function scrub($value) { return trim(htmlspecialchars($value, ENT_QUOTES, "UTF-8")); } } Foo.php Code: [Select] class Foo_Model extends Base_Model { if($_POST) { $_POST = array_map('parent::scrub', $_POST); } } This works perfectly on the workstation (MAMP) server, but generates a warning ( Warning: array_map() [function.array-map]: The first argument, 'parent::scrub', should be either NULL or a valid callback in... ) when uploaded to the production server. Both are running the exact same version of php. Any ideas would be appreciated on getting rid of the error, besides turning off warnings ( haha ). William Hey all. I have a function called displayForm in a form validation script. This function accepts a few arguments but these arguments are empty upon initial calling of the function. One of the arguments is and errors array that only gets populated if there were form errors. So upon running my script initially I get missing argument Warnings. Can these warnings simply be ignored? Would they cause problems throughout my script if I ignore these warnings? And how can I suppress these warnings if I would like to? Thanks all for your help. Cheers. i keep getting this error Fatal error: Uncaught OAuthException: Error invalidating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons. thrown in /home/sites/socialnewsoffice.com/public_html/sm-login/social-media-connect/facebook/base_facebook.php on line 1050 how can i catch and display this warning to the user? I use PHP's PDO extensively for data grabbing and inserting. When I am selecting data, the return is a PHP PDO object which in itself contains select statements. So I use foreach to parse through the object and build a table. For cells which I have data it's fine but for cells which do not get any data meaning that have no entry in the db, php throws out a error PHP Warning: Invalid argument supplied for foreach(). I tried using if(is_array) and also @ to suppress them but no luck . Can anyone point me to the right direction for suppressing these errors/warnings!! Hey Guys. I am across this in a book and I am having a hard time understanding how I can try/catch this expception
The code below will throw an exception if I add an unit object into Archer or LaserCannon object.
Here is a quick example
class UnitException extends Exception{} abstract class Unit{ function AddUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } function removeUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } abstract function bombardStrength(); } class Archer extends Unit { function bombardStrength(){ return 4; } } class LaserCannonUnit extends Unit { function bombardStrength(){ return 44; } } $laser_cannon = new LaserCannonUnit(); $laser_cannon->AddUnit(New Archer()); // This is not allowedWhen I run the client code I get the following error message Fatal error: Uncaught exception 'UnitException' with message 'LaserCannonUnitis a leaf' Can any please help me understand this?? Thanks! So I'm debating whats the best method. I'm aware that catch/blocks should be used in exceptional cases but what if it saves me from having 4 nested if/else conditions? The following is code for an xbox registration site Code: [Select] try { // check code is valid $c1 = $this->input->post('code1',true); $c2 = $this->input->post('code2',true); $c3 = $this->input->post('code3',true); $gt = $this->input->post('gamertag',true); $pass = $this->input->post('password',true); if( $c1 == '' || $c2 == '' || $c3 == '') { throw new FormError("Authorization code invalid."); } // check db for code validation $q = $this->db->query("select * from `codes` where `activated` = 0 and `code` = ".$c1.$c2.$c3." limit 0,1"); if($q->num_rows() != 1) { throw new FormError("Authorization code invalid."); } $r = $q->row_array(); $email = $r["recipient_email"]; $codeGt = $r["gamertag"]; // check valid gamertag $q = $this->db->query("select * from `users` where `gamertag` = '".$gt."'"); if($q->num_rows() > 0) { throw new FormError("Gamertag already exists."); } // validate gamertag /w inputted gamertag if(strtolower($codeGt) != strtolower($gt)) { throw new FormError("Gamertag Invalid"); } $this->_createAccount($email,$pass,$gt); // show register-thanks screen $this->load->view("register-thanks",$data); $success = true; } catch (Exception $e) { $data['error'] = $e->getMessage(); } Hello guys. Is it possible to catch a fatal error and then do something? What I need to do is to catch the error and run the script a second time, before the first execution ends. Kind regards and thanks for advance. I have the code below working perfectly, but I was wondering if there is a more eloquent way to write this, specifically handling the exceptions... This creates an object of a Router Class that parses my clean URLs into a Controller name, method name and the rest are arguments. So for example: www.domain.com/users/view/profile/bobsmith would route to the Users Controller, and find the viewUsers method and pass the arguments "profile" and "bobsmith" to it, and the method would take it from there... works great. That explains what this code does. My only question is if there is a cleaner way to handle the exceptions, so I don't have "throw new exception" written four times. Thoughts? Or is it good to go? $rawURL = getPageURL(); $router = new Router($rawURL,$rootDIR); $controller = $router->getController(); $method = $router->getMethod(); $arguments = $router->getArguments(); try { // check controller exists and set controller path // if ((isset($controller) && ($controller != ''))) { $controllerPath = APPLICATION_PATH . "controllers/" . $controller . ".class.php"; // check controller path exists // if (file_exists($controllerPath)) { // set method name and check method exists // if ((isset($method) && ($method != ''))) { $methodName = $method . ucfirst($controller); if (method_exists($controller, $methodName)) { // test it out // $test = new $controller(); $response = $test->$methodName($arguments[0]); echo $response; } else { // method_exists failed // throw new Exception("That method does not exist foo!"); } } else { // method was not found in URL // throw new Exception("No method name was given foo!"); } } else { // file_exists failed // throw new Exception("That controller does not exist foo!"); } } else { // controller was not found in URL // throw new Exception("No controller name was given foo!"); } } catch (Exception $e) { // spit it out foo // echo $e->getMessage(); } In php.ini on my local development server, error_reporting is set to Quote error_reporting = E_ALL | E_STRICT And I get no errors. However, on the remote web server I found a bunch of warnings in the error log. I fixed most of them, but this error/warning should have popped up on my development console: Quote [02-Dec-2011 17:47:22] PHP Warning: array_keys() [<a href='function.array-keys'>function.array-keys</a>]: The first argument should be an array in /home/bpslk/public_html/cart-checkout.php on line 177 [02-Dec-2011 17:47:22] PHP Warning: Invalid argument supplied for foreach() in /home/bpslk/public_html/cart-checkout.php on line 177 I can fix the code to eliminate the warning, no prob. But why am I NOT seeing this error on my development machine? --Thanks --HarryG How can i catch this exception and run the catch code , and stop the error message displaying on the webpage . Thanks <?php try{ echo $_SESSION['btn']; } catch(Exception $ex) { $_SESSION['btn'] = "Check Available"; echo $_SESSION['btn']; } ?>"/> Please help Hello, I was trying out some code to check out how some of the php settings work and when i tried allow_call_time_pass_reference to see if it works, it doesn't spew out any warning or error like the comments in the .ini file mention (or in the manual sites). Maybe i'm not using some other setting in order to see this? Here is my EXACT code. <?php ini_set('display_errors',1); error_reporting(-1); $variable = 'String'; function display($variable) { return $variable; } echo display(&$variable); ?> Outputs : String. No errors, no warnings. I'm running PHP Version 5.3.2-1ubuntu4.5 I am new to the Laravel Framework, doing an internship and at the very end.. I need some assistance please with some try catch error, Its supposed to throw an error if the site name is already in the database.. If someone could help me please and thank you ..
```
public function create() { return View::make('edit.create'); } public function edit( $clientsite ) { return View::make('edit.edit', compact('clientsite')); } public function saveCreate() { $input = Input::all(); try { $clientsite = new ClientSite; $clientsite->siteName = $input['siteName']; $clientsite->description = $input['description']; $clientsite->launchDate = $input['launchDate']; $clientsite->save(); //ClientSite::whereSiteName($clientsite->siteName)->first(); ClientSite::where('siteName', $clientsite->siteName)->first(); $clientID = $clientsite['clientID'];//getting clientID for use in join query //queries for retrieving features of each group for the selected client $clientFeatures = DB::table('features')->join('clientFeatures', function($join) use($clientID) { $join->on( 'clientFeatures.featureID', '=', 'features.featureID') ->where('clientFeatures.clientID', '=', $clientID); })->get(); $groupIDs = array(); foreach ($clientFeatures as $c) { $groupIDs[] = $c->groupID; } catch(\Illuminate\Database\QueryException $e) { return View::make('profiles.clientProfiles')->with('clientsite',$clientsite) ->with('groupIDs',$groupIDs) ->with('clientFeatures',$clientFeatures) ->with('status','<strong>'.$siteName.' Site already exist!</strong>'); ; } ``` https://github.com/webdevdea/MyDyn ( i have not pushed these changes because I have an error ) I want to use PEAR if it's installed and the regular "mail()" function if not. But to check for PEAR being installed, I can't check for the class PEAR existing because I have to include "Mail.php" first. The problem is that even though this statement works perfectly: Code: [Select] include_once "Mail.php"; This will ALWAYS be false: Code: [Select] if ( file_exists( "Mail.php" ) ) ... So how do I check for PEAR? If I just include the file, it throws a warning error that I can't seem to catch in a try..catch. Why exactly was "try" and "catch" introduced into PHP? What are the benefits of using it over "if and else" and other similar methods? Any insight is much appreciated. |