I'm having trouble describing this issue, which is probably why I can't find the answer on google.. so I figured I would try getting help here. If I'm repeating this question, feel free to direct me to a link to the thread.
So basically the issue I'm having is I am trying to pass a variable to a function that contains some php code to be eval'd.
Here's the simplified version of the code:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo eval($body);
}
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
--
For some reason, the output isn't putting out what I want. I've gotten a few whitespace errors, and a few times I've gotten the code to output the plain text of the variable $body.
Any help is appreciated. Let me know if I need to clarify the issue further.
I would change it to this:
function sendUser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo $body($row);
}
}
And then call it like this (php 5.3+):
$body = function ($row) {
return "Hello ".
htmlspecialchars($row['user_first_name'], ENT_QUOTES, 'UTF-8').
"<br />";
};
sendUser($body);
In php <= 5.2, it's a lot messier:
$body = create_function(
'$row',
'return "Hello ".'.
'htmlspecialchars($row["user_first_name"], ENT_QUOTES, "UTF-8").'.
'"<br />";'
);
sendUser($body);
That isn't now eval works; it returns null unless you explicitly return a value. You're also missing quotes around the string, and a semicolon at the end of the statement.
To get it to echo something, you'd have to pass the echo as part of the code to be evaluated:
$body = 'echo "Hello $row[\'user_first_name\'] <br>";';
or, to get your code working as written, you'd have to return the formatted string:
$body = 'return "Hello $row[\'user_first_name\'] <br>";';
This is a pretty contrived use of eval. You'd be far better off passing in a printf-style format string and using sprintf to substitute values into it, and returning that string for printing. As it stands you seem to be mixing your display logic with your database logic, which is a bad thing.
Your code, as is, will never work. Removing the mysql portion:
<?php
function senduser($body) {
$row['user_first_name'] = 'Fred';
echo eval($body);
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
Gives me:
PHP Parse error: syntax error, unexpected T_VARIABLE in /home/marc/z.php(5) : eval()'d code on line 1
Anything you pass in to eval() must be raw PHP code. It can't be plaintext with embedded <?php ?> PHP blocks - it has to be actual PHP code. When you fix up $body to account for this:
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
Then you get:
Hello Fred <br>
I'm not exactly positive what you're trying to do, but I think your problem is in the definition of $body and your use of eval.
$body = 'Hello $row[\'user_first_name\'] <br>';
is not a valid line of php, and eval won't know what to do with it.
See if this fits what you want:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
eval($body);
}
}
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
sendUser($body);
Related
Im a student studying PHP, Java. but I don't know if eval can access outside variable.
My code :
<?php
$o = "This is just test character";
$code = "echo $o;"
eval($code);
?>
does it active? if not, how can i make it to active? (my purpose is eval() can access outside variable..)
sorry for my bad english and thx for listening.
Apart from the obvious missing ; on line 2
The issue you're having with eval is the string you're passing is not valid PHP.
<?php
$o = "This is just test character";
$code = '<?php echo $o;';
eval('?>'.$code);
https://3v4l.org/CHkR3
And if you're using double quotes it will parse into the string and again create invalid PHP by missing the quotes.
<?php
$o = "This is just test character";
$code = "<?php echo '$o';";
eval('?>'.$code);
https://3v4l.org/CHkR3
Bottom line, if you don't know how eval works then you should definitely not use it.
You need to put the string in the $code variable between aposthropes and then it'll work. Like this:
$o = "'This is just test character'";
$code = "echo $o;";
eval($code);
Could someone point out what I'm mistaking here? :)
<?php
$q = $_GET[q];
$acuman = <<<PARSE
input: (contains: "hello"){
output: "hello";
}
PARSE;
$acuman = str_replace("input: (contains: ", 'if(strpos(', $acuman);
$acuman = str_replace("){", ', $q) !== false) {', $acuman);
$acuman = str_replace("output: ", '$output = ', $acuman);
eval($acuman);
?>
I'm attempting to execute the string $acuman, a heredoc which has been altered by various str_replace functions. However, it is not doing what I intend it to do, and I am confused as of what to do as I've tried many different things.
Since many people seemed confused: My intention is for the code in the string $acuman to be executed as code properly. I just want the eval function to work. I know that eval is evil, please, stop: I'm just asking for help for solving the problem at hand.
Edit: When I echo the string $acuman, this is what I get:
if(strpos("hello", $q) !== false) { $output = "hello"; }
You have the arguments in the wrong order:
if(strpos($q, "hello") !== false) { $output = "hello"; }
strpos() takes the "haystack" (string being searched) as the first argument and the "needle" (string to find as within the "haystack") as the second argument.
Ok, so... $acuman appears to contain the following:
if(strpos("hello", $q) !== false) {
echo "hello";
}
Which indicates that $q needs to contain a portion of "hello" to echo the string "hello".
I don't see any problem here, EXCEPT that $q = $_GET[q]; won't work with any modern version because q is treated like a constant, not a variable nor a string literal array index. See this PHP documentation on the subject.
Upon changing to $q = $_GET['q']; instead (note the quotes), it seems like this code actually works. It will output "hello" whenever passing any portion of "hello" to the URL parameter (which gets passed to the PHP code).
Needless to say: Do not use this code for production. The code as it is is very vulnerable and allows a user to pass raw PHP code through to your script to execute. The function of this code can be completely re-written in a much safer manner, but you have expressed the desire to continue using eval(); so please be careful.
Enjoy.
I have the following code:
$name = "<test>";
$msg = "Hi $name Hope your feeling well today";
print_r ($msg);
The problem is, it will print Hi Hope your feeling well today and skip the $name
When I tried it this way:
$name = "<test>";
$msg = "Hi ".$name." Hope your feeling well today";
print_r ($msg);
it also printed the same.
When I tried it as:
$name = "<test>";
$msg = 'Hi $name Hope your feeling well today';
print_r ($msg);
it printed Hi $name Hope your feeling well today
I need a solution so that the variable $name will be printed as it is if starting with < or any other PHP related code.
View the source of your web page. It is there. You don't see it because it is in brackets which the browser interprets as HTML. Since HTML tags are interpreted and not displayed, you don't see that content.
To display those brackets, you need to convert them into HTML entities. You can use the aptly named htmlentities() function to do that.
$name = "<test>";
$msg = "Hi $name Hope your feeling well today";
echo htmlentities($msg, ENT_NOQUOTES, 'UTF-8');
Write instead of < < and instead of > >
I have a sql query that I store in a variable and I displayed. I get the contents of this with file_get_contents from another file, I would like to recover some of this code (which is html) in order to make link. More precisely retrieve the id.
My api.php
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_GET['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme
FROM organismes
WHERE code_postal LIKE "%'.$_GET['cp'].'%"
ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
}
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
}
I want to get the id="I WANT THIS".
And my index.php (part of my code that retrieves the contents).
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
echo $var;
}
How can I get the id="" in my index.php ?
please look at php get documentation. you need to link to your script with url parameters and access them in your php code.
http://php.net/manual/en/reserved.variables.get.php
echo ''.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</br>';
php
if(isset($_GET['id']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_GET['id'];
$var = file_get_contents($api);
echo $var;
}
if you dont want to use url parameter you can use post values
http://php.net/manual/en/reserved.variables.post.php
I understand what your trying to do, but dont find it logical without knowing the purpose of this tiny code :)
Do you have a link or some sort?
Basicly what i should do is:
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_POST['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme FROM organismes WHERE code_postal LIKE "%'.$_GET['cp'].'%" ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</p></br>';
}
} else {
echo 'show something else';
}
If I get you correctly, you are
Sending a GET request in index.php using file_get_contents() to your website.
The website (api.php) performs an SQL query and prints the result in HTML.
index.php takes this HTML output and stores it in the variable $var.
You want to retrieve all values contained inside the id attribute of the paragraph.
In this case, you probably want to use regular expressions. preg_match_all seems to be appropriate. It should work for you like this:
$out = array();
preg_match_all("/id=\"([^\"]*?)\"/U", $var, $out);
foreach ($out as $value) {
echo 'I found some id ' . htmlspecialchars($out[$value][2]) . '<br />';
}
And additionally:
A decent HTML parser would be much more appropriate in this case (eg. it would not match id="X" in flow text).
Your PHP code is vulnerable to SQL injections.
You should sanitize plain text to HTML appropriately.
First of all, you should try to display your API reply as a JSON-string, this is much more convenient.
If you still want to use your api.php, you first need to close your opening paragraph! You did forget a '>'!
echo '<p id="'.$data['ID_organisme'].'">'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
Then you need to parse your paragraph.
You can do it like that:
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
preg_match("#<p id='(.*)'#", $var, $matches);
id = $matches[1];
echo $id;
}
I have something like this in one field of my table(MySql):
$data = '<td>apple</td>';
echo $data;
I select this field and echo it into the page.I want to replace 'apple' word with a php function that return a word.So I thought
$data = '<td>myphp_function('fruit');</td>';
echo $data;
but what I see in the page is exactly the line above and not my function output.
how can I do it?
I am not sure if i could explain my mean clearly...
Edited.
According to your last edit, what you need is the following:
$data = '<td>' . myphp_function('fruit') . '</td>';
echo $data;
This is assuming your myphp_function() will return some kind of value.
If the function echoes the value, it will not work as expected!
You can only execute PHP when you open PHP tags. Other than that, it's just plain text/html.
<td>myphp_function('fruit');</td>
To execute your function you have to open PHP tags:
<td><?php myphp_function('fruit'); ?></td>
you have to insert some sort of placeholder into your text. Like this
<td>[fruit]</td>
and then do a replace before printing it out:
$fruit = 'apple';
$text = str_replace('[fruit]',$fruit,$text);
Of course, for the real life usage there will be more complex solution.
So, you will do yourself enormous favor, if you post here your real task with real data example, not oversimplified and useless abstract question.