What is the scope of error_get_last() in PHP? - php

I've been using error_get_last() in combination with register_shutdown_function() to create an error report for some of my scripts. It's been working fine for the most part.
Every now and then, though, the error report will show an error from a different script.
I'm not quite sure how that can happen. Can anyone explain?
I'm wondering if error_get_last() in one script should be able to show errors from different scripts and if that's the case, under what circumstances would that happen?
My only guess is that the error is saved for a short time so that a script that finishes execution at almost the same time might catch another script's errors. Could that be it?
This is the code I use and have included in many different PHP files:
function send_error_report($extra) {
global $conn;
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
$error = error_get_last();
if (isset($error)) {
$error_str = "Type: " . $error['type'] . " | Message: " . $error['message'] . " | File: " . $error['file'] . " | Line: " . $error['line'];
$sql = "INSERT INTO `error_report` (`script`, `error`) VALUES ('$url', '" . $error_str . " - " . $extra . "');";
$conn->query($sql);
}
}
register_shutdown_function('send_error_report', '');

Related

PHP - Login via form and grab cookie

I'm trying to login to the following URL: pitangui.amazon.com
I have tried using cURL as well as libraries like https://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
However, I'm getting the following error using the webscraper via Amazon:
This is my PHP code:
<?php
require_once "support/http.php";
require_once "support/web_browser.php";
require_once "support/simple_html_dom.php";
$url = "https://pitangui.amazon.com";
$web = new WebBrowser(array("extractforms" => true));
$result = $web->Process($url);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
$form = $result["forms"][0];
$form->SetFormValue("email", "myemail#gmail.com");
$form->SetFormValue("password", "mypass");
$result2 = $form->GenerateFormRequest("signIn");
$result = $web->Process($result2["url"], "auto", $result2["options"]);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
// Do something with the results page here...
print_r($result);
}
}
?>
I'm first trying to get the login working, then I will grab the cookie via $_SERVER['Cookie']
add
$form->SetFormValue("create","0");

get error throwing php script name inside class

I am using Bennett Stone php wrapper class for mysqli operations. class is working fine without any issues. There is a function inside it (shared below) which sends an email to administrator for any kind of mysqli errors.
Issue
There are 100's of scripts using this class, I am not able to find out which script thrown any particular error.
What i want
I want to get the full path of error originating script inside class from where query originated. for example, test.php contains query & post execution if any error comes out then i want complete path of test.php inside error handling function along with error details (shared below).
What i can do
Class modification I can do by my own
I am getting details like this:
Error at 2016-08-23 05:44:18:
Query: SELECT email FROM users WHERE
Error: 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 '' at line 1
Error handling function
public function log_db_errors( $error, $query )
{
$message = '<p>Error at '. date('Y-m-d H:i:s').':</p>';
$message .= '<p>Query: '. htmlentities( $query ).'<br />';
$message .= 'Error: ' . $error;
$message .= '</p>';
if( defined( 'SEND_ERRORS_TO' ) )
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Admin <'.SEND_ERRORS_TO.'>' . "\r\n";
$headers .= 'From: systems<noreply#'.$_SERVER['SERVER_NAME'].'.com>' . "\r\n";
mail( SEND_ERRORS_TO, 'Database Error', $message, $headers );
}
else
{
trigger_error( $message );
}
if( !defined( 'DISPLAY_DEBUG' ) || ( defined( 'DISPLAY_DEBUG' ) && DISPLAY_DEBUG ) )
{
echo $message;
}
}
Put these lines somewhere above all your codes:
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and you will have every error logged with a stack trace. While all this bushy "log_db_errors" stuff will be thrown away.
the problem solved.
NB. This wrapper class is just terrible. Utilizes almost every bad practice ever exists.
What you can do is catching exception and edit error message, using some magic php const in it : PHP: Magic constants
Example, in your class, around the query :
try {
// your query
} catch (Exception $e) {
// launch your log_db_errors() function, with some of const, like __CLASS__, __LINE__, etc :
$error = '[' . __FILE__ . '][' . __CLASS__ . '::' . __FUNCTION__ . '][' . __LINE__ . '] : ' . $e->getMessage();
// ...
}

file_get_contents - "Use of undefined constant code - assumed 'code'"

