Logging Paradigms in PHP - php

Is it just me or is do others have trouble understanding how logging works in PHP?
I come from a Java/Python logging world where you usually have access to an inbuilt utility for logging that allows you to either specify a log level or call a log level function (like logger.info('foo');). The core library would then organise from configuration values how the log appears and in what file it ends up in.
However out of the many documents I've read and google searches done on the subject, I seem to be missing some sort of fundamental understanding of the way PHP logging works.
what I've found so far is that PHP has:
the log_errors=[0|1] ini config directive, which enables logging of errors (if you would believe it),
the error_log=/path/to/file, not to be confused with the error_log() function, which defines the file which errors are logged to
an additional note on the error_log value, I have found that in apache2, when you set this value as an absolute path, Apache will honor the value, however any other relative path will default to the ErrorLog value of the Apache server (usually /var/log/[httpd|apache2|apache]/error.log)
a syslog() and error_log() function which defers messages to either the PHP system logger (/var/log/syslog) or the SAPI logger respectively (see this post and notice on error_log).
I have no control from the method signature what level message I have logged. (I know there are different levels as I can see when I receive an Illegal string offset Warning or Undefined variable notice).
# php internal log examples
[10-Mar-2017 02:45:17 UTC] PHP Warning: Illegal string offset 'username' in /var/www/html/foobar.php on line 123
[10-Mar-2017 02:45:17 UTC] PHP Notice: Undefined variable: col_info in /var/www/html/barfoo.php on line 89
[10-Mar-2017 02:45:17 UTC] my message using error_log() function without any level indication.
Now I realise that I may output the level myself, but am I to believe I cannot integrate with PHP's own level system for the sake of easy config? I choose to believe otherwise.
All my searches thus far have only informed me how to disable or enable these levels and not how to output a message with a given level.
I am hoping to be directed to some fundamental documentation on the reasoning behind logging in PHP... Or I may eat my shoe out of frustration from this simple endeavour.
P.S. I am using Apache2 as my web server.
Update:
I can see that you may log to syslog with syslog($ERRNO, $ERRMSG) and this sets the log_level (LOG_DEBUG, LOG_INFO, etc...). It would be nice to hijack the log_level configuration without using the implicit syslog file. i.e. my_error.log as opposed to syslog. I'm beginning to believe that log levels are internal ideas in the PHP core.

Related

How do I detect error in shared hosting/live server?

In localhost, we can easily find the errors like missing semicolon in line number xxx, undefined variable in line number xxx,class already declared etc. But, when I upload all my files in shared hosting and try to see results in the web browser, I get to see same error page everytime and it's really really hard to detect what exactly caused the error. The project which i uploaded to the live server was written in laravel. I have tried 'Display errors On' in php.ini, error_reporting(E_ALL). I have even checked the error_log in the root directory but, those logs are usually from few days ago. error image description here
Any possible solutions ? Or should I switch to server where proc_open is enabled?
Check this:
https://laravel.com/docs/7.x/errors
Laravel handles errors and can write them in a log file.
You can customize it if you want, but I don't think it's necessary to do so.
If you dont use any frameworks or ones that don't support such a feature for that matter you could always use the native PHP function set_error_handler and catch errors and write them in a log file.
Note: BEWARE of the excessive log file size. If your project has a lot of visitors or has lots of notices and warnings, this log files can get excessively massive, unreadable, and consuming your space. Don't turn it off, it's always good to know where are the errors, but check and debug them often and delete them when not needed.

CodeIgniter returns a blank response, no error message. (Possibly related to filemtime(): stat failed)

