Undefined Index Error Reporting in WAMP and PHP - php

I'm using wamp to develop a php application. My problem is that everytime I call a variable that sometimes happens to not have a value, I get an error that says it's an undefined index. Is there a way to change the error reporting to not display this error? I have to use isset to determine if it's set or not before I output the variable, but I don't want to have to do this. There are areas of my application that make this method inefficient.

If you don't want to change error_reporting level you should check, is variable exists, before using it. You may use
if(isset($var))
for it. You may add some function, to not write it always. Example:
function getPost($name,$default=null){
return isset($_POST[$name])?$_POST[$name]:$default;
}
Usage:
getPost('id');
getPost('name','Not Logged In');

You can just turn off the mechanism in php.ini.
This thread would help you.
http://www.wampserver.com/phorum/read.php?2,70609,70700
But it generally its better to take care of undefined variables as they might save you some run time trouble.
Update:
In php.ini change
error_reporting = E_ALL to error_reporting = E_ALL & ~E_NOTICE

There are multiple ways to get around this:
error_reporting(0) Use this at the top of your script
set display_errors = Off in php.ini
Use '#' before the statement that generates an error
But unless you are writing something trivial you absolutely must use array_key_exists or if(!empty($arrayName['key'])) for everything sent by the user.

Try this:
if(!isset($var)) $var="";

PHP.ini files reside in both :
bin\php\php5.x
and
bin\apache\apache2.x\bin
be sure to make the changes in the apache folder version.
Also setting :
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
leaves errors from being displayed on the client, but still allows them to be logged in the error log.

Related

PHP: skip code on any error

I have written a supersimple code to track my blog's activity.
I'm including this file on every page at the very begining:
<?php
session_start();
if ($_SESSION["i"] == "") {
$_SESSION["i"] = rand(0,9) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90));
}
$r = $_SERVER['HTTP_REFERER'];
if ($r == "") {$r = "Direct";}
$u = $_SERVER['REQUEST_URI'];
include ($_SERVER['DOCUMENT_ROOT'].'/db.php');
$stmt = $conn->prepare("INSERT INTO analytika (id, page, referrer, visit, time) VALUES (DEFAULT, ?, ?, ?, DEFAULT)");
$stmt->bind_param("sss",$u,$r,$_SESSION["i"]);
$stmt->execute();
$stmt->close();
$conn->close();
?>
Problem is, what do I do to prevent echo's from PHP when error occures?
I've found error_reporting(0); but that obviously isn't the solution, because my page wont load further the error. And since im including things into DB, problems may really occur.
So, how do I rewrite my code to skip itself if something goes wrong and the page loads on as it would normally? Thanks
PHP 7.0
You would typically use a try/catch block to handle errors that you think may occur e.g. "what do you want to happen if your database is unavailable?"
https://www.w3schools.com/php/php_exception.asp
In PHP you can suppress error messages using the # operator. Again though it's recommended that you handle errors. This wouldn't prevent an error in your script from stopping execution.
http://php.net/manual/en/language.operators.errorcontrol.php
When you're using PHP in production, it's highly recommended not to show exceptions and errors, and even notices and warnings. To prevent showing these bad characters, you have to change display_errors option in php.ini file (see the link for more details).
However, there's another option. For instance, if you could not change ini file, you can use ini_set() function on every page you want to disable error reporting. But there is a problem with ini_set(); from php.net:
Note: Although display_errors may be set at runtime (with ini_set()), it won't have any effect if the script has fatal errors. This is because the desired runtime action does not get executed.
Also, to track errors, you can set log_errors and error_log options, by changing php.ini or using ini_set() function.

warning if variable does not exist

If I try to use a variable which doesnt even exist in PHP, I dont get any errors or notices. In the example below the return value is "null". I'd like to see some form of notification if that happens so that I can find bugs in my code more easily.
echo $doesNotExist -> something; //returns null
The error reporting in my php.ini is the following
error_reporting = E_ALL
What do I have to do to see notifications when accessing varibles that don't exist?
To clarifiy this:
I know that I can check if a variable exists by using isset(). That's not what I want though. I want to get a notification in case I accidentaly try to use a variable that does not exists. For example if I misspell the name of a variable.
display_errors = On is in my php.ini
As well as error_reporting, you may need to turn on display_errors, which should be off in production environments.
Production environments can use log_errors instead, which outputs the errors to the file named in the error_log directive.
I generally use thw following;
if(isset($var) && !empty($var)) {
//Do something with $var
} else {
//Define $var
}
As said in a previous answer you also need to turn error reporting on in the php.ini
what you do is perfectly valid in PHP. It just creates and instantiates that variable at runtime, and doesn't throw an error like other languages.
even isset would not work too well. Say you set an object variable with a wrong name. If you do isset on that name, it will be true. If you do isset on the correct name, it will be false.
Example:
class test{
public $name1;
}
$test = new test;
$test->name2 = 'wrong';
var_dump($test);
prints: object(test)#1 (2) { ["name1"]=> NULL ["name2"]=> string(5) "wrong" }

