PHP - Error parsing a string with code - php

I'm having a problem with some code that used to work in PHP 4.X and is not working in PHP 5.2.4
First of all, there is a small example of a code similar to the one is causing the problem. Unfortunately, I haven't been able to reproduce the problem with a small example.
<?php
class Example{
public function showExample()
{
$ind = 1;
$m = "method";
$str2 = "{call method}";
$str2 = str_replace("{call $m}" , "<?php print( \$pre$ind ); ?>", $str2);
echo $str2 . "\n";
}
}
$e = new Example();
$e -> showExample();
?>
What this code is doing is building a string with some php code to execute later on. In particular, the code generated will print the value of a variable named "$pre" + a variable number. In this case, the output is the following:
<?php print( $pre1 ); ?>
Everything runs fine with this code. The problem is when I use it in the context of a much bigger class, that is part of a framework I've been using for a long time. I cannot paste here the whole source of the class, but the problematic lines are the following (I simplified them a little bit to remove the str_replace, but the error still appears):
$myVar = "value";
$myVar2 = 2;
$str2 = "<?php print( \$myVar$myVar2 ); ?>";
When I load the file, I get the following two messages:
PHP Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /Users/giove/Sites/mundial/htmltemplate.php on line 252
PHP Parse error: syntax error, unexpected T_VARIABLE in /Users/giove/Sites/mundial/htmltemplate.php on line 252
I can fix the warning by removing the '\', but that changes the semantics of the code, so it's not a real possibility.
Now, the weirdest part is I can remove both errors by breaking or removing the sequence "
This seems to be a difference in versions, but I haven't been able to find any mention to it on the change logs.
Now I've got a working solution from Cryo: split the string
"<?php"
to prevent its 'evalution' (I'm not sure if that's really an evaluation).
Nevertheless, I still would like to know the reason for this weird behavior.
Cryo: thanks for your help, I'll mark the question as answered in a couple of days.

My guess is that PHP is catching on the re-opening of the php tag <?php, try splitting just that:
$str2 = "<?" . "php print( \$myVar$myVar2 ); ?>";
Or use single quotes and concatenation:
$str2 = '<?php print( $myVar' . $myVar2 . ' ); ?>';

Cryo is on the right track, though I think the actual issue is that PHP evaluates variables within double-quoted strings. However, the slash should prevent the variable from being evaluated. So:
$a = "somestring"
$b = "\$a" // -> \$a
$c = '\$a' // -> \$a
I think your string is getting evaluated in an odd way such that the \ + $myVar is evaluated in a strange way.

Related

Eval on a certain array part

Ok I been looking online for a few hours and i'm confused how eval() can be used in my situation so I know eval is evil but I need
and I want to use eval still for personal reasons so how can I get the variable $part to work properly like this.
$numbers= array($part);
Which means this
$numbers= array(4,6,2,22,11);
but it is not working so how can I do this with eval? and this is my failed code.
<?php
$part= eval(4,6,2,22,11);
$numbers= array($part);
sort($numbers);
$arrlength=count($numbers);
$output='';
for($x=0;$x<$arrlength;$x++) {
$output .= $numbers[$x].'<br>';
}
echo $output;
?>
and this is the error I am getting
Parse error: syntax error, unexpected ',' in C:\path\example.php on line 3
Eval only run string as php code and your use is wrong because 2,4,6 is not code in php language. How documentation says
eval - Evaluate a string as PHP code
This will work.
$stringNumbers = "4,6,2,22,11";
$part= eval("return array(\".$stringNumbers.\");");
$numbers= $part;

PHP Unicode codepoint to character

