I get this warning in a chunk of instructions PHP 8+ dedicated to the check of the user inside the page:
if ($_POST['go'] ?? null) {
// $_SESSION_VALUES is an array $db, $nick are classes of mine
$_SESSION_VALUES = $nick->get_cookie (COOKIE_NAME); // get the name of the cookie
if ($db->check_user (USERS_TABLE, $_POST['nick'], $db->encode_password($_POST['password']))) {
$_SESSION_VALUES['_USERNAME'] = $db->user_rec['nick']; // get the nickname from the cookie
$_SESSION_VALUES['_PASSWORD'] = $db->user_rec['password']; //get the password
$_SESSION_VALUES['_USER'] = $db->user_type;
if (! $nick->set_cookie (COOKIE_NAME, $_SESSION_VALUES)) die ('Cannot write the cookie'); // record the cookie
header('Location: ./copertina'); }
else $_SESSION_VALUES['_USER'] = -1;
}
The execution of
else $_SESSION_VALUES['_USER'] = -1;
gives "Automatic conversion of false to array is deprecated"
Following a suggestion from stack overflow I tryed this:
$\_SESSION_VALUES = \[\];
if ($\_POST\['go'\] ?? null) {
...
but apparently it doesn't work
any idea?
Thanks
I assume that $nick->get_cookie(COOKIE_NAME); returns false.
Try changing:
else $_SESSION_VALUES['_USER'] = -1;
to:
else $_SESSION_VALUES = ['_USER' => -1];
This will probably get rid of the error message you reported, but I don't know if the rest of your code, which I cannot see, will accept this.
A quick question, I'm venturing into Kafka using php-rdkafka ( https://github.com/arnaud-lb/php-rdkafka ).
I went through the documentation and i can't find the syntax to produce into existing topic unless the syntax newTopic will insert to the existing topic which i doubt. I keep on getting Java error thrown and i'm not good debugging Java error. I'm seeking help from those who has been using the framework , is it a correct syntax? Please advice
<?php
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');
//If you need to produce exactly once and want to keep the original produce order, uncomment the line below
//$conf->set('enable.idempotence', 'true');
$producer = new RdKafka\Producer($conf);
$topic = $producer->newTopic("test"); // Is this a correct syntax to consume existing topic?
for ($i = 0; $i < 10; $i++) {
$topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message $i");
$producer->poll(0);
}
for ($flushRetries = 0; $flushRetries < 10; $flushRetries++) {
$result = $producer->flush(10000);
if (RD_KAFKA_RESP_ERR_NO_ERROR === $result) {
break;
}
}
if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
throw new \RuntimeException('Was unable to flush, messages might be lost!');
}
As per discussion with the developer,
The following syntax can be used to create new topic and add the data to the following/existing topic
$topic = $producer->newTopic("test"); /
I'm using the Class "mysql2json" to make my Json.
<?php
class mysql2json{
static public function getJSON($resultSet,$affectedRecords){
mb_internal_encoding("UTF-8");
$numberRows=0;
$arrfieldName=array();
$i=0;
$json="";
//print("Test");
while ($i < mysql_num_fields($resultSet)) {
$meta = mysql_fetch_field($resultSet, $i);
if (!$meta) {
}else{
$arrfieldName[$i]=$meta->name;
}
$i++;
}
$i=0;
$json="{\n\"data\": [\n";
while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
$i++;
//print("Ind ".$i."-$affectedRecords<br>");
$json.="{\n";
for($r=0;$r < count($arrfieldName);$r++) {
$json.="\"$arrfieldName[$r]\" : \"$row[$r]\"";
if($r < count($arrfieldName)-1){
$json.=",\n";
}else{
$json.="\n";
}
}
if($i!=$affectedRecords){
$json.="\n},\n";
}else{
$json.="\n}\n";
}
}
$json.="]\n};";
return $json;
}
}
?>
The problem is I'm getting a not valid JSON error in Xcode (iPhone App) and the JSON validator is saying there is an error on line 11 of the results even though line 11 is blank.
Validator: http://jsonlint.com/
Here is a sample URL.
http://leafseed.com/webservice.php?upc=1116102338
Xcode Error:
2012-01-11 08:55:46.137 GroceryVine[6476:bf03] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=10 \"Garbage after JSON\" UserInfo=0x9bbabc0 {NSLocalizedDescription=Garbage after JSON}
Validator Error
Parse error on line 11:
...." } ]};
--------------------^
Expecting 'EOF', '}', ',', ']'
Any Ideas?
Best Solution
I wouldn't bother with this class. Just use the native json_encode() DOCs PHP function as it will give you correctly formatted JSON very easily every time.
For example:
$json_arr = array();
while($row = mysql_fetch_array($resultSet, MYSQL_NUM)) {
$json_arr[] = $row;
}
echo json_encode($json_arr);
A list of other PHP JSON implementations can be found on the json.org website (hint: scroll down).
Direct answer
Looking at your updated question with debug output. Looks like there is an errant semi-colon (;) in your output.
Change your last append from
$json.="]\n};";
to
$json.="]\n}";
And I think that will fix your issue.
what about json_encode function and fetch data separately ?
http://php.net/manual/en/function.json-encode.php
The ; after the last curly brace is wrong
Replacing:
}
$json.="]\n};";
return $json;
}
With
}
$json.="]\n}";
return $json;
}
should solve your problem.
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.
morning. I am wanting to take all segments of php code out of a file located on my local server. Problem is i dont seem to be getting anywhere, no php errors just browser errors.
$file_contents = "<xmp>".file_get_contents("../www.cms.actwebdesigns.co.uk2/pageIncludes/instalation/selectMainPages.php")."</xmp>";
if(preg_match_all("#<\?php((?!\?>).)*#is", $file_contents, $matches))
{
foreach($matches[0] as $phpCode)
{
$code = "<xmp>".$phpCode."\n?></xmp>";
}
}
echo "dsds";
?>
could someone please point me in the right direction?
working with this:
$file_contents = token_get_all(file_get_contents("../www.cms.actwebdesigns.co.uk2/logged.php"));
$start=0;
$end=0;
$segmentArray = array();
foreach($file_contents as $key => $token)
{
$tokenName = token_name($key);
if($start==0 && $end==0 && $tokenName=="T_OPEN_TAG")
{
$start=1;
}
if(start==1 && $end==0 && $tokenName!="T_CLOSE_TAG")
{
$entryNo = count($segmentArray);
$segmentArray[$entryNo][] = $token;
}
if($tokenName=="T_CLOSE_TAG")
{
$start=0;
}
}
You might want to tokenize the PHP script using the Tokenizer extension:
http://php.net/manual/en/book.tokenizer.php
The extensions is built into PHP since PHP v4.3.0.
$tokens = token_get_all(file_get_contents($file));
http://www.php.net/manual/en/function.token-get-all.php
Not sure how to use this. Puts all code into an array. For me to use it wouldn't i have to implode it or something then im back to square one?