How to make smarty output debug info when template fails to compile?

I'm already set its debugging option to true,but when there's error in smarty template(i.e. there is no corresponding plugin for a specific smarty_modifier),nothing is output for information.
UPDATE
For anyone that wants to have a try,this is the most simple template I can think of :
{$var|nosuch_modifier}
1- First, you can check if error_reporting is on. this is usually done in php.ini but you can place these statements on top of your php source.
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
and make sure it is not disabled elsewhere.
2- smarty may report errors as throwing an exception. You can define a global exception handler to catch them, here is an example;
try {
// place your code here
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Update upon comments:
The only reason I can think of is that you've set compile_check to false.
$tpl->compile_check = false;
In this case, Smarty will show the latest compiled source, whatever you do to the tpl file. So, did you check and set compile_check to true?
$tpl->compile_check = true;
Try
ini_set('display_errors', true);
error_reporting(E_ALL);
in the PHP code.
Smarty error reporting can be set manually.
$smarty->error_reporting = E_ALL ^ E_NOTICE;
Some comments from the Smarty.class.php
error muting is done because some people implemented custom
error_handlers using http://php.net/set_error_handler and for some
reason did not understand the following paragraph:
It is important to remember that the standard PHP error handler is
completely bypassed for the error types specified by error_types
unless the callback function returns FALSE. error_reporting() settings
will have no effect and your error handler will be called regardless -
however you are still able to read the current value of
error_reporting and act appropriately. Of particular note is that this
value will be 0 if the statement that caused the error was prepended
by the # error-control operator.
Smarty deliberately uses #filemtime() over file_exists() and
filemtime() in some places. Reasons include
- #filemtime() is almost twice as fast as using an additional file_exists()
- between file_exists() and filemtime() a possible race condition is opened, which does not exist using the simple #filemtime() approach.

What can I do to make my PHP web application fail in a more noisy way?

What can I do to make my PHP web application fail in a more noisy way?
I am using an MVC pattern and often when classes fail to load or failures they do so without error.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', '1' );
ini_set( 'log_errors', '1' );
function error_handler($errno, $errstr, $errfile, $errline) {
system('/usr/bin/mplayer /home/user/music/Moras_Modern_Rhythmists/Mr._Ghost_Goes_to_Town.mp3', $retval);
return true;
}
set_error_handler( "error_handler" );
?>
Depending on what your error reporting level is at, you could try raising it via .htaccess.
php_value display_errors 1
php_value error_reporting 2147483647
Use the require_once method to load your files instead of include.
I think that's what you're asking, right?
If you're doing testing, check whether your php.ini settings has display_errors property turned on.
<? ini_set("Melodramatic", "true"); ?>
The easy answer: die('A fatal error occurred')
In a PHP application I wrote, I came up with a convention of using a variable or class member named $err_msg which is initially set to null . When an error happens, set it to a human readable string. When it's time to check errors, check $err_msg and put it on display for the end-user. If it's an AJAX call, echo $err_msg on failure, echo 'OK' on success.
In my case, I wrote a simple jQuery-based status box that can display busy indicators and errors. When an AJAX call returns an error message, I make the status box fade in with a red background and display the error message. It's quite nice and uniform.

How to turn off mysql errors from being displayed to screen in CodeIgniter

Even though error_reporting is set to 0, database errors are still being printed to screen. Is there a setting somewhere I can change to disable database error reporting? This is for CodeIgniter v1.6.x
EDIT: Re: Fixing errors - Um, yes. I want to fix the errors. I get error notices from my error log, not from what my visitors see printed to their screen. That helps no one, and hurts my system's security.
EDIT 2: Setting error_reporting to 0 does not affect CodeIgniter's built-in error logging class from writing to the error log.
Found the answer:
In config/database.php:
// ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
so:
$db['default']['db_debug'] = FALSE;
... should disable.
In addition to Ian's answer, to temporarily disable the error messages:
$db_debug = $this->db->db_debug;
$this->db->db_debug = false;
// Do your sketchy stuff here
$this->db->db_debug = $db_debug;
You don't want to change
error_reporting to 0, because that will
also suppress errors from being
logged.
instead you should change
display_errors to 0
This doesn't explain why you are
getting errors displayed though,
assuming error_reporting is actually
0. Maybe the framework handles these errors
You can edit the /errors/db_error.php file under the application directory - that is the template included for DB errors.
However, you should really just fix the errors.

Categories