I don't know how to make this.
There is an XML Api server and I'm getting contents with cURL; it works fine. Now I have to call the creditCardPreprocessors state. It has 'in progress state' too and PHP should wait until the progess is finished. I tried already with sleep and other ways, but I can't make it. This is a simplified example variation of what I tried:
function process_state($xml){
if($result = request($xml)){
// It'll return NULL on bad state for example
return $result;
}
sleep(3);
process_state($xml);
}
I know, this can be an infite loop but I've tried to add counting to exit if it reaches five; it won't exit, the server will hang up and I'll have 500 errors for minutes and Apache goes unreachable for that vhost.
EDIT:
Another example
$i = 0;
$card_state = false;
// We're gona assume now the request() turns back NULL if card state is processing TRUE if it's done
while(!$card_state && $i < 10){
$i++;
if($result = request('XML STUFF')){
$card_state = $result;
break;
}
sleep(2);
}
The recursive method you've defined could cause problems depending on the response timing you get back from the server. I think you'd want to use a while loop here. It keeps the requests serialized.
$returnable_responses = array('code1','code2','code3'); // the array of responses that you want the function to stop after receiving
$max_number_of_calls = 5; // or some number
$iterator = 0;
$result = NULL;
while(!in_array($result,$returnable_responses) && ($iterator < $max_number_of_calls)) {
$result = request($xml);
$iterator++;
}
I have a PHP loop below which works fine however sometimes there will be a error page returned by the CURL request, how can I restart the operation for that current page only without restarting the whole loop?
while ($daytofetch <= $lastdaytofetch) {
//Do all my stuff and run curl request here
$daytofetch++
}
while ($daytofetch <= $lastdaytofetch) {
// Do all my stuff and run curl request here
if ($error_detected) {
// This will resume the loop without incrementing
// $daystofetch
continue;
}
$daytofetch++
}
I would probably do something like this:
while ($daytofetch <= $lastdaytofetch) {
$error = false;
//Do all my stuff and run curl request here
//if there is an error, then set $error = true;
if (!$error)
$daytofetch++
}
if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc() && $getstatusarr["Type"] != $data["type"])
echo "error"
else
...
first code will not work, to make works this way, see Nin's post
Is it possible to make the code easily?
Also I can do it like this:
if($getstatus->num_rows != 0)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}
by ellipsis I have too many lines of code :)
added:
also I can do in this way:
if($getstatus->num_rows != 0) {
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error";
goto skip;
}
}
... // some code which I need not to execute if $getstatusarr["Type"] != $data["type"] are true
skip:
// another code which will execute in all cases
Well, don't use goto: :)
Whether you put all the if's on one line or on several lines is mostly a personal preference.
Too many lines with if will make the code harder to read but putting it all on one line also makes it difficult to read and difficult to debug (error on line 12 can mean many things then). If you're using a debugger like xdebug or Zend debug then having multiple lines to step over is also easier.
So find a way in between this.
I would do it like this, since then you also check if fetch_assoc() returned a result:
if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc())
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}
From my point of view is always best to unwrap statements and clean the code as much as you can, maybe someone later on will have to read what you did and he will have a hard time doing that.
Also you cannot assign new variables in a if statement like that:
$error = false;
if($getstatus->num_rows)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
$error = array('type' => 'invalid type');
}
}
if($error) {
// do something with $error array
}
The script runs on php 4 with nusoap library
require_once('nusoap/lib/nusoap.php');
ini_set("soap.wsdl_cache_enabled", "0");
$client = new soapclient("some-url",true);
$err = $client->getError();
if ($err)
{
header("Location: error-page");
exit();
}
My question is this: in case an error is detected, is it possible to wait for 1-2 secs ( something like sleep(2); ) and then try to re-enable the soap connection? And for future reference... how can i get all possible errors and build cases for them? For example for some errors wait to re-initialize the connection, for some other errors, log to db the reason, and for the rest just redirect to a general error page.
You do know how to program, right? Just drop the code into a loop:
$retries = 3; // how many times to retry the connection
$sleep = 2; // number of seconds to sleep in-between retries
$i = 1;
while (TRUE) {
$client = new soapclient("some-url",true);
if ( ! $client->getError()) {
break; // break out of the loop on success
} elseif ($i === $retries) {
header("Location: error-page");
exit();
}
sleep($sleep);
++$i;
}
Disclaimer; I'm fully aware of the pitfalls and "evils" of eval, including but not limited to: performance issues, security, portability etc.
The problem
Reading the PHP manual on eval...
eval() returns NULL unless return is
called in the evaluated code, in which
case the value passed to return is
returned. If there is a parse error in
the evaluated code, eval() returns
FALSE and execution of the following
code continues normally. It is not
possible to catch a parse error in
eval() using set_error_handler().
In short, no error capture except returning false which is very helpful, but I'm sur eI could do way better!
The reason
A part of the site's functionality I'm working on relies on executing expressions. I'd like not to pass through the path of sandbox or execution modules, so I've ended using eval. Before you shout "what if the client turned bad?!" know that the client is pretty much trusted; he wouldn't want to break his own site, and anyone getting access to this functionality pretty much owns the server, regardless of eval.
The client knows about expressions like in Excel, and it isn't a problem explaining the little differences, however, having some form of warning is pretty much standard functionality.
This is what I have so far:
define('CR',chr(13));
define('LF',chr(10));
function test($cond=''){
$cond=trim($cond);
if($cond=='')return 'Success (condition was empty).'; $result=false;
$cond='$result = '.str_replace(array(CR,LF),' ',$cond).';';
try {
$success=eval($cond);
if($success===false)return 'Error: could not run expression.';
return 'Success (condition return '.($result?'true':'false').').';
}catch(Exception $e){
return 'Error: exception '.get_class($e).', '.$e->getMessage().'.';
}
}
Notes
The function returns a message string in any event
The code expression should be a single-line piece of PHP, without PHP tags and without an ending semicolon
New lines are converted to spaces
A variable is added to contain the result (expression should return either true or false, and in order not to conflict with eval's return, a temp variable is used.)
So, what would you add to further aide the user? Is there any further parsing functions which might better pinpoint possible errors/issues?
Chris.
Since PHP 7 eval() will generate a ParseError exception for syntax errors:
try {
$result = eval($code);
} catch (ParseError $e) {
// Report error somehow
}
In PHP 5 eval() will generate a parse error, which is special-cased to not abort execution (as parse errors would usually do). However, it also cannot be caught through an error handler. A possibility is to catch the printed error message, assuming that display_errors=1:
ob_start();
$result = eval($code);
if ('' !== $error = ob_get_clean()) {
// Report error somehow
}
I've found a good alternative/answer to my question.
First of, let me start by saying that nikic's suggestion works when I set error_reporting(E_ALL); notices are shown in PHP output, and thanks to OB, they can be captured.
Next, I've found this very useful code:
/**
* Check the syntax of some PHP code.
* #param string $code PHP code to check.
* #return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned.
*/
function php_syntax_error($code){
if(!defined("CR"))
define("CR","\r");
if(!defined("LF"))
define("LF","\n") ;
if(!defined("CRLF"))
define("CRLF","\r\n") ;
$braces=0;
$inString=0;
foreach (token_get_all('<?php ' . $code) as $token) {
if (is_array($token)) {
switch ($token[0]) {
case T_CURLY_OPEN:
case T_DOLLAR_OPEN_CURLY_BRACES:
case T_START_HEREDOC: ++$inString; break;
case T_END_HEREDOC: --$inString; break;
}
} else if ($inString & 1) {
switch ($token) {
case '`': case '\'':
case '"': --$inString; break;
}
} else {
switch ($token) {
case '`': case '\'':
case '"': ++$inString; break;
case '{': ++$braces; break;
case '}':
if ($inString) {
--$inString;
} else {
--$braces;
if ($braces < 0) break 2;
}
break;
}
}
}
$inString = #ini_set('log_errors', false);
$token = #ini_set('display_errors', true);
ob_start();
$code = substr($code, strlen('<?php '));
$braces || $code = "if(0){{$code}\n}";
if (eval($code) === false) {
if ($braces) {
$braces = PHP_INT_MAX;
} else {
false !== strpos($code,CR) && $code = strtr(str_replace(CRLF,LF,$code),CR,LF);
$braces = substr_count($code,LF);
}
$code = ob_get_clean();
$code = strip_tags($code);
if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
$code[2] = (int) $code[2];
$code = $code[2] <= $braces
? array($code[1], $code[2])
: array('unexpected $end' . substr($code[1], 14), $braces);
} else $code = array('syntax error', 0);
} else {
ob_end_clean();
$code = false;
}
#ini_set('display_errors', $token);
#ini_set('log_errors', $inString);
return $code;
}
Seems it easily does exactly what I need (yay)!
How to test for parse errors inside eval():
$result = #eval($evalcode . "; return true;");
If $result == false, $evalcode has a parse error and does not execute the 'return true' part. Obviously $evalcode must not return itself something, but with this trick you can test for parse errors in expressions effectively...
Good news: As of PHP 7, eval() now* throws a ParseError exception if the evaluated code is invalid:
try
{
eval("Oops :-o");
}
catch (ParseError $err)
{
echo "YAY! ERROR CAPTURED: $err";
}
* Well, for quite a while then... ;)
I think that best solution is
try {
eval(/* ... */);
} catch (Throwable $t) {
//...
}
It catches every error and exception, including Call to undefined function etc
You can also try something like this:
$filePath = '/tmp/tmp_eval'.mt_rand();
file_put_contents($filePath, $evalCode);
register_shutdown_function('unlink', $filePath);
require($filePath);
So any errors in $evalCode will be handled by errors handler.