I would like to convert Unicode codepoint to character. Here is what I have tried:
$point = dechex(127468); // 1f1ec
echo "\u{1f1ec}"; // this works
echo "\u{$point}"; // this outputs '\u1f1ec'
echo "\u{{$point}}"; // Parse error: Invalid UTF-8 codepoint escape sequence
echo "\u\{{$point}\}"; // outputs \u\{1f1ec\}
echo "\u{". $point ."}"; // Parse error; same as above
You don't need to convert integer to hexadecimal string, instead use IntlChar::chr:
echo IntlChar::chr(127468);
Directly from docs of IntlChar::chr:
Return Unicode character by code point value
A similar problem occurs when you want to get a floating point number, say, 12e-4, concatenating pieces. The parsing is done too early in the compiler to allow it. You probably can, however, use eval() to do so. Yuck.
Actually find the solution after several hours:
$unicode = '1F605'; //😅
$uni = '{' . $unicode; // First bracket needs to be separated, otherwise you get '\u1F605'
$str = "\u$uni}";
eval("\$str = \"$str\";"); // Turns unicode into RegEx and store it as $str
echo $str;
Thanks #Rick James for the idea with the eval() function
PHP 7+ solution snippet:
function charFromCodePoint($codepoint) {
eval('$ch = "\u{'.dechex($codepoint).'}";');
return $ch;
}
Notice, that PHP5 doesn't support the "\u{}" syntax.

I got trouble with eval() function in php?

i have searched this function on google a lot. However, i can't understand this function clearly.
i have a example:
<?php
//eval dangerous to use
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1><?php echo $motto;?><br/>";
echo $str.'<br />'; //result: welcome
eval("?>"." $str"."<?php echo $motto;"); //error
echo $str;
?>
eval() takes a string and evaluates it as PHP code. Here are some important points to note:
eval() takes PHP Code as it's argument -- not mixed HTML markup. Currently, you're passing a string containing HTML markup.
You don't need to add <?php ... ?> tags in the string. eval() already knows the argument is going to be PHP code (it's supposed to be), so you don't need to tell it
Here's a very short example:
$motto = "lksdfasdkf";
$str = 'echo $motto;';
eval($str); // => lksdfasdkf
Here, the string $str contains the literal string echo $motto;, which is a valid statement in PHP. When you call eval($str); the string gets evaluated as PHP code. In this case, it will echo the contents of the variable.
Note that this wouldn't work if you use double-quotes instead:
$motto = "lksdfasdkf";
$str = "echo $motto;";
eval($str);
If you have error reporting enabled, then you'll get the following error:
Notice: Use of undefined constant lksdfasdkf - assumed 'lksdfasdkf' in
The reason is that variables are not parsed when they're wrapped in single-quotes. When you use double-quotes to define your variable, the variable value gets interpolated into the resulting string, meaning $str will contain the literal string echo lksdfasdkf; -- which is not valid PHP code. The solution is to escape the dollar character to avoid it being interpreted as a variable:
$motto = "lksdfasdkf";
$str = "echo \$motto;";
eval($str); // => lksdfasdkf
eval — Evaluate a string as PHP code - your code also working fine
try
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1>$motto<br/>";
echo $str.'<br />'; //result: welcome
eval("\$str = \"$motto\";");
echo $str;

parsing inline variables from string from file in php