I'm trying to add a basic new-grabber for a site I'm making and cannot figure out for the life of me what is causing this error. The file I'm grabbing is a plain-text file, completely accessible.
I've seen it posted before and the OP is calling something like:
$var = $data[str] instead of $var = $data['src']
But I am not calling anything with "code" in the name.
I receive this error upon running my code:
HTTP request failed. Error 8 on line 123: Use of undefined constant
code - assumed 'code' in file /usr/local/lib/php/head.php
Here is my entire file below:
<?
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if (!$e_news === true) {
$error = error_get_last();
echo "HTTP request failed. Error " . $error['type'] . " on line " . $error['line'] . ": " . $error['message'] . " in file " . $error['file'] . "<br>";
} else {
echo "Everything went better than expected";
}
if ($e_news === true) {
$news = explode("|", $e_news);?>
<h4>News - <? echo (!empty($news) ? $news[1] : "v0.0.1");?> <small><? echo (!empty($news) ? $news[0] : "5/22/2016");?></small></h4>
<p><? echo (!empty($news) ? $news[2] : "Loading news failed, or there is currently no news.");?></p>
<?
} else {
echo "<h4>News failed to load</h4>";
}
?>
Do you guys know what I'm missing or doing wrong here?
As already suggested by #John Stirling, "the issue is elsewhere".
More precisely the reported Error 8 on line 123... etc is related to an error that happened previously, elsewhere.
And your current code is responsible to make this error appear now because you wrote:
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if (!$e_news === true) {
$error = error_get_last();
This way, the following happens:
Each time file_get_contents() is successfull, $e_news gets its content.
Then $e_news === true is FALSE (even if this content is empty, because you used ===), and if (!$e_news === true) is always TRUE.
So there is no error now, and your error_get_last() gets the trace of the last error that previously happened, elsewhere...
In fact, for your code to work as expected you should rather do something like this:
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if ($e_news === false) {
$error = error_get_last();
echo "HTTP request failed. Error " . $error['type'] . " on line " . $error['line'] . ": " . $error['message'] . " in file " . $error['file'] . "<br>";
echo "<h4>News failed to load</h4>";
} else {
echo "Everything went better than expected";
$news = explode("|", $e_news);?>
<h4>News - <? echo (!empty($news) ? $news[1] : "v0.0.1");?> <small><? echo (!empty($news) ? $news[0] : "5/22/2016");?></small></h4>
<p><? echo (!empty($news) ? $news[2] : "Loading news failed, or there is currently no news.");?></p>
<?
}

How to debug php code in this case?

I 'm developing an android app which connects to database using PHP API. It's the first time for me to encounter PHP.
What happens is that I "POST" parameters to the php code with a URL to connect to it then php makes a query to my database and store them ... the issue is that all I see is what happens in logcat, I have no idea what is goin on with the PHP so if there is something wrong in there what can I do to debug it ?
Note : I 'm already familiar with echos and var dump I 'm looking for fully debugging tool that will allow me to debug the script without actually running it directly and by that I mean accessing it from my android project.
In such cases i log / append all actions on php side into a file - with a simple
file_put_contents({file}, {data}, FILE_APPEND);
.
u could also catch nearly every error in php with following methods:
set_error_handler({YOUR_ERROR_HANDLER}, E_ALL);
register_shutdown_function({YOUR_ERROR_HANDLER});
http://php.net/manual/de/function.set-error-handler.php
http://php.net/manual/de/function.register-shutdown-function.php
example code of how would i test an envoirement in php, which i could not debug direct:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// will be triggered on every php shutdown - will log the last error (if one occurs)
register_shutdown_function(function()
{
// get last error
$aError = error_get_last();
if(!empty($aError))
{
logAction('called from register_shutdown_function | ' . $aError['message']);
}
});
// will be triggered on every error
set_error_handler(function($iErrCode, $sErrorText, $sErrorFile = '', $sErrorLine = '')
{
logAction('called from set_error_handler | Code: ' . $iErrCode . ' Text: ' . $sErrorText . ' File: ' . $sErrorFile . ' Line: ' . $sErrorLine);
}, E_ALL);
// will be triggered on every exception
set_exception_handler(function(\Exception $e)
{
logAction('called from set_exception_handler | Code: ' . $e->getCode() . ' Text: ' . $e->getMessage() . ' File: ' . $e->getFile() . ' Line: ' . $e->getLine());
});
// main log / debug method
function logAction($sText)
{
$sDate = date('Y.m.d H:i:s');
file_put_contents('debug.log', $sDate . ': ' . $sText, FILE_APPEND);
}

PHP code is displayed in user's browser

I have a php script like this :
<?php
$confirmationCode = trim($_GET['confcode']);
$_SERVER['REMOTE_ADDR'] = 'xxx.xxx.xxx.xxx';
$emailLogId = 1;
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>' .'xxxxx' . $emailLogId . '###'; //exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
It is running on my server. Actually some people are complaining that they are seeing the source code of this script( pasted below ) on their browser and they send me snap shot of this issue:
' .'xxxxx' . $emailLogId . '###'; //exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
Actually I am really confused because I am not able to reproduce this problem, but 3-4 people are complaining about same the thing.
Do you have any idea what is the issue?
Yes, similar thing happened with me too.
2 things:
. Apache configuration.
Make sure php engine is ON. If you cannot access your apache configuration file then, add this in your .htaccess:
php_flag engine on
. CDN.
If you are using any Cloud Distribution Network, it is time for you to ask them to purge your existing cache and re-load the new one.
Browser will display PHP source code ONLY AND ONLY if apache configuration is going wrong.
Hope that helps.
EDIT:
After reading Sabin's comment, I gave a second look at the code.
Problem is, he has ASSIGNED the value to $_SERVER['REMOTE_ADDR'] (line 3)
Here is how it should be:
<?php
$confirmationCode = trim($_GET['confcode']);
$ip = 'xxx.xxx.xxx.xxx';
$emailLogId = 1;
//Whatever conditions.
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') {
// print '<pre>' .'xxxxx' . $emailLogId . '###'; exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
However, echo-ing the source code cannot be due to this. I would ask you to put FULL FILE so that we could see if you are missing a closing single quote!
It sounds like PHP is not working at all. The only reason you are not seeing the first part, is because your browsers is parsing it as if it were an HTML tag.
And Please try to print phpinfo() once,
please check for the below link, for more details
PHP code displayed in browser

Categories