I've written some code as part of an existing CodeIgniter 2 application, which is designed to extract some data from the database, generate preview images, transform the data, then send it to a third-party search service. It works perfectly on my development environment. However, after deploying it to the staging environment, I get an empty 200 response from the server.
The Apache error log shows nothing, the Apache access log just has a single entry with the 200 code. This is despite error_reporting being set to E_ALL and display_errors being set to true. The only error message I am seeing is in the .php log file generated by CodeIgniter within the application directory. Here it is:
ERROR - 2017-04-18 12:40:08 --> Severity: Warning --> filemtime(): stat failed for /var/www/vhosts/gvip.io/staging/current/wwwroot/cache/made/23f4b9ae97bceb7ea30e71bdc2a48ece_27_27_ffffff_all_2_s_c1.JPG /var/www/vhosts/gvip.io/staging/releases/20170417130504/.app/libraries/Ce_image.php 2236
Sure enough, line 2236 of the Ce_image library does include a call to filemtime:
$finaltime = #filemtime( $this->path_final ); //filetime of cached image
However,
I don't see how this error would cause the application to die (and not return the expected HTML response). It is listed as Warning, not Fatal.
If this is the problem, I'm honestly rather lost as to how to debug it. The line that's pointed to in the error message is part of a library, nested inside a long function, called from another function, etc.
It's certainly true that the file referenced in the error message doesn't exist.
Interestingly, the first time I ran the code, about 92 similar error messages were generated, each with a different file name. On subsequent runs, it only generated one error message each time (with the same file name each time).
I tried setting the CodeIgniter logging level to 4 (all messages), but it didn't really reveal anything new. Apart from some messages about initializing helpers and classes, it just had around 3300 lines stating XSS Filtering completed. (The query only has around 2600 records, so I'm not sure why 3300.)

hide/resolve warning messages on my website

Warning: mkdir() [function.mkdir]: No such file or directory in
/var/www/humspm/data/www/humspm.com/gettext.php on line 17 CMD:EXIT
can you please help me to resolve this issue
Thanks in adavence
You can turn off notifications in PHP:
<?php error_reporting(0); ?>
More:
http://php.net/manual/de/function.error-reporting.php
http://www.w3schools.com/php/php_error.asp
I recommend to solve the issue with correct coding instead of just turning off errors and warnings!
For your issue, just check if the file or directory exists before you try to work with the filesystem. (check the PHP manual for file_exists() and is_dir())
From the CAKEphp manual:
Error configuration is done inside your application’s
app/Config/core.php file. You can define a callback to be fired each
time your application triggers any PHP error - exceptions are handled
Exceptions separately. The callback can be any PHP callable, including
an anonymous function. The default error handling configuration looks
like:
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true ));
You have 5 built-in options when configuring error handlers:
handler - callback - The callback to handle errors. You can set this
to any callable type, including anonymous functions.
level - int - The
level of errors you are interested in capturing. Use the built-in PHP
error constants, and bitmasks to select the level of error you are
interested in.
trace - boolean - Include stack traces for errors in
log files. Stack traces will be included in the log after each error.
This is helpful for finding where/when errors are being raised.
consoleHandler - callback - The callback used to handle errors when
running in the console.
If undefined, CakePHP’s default handlers will
be used. ErrorHandler by default, displays errors when debug > 0, and
logs errors when debug = 0. The type of errors captured in both cases
is controlled by Error.level. The fatal error handler will be called
independent of debug level or Error.level configuration, but the
result will be different based on debug level.
Link to manual
First of all check what causes this issue,
Check folder permission
Check whether you have privileges to create a directory inside the specific location.
Still if you want to silence the error
You can add # in front of mkdir
You can disable error reporting.
Please see your directory structor carefully.According to url something is repeating into your url.
/var/www/humspm/data/www/humspm.com/gettext.php
Also see mkdir is only working with the directory path, not the URL or domain.
You should have to point to your subdomain's absolute path, not the URL.
I ran into the same error on a client's WordPress site:
(Warning: mkdir() [function.mkdir]: No such file or directory in /var/www/humspm/data/www/humspm.com/gettext.php on line 17 CMD:EXIT)
I found that their index.php file was calling a file named cache.php on line 1.
cache.php contained obfuscated code that appears to have been attempting to use the invalid absolute path. The use of obfuscated code probably explains why you couldn't find any reference to that directory path in your code.
The actual file name may differ in your site, I'd recommend looking out for any unfamiliar php files in the same directory as your index.
Commenting out the line in index.php that called to this cache.php fixed the issue with the warning message.
However, the file itself appears to be malicious so I'm recommending that my client harden their security and scan for additional malware. You might want to do the same.

imagefill() causing 'Premature end of script headers'