I'm localizing a website that I've built. I'm doing this by having a .lang file read and each line (syntax: key=string) is placed in a variable depending on the chosen language.
This array is then used to place the strings in the correct places.
The problem I'm having is that certain strings need to have hyperlinks in the middle of them for example someplace I've put my name that links to my contact page. Or a lot of the readouts of the website need to be in the strings.
To solve this I've defined a variable that holds the html + Forecaster + html,
and the localization file contains the $Forecaster variable in the string.
The problem with this as I promptly discovered is that it stubbornly refuses to parse the inline variables in the strings from the file.
Instead it prints the string and variable name as it looks in the file.
And I have yet to find a way to make it parse the variables.
For example "Heating up took $str_time" would be printed on the page exactly like that, instead of inputting the previously defined value of $str_time.
I currently use fopen() and fgets() to open and read the lines. I then explode them to separate the key and the string and then place these into the array.
Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?
The code that gets the line and converts it to the array looks like this:
(It obviously loops through the lines)
#list($key, $string) = explode('=', $line);
$key = strtok($line, '=');
$string = strtok('=');
$local[$key] = $string;
$counter++;
echo $local[$key] . "<br>";
The counter is unused and the echo is for testing.
A line from the .lang file looks like this:
fuel.results.heatup.timeused=Heating up took $str_time
I would call the array where I want the string like this:
$local['fuel.results.heatup.timeused']
As you can see I've tried both explode and strtok but it hasn't made a difference.
Personally I'd write your text file in JSON format to make it easier to pull data out.
Here is a solution directly from the php manual: http://nz2.php.net/manual/en/function.eval.php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
It is worth noting that eval() can be very dangerous used in the wrong way so make sure you're code is very secure E.g. if someone altered your txt file with real PHP code they could execute it directly on the server.
Another approach would require you to know all your variable names and could then do something like:
$str = 'Heating up took $str_time';
echo 'str=' . str_replace('$str_time', $str_time, $str);
Or do this via an array:
$str = 'Heating up took $str_time as well as $other_value';
$vars = Array('str_time', 'other_value');
foreach($vars as $varName) {
$str = str_replace('$' . $varName, $$varName, $str);
}
echo 'str=' . $str;
If you not know all the variable name, you can use this example, without eval(). It is indicatred to avoid eval().
$str = 'fuel.results.heatup.timeused=Heating up took $str_time';
$str_time = 'value';
if(preg_match('/\$([a-z0-9_]+)/i', $str, $v)) {
$vname = $v[1];
$str = str_replace('$'.$vname, $$vname, $str);
}
echo $str; // fuel.results.heatup.timeused=Heating up took value

json_encode() works for one string but not another?

EDIT:
Solved. Somebody commented with an answer, but then deleted it. Embarrassingly, the problem was fixed by adding semi-colons after the two json_encode lines. I still have no idea why string1 worked without a closing semi-colon and string2 did not, but it works, so… success?
/EDIT
Hi… fairly nooby programmer here.
Within PHP, I'm grabbing two arrays from my database. This works fine. I then implode each array into a string. This too works fine.
Later in the same file, in the javascript section of my code (featuring jQuery), I do:
string1 = <?php echo json_encode($string_1);?>
string2 = <?php echo json_encode($string_2);?>
Encoding string1 works perfectly… so long as I comment out the string2 line entirely. It kills my page.
I've tried ensuring that my string is utf8-encoded. I've tried ensuring that there are no backslashes or other problematic characters. Currently, I've got some dummy code that's designed to be as unproblematic as possible… still doesn't work.
Here's the skeleton version of it.
PHP:
$array1 = array();
$array2 = array();
$i = 1;
while($row = mysqli_fetch_assoc($query_result)) {
$array1[$i] = $row['column1'];
$array2[$i] = $row['column2'];
$i++;
}
$string1 = implode(",", $array1);
$string2 = "oh_come_on_why_doesnt_this_work"; // implode(",", $array2);
And JS/HTML/JQuery:
var string1;
var string2;
$.getScript("js/set_functions.js", function(){ loadedScript() });
function loadedScript() {
string1 = <?php echo json_encode($string1);?>
string2 = <?php echo json_encode($string2);?>
// string2 = <?php echo "'" . $string2 . "'";?> doesn't work either
alert(string1); // works if I comment out both string2 = … lines
alert(string2); // displays "undefined" if the first string2 = … line is commented…
// …out, doesn't display at all if it isn't
}
STUCK PLEASE HELP.
Let me know if you need to see more of my code, or if there's anything else I could do to help make this question better. Thanks.
PS: I'm not a good programmer, I know. Please don't correct my other bad coding habits IN LIEU OF helping solve this problem. Thanks!
EDIT: Sorry, in response to Joe Fraumbach, that was an error in my copy-pasting. I had actually declared $array2 = array();
EDIT: You are missing semicolons at the end of the JS assignment expressions, which in some cases will cause parsing problems: both lines may become part of a single, multiassignment expression. Try adding them and see if that fixes your problem.
string1 = <?php echo json_encode($string1); ?>;
string2 = <?php echo json_encode($string2); ?>;
Note that json_encode only works with UTF-8. So if you're not sure that its input is UTF-8, utf8_encode() the strings you feed it, otherwise the whole string is rendered as null in PHP (and translated into an empty string upon concatenation).
$array2 is never defined. You defined $array1 = array();. Do the same for $array2.

Categories