Is there any way to catch fatal error using eval()? - php

$code = 'php statement';
// getting perse error
function perse_error_check($code){
if(eval($code) === "true"){
return "no perse error";
}
if(eval($code) === "false"){
return "perse error found";
}
}
// getting fatal error
function fatal_error_check($code){
.......................................
.......................................
}
Can you help me to complete the second function? Actually I am not sure weather it is possible or not.

The following writes the PHP code to another file.
It then uses command line execution to parse the file and check for erros:
/* Put the code to be tested in a separate file: */
$code = '<?php echo "Test"; ?>';
file_put_contents('check.php', $code);
/* Parse that file and store the message from the PHP parser */
$x = exec( 'php -l check.php');
/* Check the message returned from the PHP parser */
if(preg_match('/Errors parsing/i',$x))
{
echo 'The code has errors!';
}
else
{
echo 'The code looks good!';
}
/* delete the file */
unlink('check.php');
The benefit is that the code doesn't run, it just gets parsed. However I assume you would then write that code to a file and use it... so like others mentioned, be VERY careful. Use things like open_basedir (and test it) to restrict access to specific directories, manually check the code before including it in production... etc.

There is a simple way. Put your PHP code in an another file. For an example: index.php and check.php . Put your PHP code in check.php.
Now in index.php write:
$check_data = file_get_contents("yourhosturl/allotherdirectory/check.php");
if(preg_match("/Fatal error/",$check_data)){
echo "fatal error found";
}

Related

Failing to connect and output my json requests

So I have access to a public web API and I'm trying to pull information from it and use it in a PHP if statement. I have tried a few different ways but each time I fail? I will post all of my failed attempts to see if anyone knows what I'm doing wrong...
This is the JSON file;
{
"players": [
{
"SteamId": "76561198074117457",
"CommunityBanned": false,
"VACBanned": true,
"NumberOfVACBans": 1,
"DaysSinceLastBan": 738,
"NumberOfGameBans": 0,
"EconomyBan": "none"
}
]
}
Attempt 1 using a PHP function
(php file)
<?php
function VACBanned($vacban) {
if ($vacban == "false") {
return "";
}
elseif ($vacban == "true") {
return "<p>This user has a vac ban...</p>";
}
}
?>
(index file)
<html>
<body>
<?=VACBanned($json['players'][0]['VACBanned']);?>
</body>
</html>
This would output the following error;
PHP Notice: Undefined index: players in index.php on line 13
I initially thought that the API must not have been correctly connecting, so I went into the PHP file and echoed my user ID like so $json["players"][0]["SteamId"]; and it worked... But when I went and attempted to perform the same thing in the Index <?php echo $json["players"][0]["SteamId"];?> I got the error again? When I did this in the php file $test = $json["players"][0]["SteamId"]; and this in the index <?php echo $test;?>it echoed my steam id?????? I tried to just call the if statement in the index like so
<?php
if ($vac_ban == "false") {
return "123";
}
else {
return "<div class='ban_vac'><p>1 VAC BAN<br>76 Days Ago</p></div>";
}
?>
and $vac_ban would be stated in the php file as = $json["players"][0]["VACBanned"]; but that just made it outpute everything above the <? tag and nothing below it. Note the whole time during this I had the two files connected using include('filename'); and error_reporting(E_ALL); ini_set("display_errors", 1); and the json is decoded json_decode(file_get_contents($api_url), true);
You must decode json before use with PHP:
$array = json_decode($data, true);
Now you can do what you want:
VACBanned($array['players'][0]['VACBanned']);
Take a look: json_decode
So, I worked it out for anyone who might be having this issue, I just put my PHP code into the one document, it looks messy but works :)

AJAX call returns status 200 but no content

I have a simple AJAX call that retrieves text from a file, pushes it into a table, and displays it. The call works without issue when testing on a Mac running Apache 2.2.26/PHP 5.3 and on an Ubuntu box running Apache 2.2.1.6/PHP 5.3. It does not work on RedHat running Apache 2.2.4/PHP 5.1. Naturally, the RedHat box is the only place where I need it to be working.
The call returns 200 OK but no content. Even if nothing is found in the file (or it's inaccessible), the table header is echoed so if permissions were a problem I would still expect to see something. But to be sure, I verified the file is readable by all users.
Code has been redacted and simplified.
My ajax function:
function ajax(page,targetElement,ajaxFunction,getValues)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
document.getElementById(targetElement).innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open('GET','/appdir/dir/filedir/'+page+'_funcs.php?function='+ajaxFunction+'&'+getValues+'&'+new Date().getTime(),false);
xmlhttp.setRequestHeader('cache-control','no-cache');
xmlhttp.send();
}
I call it like this:
ajax('pagename','destelement','load_info');
And return the results:
// Custom file handler
function warn_error($errno, $errstr) {
// Common function for warning-prone functions
throw new Exception($errstr, $errno);
}
function get_file_contents() {
// File operation failure would return a warning
// So handle specially to suppress the default message
set_error_handler('warn_error');
try
{
$fh = fopen(dirname(dirname(__FILE__))."/datafile.txt","r");
}
catch (Exception $e)
{
// Craft a nice-looking error message and get out of here
$info = "<tr><td class=\"center\" colspan=\"9\"><b>Fatal Error: </b>Could not load customer data.</td></tr>";
restore_error_handler();
return $info;
}
restore_error_handler();
// Got the file so get and return its contents
while (!feof($fh))
{
$line = fgets($fh);
// Be sure to avoid empty lines in our array
if (!empty($line))
{
$info[] = explode(",",$line);
}
}
fclose($fh);
return $info;
}
function load_info() {
// Start the table
$content .= "<table>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>";
// Get the data
// Returns all contents in an array if successful,
// Returns an error string if it fails
$info = get_file_contents();
if (!is_array($info))
{
// String was returned because of an error
echo $content.$info;
exit();
}
// Got valid data array, so loop through it to build the table
foreach ($info as $detail)
{
list($field1,$field2,$field3,$field4) = $detail;
$content .= "<tr>
<td>$field1</td>
<td>$field2</td>
<td>$field3</td>
<td>$field4</td>
</tr>";
}
$content .= "</table>";
echo $content;
}
Where it works, the response header indicates the connection as keep-alive; where it fails, the connection is closed. I don't know if that matters.
I've looked all over SO and the net for some clues but "no content" issues invariably point to same-origin policy problems. In my case, all content is on the same server.
I'm at a loss as to what to do/where to look next.
file_get_contents() expects a parameter. It does not know what you want, so it returned false. Also, you used get_file_contents() which is the wrong order.
This turned out to be a PHP version issue. In the load_info function I was using filter_input(INPUT_GET,"value"), but that was not available in PHP 5.1. I pulled that from my initial code post because I didn't think it was part of the problem. Lesson learned.