I'm posting because after hours of searching I'm utterly confounded. Here's the deal. My Laravel application uses the PHP Image Workshop bundle. Everything seems to be working fine, except if I try to make a resizeInPixel() call or a cropInPixel() call (or similar calls) the server throws an internal server error. If I investigate the error log I see:
Premature end of script headers: index.php
This only occurs when I use the resize and crop related methods (i.e. image processing). I can initFromPath() with no issue, and I can use the save() method without issue. Only the image processing methods cause the internal server error.
I've also read online that this can be the result of a suphp_log file exceeding 2GB. I've tracked down and cleaned out that file, but to no avail.
Any thoughts are most welcome! Even if they're just general "have you tried...".
UPDATE
I've narrowed it down to a particular line in the Image Workshop code. This line is causing the error:
imagefill($image, 0, 0, $color);
Additionally, this error only occurs when the color is created using imagecolorallocatealpha, NOT when it is created using only imagecolorallocate.
There are some great hints for solving this issue at Liquidweb.com. My money is on #2 (see bold text) because you are getting the error when doing image manipulations:
Sometimes when executing a script you will see an error similar to the following:
Premature end of script headers: /home/directory/public_html/index.php
This error occurs because the server is expecting a complete set of HTTP headers (one or more followed by a blank line), and it doesn’t get them. This can be caused by several things:
Upgrading or downgrading to a different version of PHP can leave residual options in the httpd.conf. Check the current version of PHP using php -v on the command line and search for any lines mentioning another version in the httpd.conf. If you find them, comment them out, distill the httpd.conf and restart apache.
The RLimitCPU and RLimitMEM directives in the httpd.conf may also be responsible for the error if a script was killed due to a resource limit.
A configuration problem in suEXEC, mod_perl, or another third party module can often interfere with the execution of scripts and cause the error. If these are the cause, additional information relating to specifics will be found in the apache error_log.
If suphp’s log reaches 2GB in size or larger you may see the premature end of scripts headers error. See what the log contains and either gzip it or null it. Restart apache and then deal with any issues that the suphp log brought to light. The suphp log is located at: /usr/local/apache/logs/suphp_log
The script’s permissions may also cause this error. CGI scripts can only access resources allowed for the User and Group specified in the httpd.conf. In this case, the error may simply be pointing out that an unauthorized user is attempting to access a script.
UPDATE:
After some more info in the comments, I still feel this is a memory related thing.
According to this SO wiki: About gdlib
Warning: Image functions are very memory intensive. Be sure to set memory_limit high enough
What is your PHP memory_limit? Can you crank it up a bit?

What setting(s) determine whether PHP will throw an error on accessing an array using a non-existent index?

I'm trying to get a PHP 5 application working on IIS7.
This application appears to have been built under the assumption that accessing an array using an index that doesn't exist will simply return null, without raising an error and halting the program.
Given the following code:
<?PHP
$testarray = array();
print $testarray[1];
print 'hello';
?>
When accessed through Apache (installed under WampServer), it will simply print "hello" on the screen, and ignore the error.
When accessed through IIS 7, it generates the following exception:
PHP Notice: Undefined offset: 1 in C:\Users\Jonathan\Projects\MyApp\api\inf.php on line 3
PHP Stack trace:
PHP 1. {main}() C:\Users\Jonathan\Projects\MyApp\api\inf.php:0
But if I comment out the first print statement, it executes correctly and displays "hello".
Both IIS and Apache are pointing to the same code-base, using the same instance of PHP (the version is 5.3.5) and the same PHP config.
Since this is a language issue, I don't see why it would matter what web-server I use, but I'm totally lost as to why one instance works when the other throws an error.
What setting might be responsible for this difference?
(If there's a way to configure IIS to be more lenient, I'd prefer that, rather than re-factoring the whole application to check arrays for indexes before accessing them.)
You can change this behavior by altering the error reporting settings in php.ini.
You can set different levels of error reporting. For example, trying to access an undefined array index is an E_NOTICE. You can choose whether or not to display errors of this type. To see what the other levels are, see this page.
Any production website shouldn't display any errors whatsoever, while you should probably display every error in a development environment.

Categories