iSDK - Can't call function sendEmail (undefined function)

I am using this API "https://github.com/infusionsoft/PHP-iSDK".
I am calling it in a simple php file but I am having a error, I am new to php any body with some easy solution, here is my code.
<?php
echo "Hello World! <br/>";
include_once('iSDK/src/isdk.php');
$myApp = new iSDK;
if($myApp->cfgCon("connectionName")) {
echo "Connected...";
} else {
echo "Not Connected...";
}
sendEmail('conList','fromAddress','toAddress', 'ccAddresses', 'bccAddresses', 'contentType', 'subject', 'htmlBody', 'txtBody');
?>
This code below give this error :
Call to undefined function sendEmail() in C:\xampp\htdocs\test\email.php on line 16
Is this the only error in this code?
It looks like php can't find the function within iSDK.
The line nclude_once'iSDK/src/isdk.php'; should be include_once('iSDK/src/isdk.php'); and you should check, if the relative path is correct.
The first character in the next line is also missing: myApp = new iSDK; should be $myApp = new iSDK();
Second guess is to write $myApp->sendEmail( instead of sendEmail(

PHP include/require within a function

Is it possible to have return statements inside an included file that is inside a function in PHP?
I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.
As in
function sync() {
include_once file.php;
echo "Test";
}
file.php:
...
return "Something";
At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?
Sorry for the slightly odly worked question, hope I made it make sense.
Thanks,
You can return data from included file into calling file via return statement.
include.php
return array("code" => "007", "name => "James Bond");
file.php
$result = include_once "include.php";
var_dump("result);
But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.
EDIT:
I am looking to do this as I have lots
of functions in separate files and
they all have a large chunk of shared
code at the top.
In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.
return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;
function sync() {
ob_start();
include "file.php";
$output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
return $output;
}
I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.
see also the part in the manual about this:
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it.
The return statement returns the included file, and does not insert a "return" statement.
The manual has an example (example #5) that shows what 'return' does:
Simplified example:
return.php
<?php
$var = 'PHP';
return $var;
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
I think you're expecting return to behave more like an exception than a return statement. Take the following code for example:
return.php:
return true;
?>
exception.php:
<?php
throw new exception();
?>
When you execute the following code:
<?php
function testReturn() {
echo 'Executing testReturn()...';
include_once('return.php');
echo 'testReturn() executed normally.';
}
function testException() {
echo 'Executing testException()...';
include_once('exception.php');
echo 'testException() executed normally.';
}
testReturn();
echo "\n\n";
try {
testException();
}
catch (exception $e) {}
?>
...you get the following output as a result:
Executing testReturn()...testReturn() executed normally.
Executing testException()...
If you do use the exception method, make sure to put your function call in a try...catch block - having exceptions flying all over the place is bad for business.
Rock'n'roll like this :
index.php
function foo() {
return (include 'bar.php');
}
print_r(foo());
bar.php
echo "I will call the police";
return array('WAWAWA', 'BABABA');
output
I will call the police
Array
(
[0] => WAWAWA
[1] => BABABA
)
just show me how
like this :
return (include 'bar.php');
Have a good day !

PHP Always run function

I am trying to get some errors returned in JSON format. So, I made a class level var:
public $errors = Array();
So, lower down in the script, different functions might return an error, and add their error to the $errors array. But, I have to use return; in some places to stop the script after an error occurs.
So, when I do that, how can I still run my last error function that will return all the gathered errors? How can I get around the issue of having to stop the script, but still wanting to return the errors for why I needed to stop the script?!
Really bare bones skeleton:
$errors = array();
function add_error($message, $die = false) {
global $errors;
$errors[] = $message;
if ($die) {
die(implode("\n", $errors));
}
}
If you are using PHP5+ your class can have a destructor method:
public function __destruct() {
die(var_dump($this->errors));
}
You can register a shutdown function.
Add the errors to the current $_SESSION
Add the latest errors to any kind of cache, XML or some storage
If the code 'stops':
// code occurs error
die(print_r($errors));
You can use a trick involving do{}.
do {
if(something) {
// add error
}
if(something_else) {
// add error
break;
}
if(something) {
// add error
}
}while(0);
// check/print errors
Notice break, you can use it to break out of the do scope at any time, after which you have the final error returning logic.
Or you could just what's inside do{} inside a function, and use return instead of break, which would be even better. Or yes, even better, a class with a destructor.

Categories