No doubt PHP is a powerful interpreter… It has everything a programmer need to make his program. Today we are going to talk about a little less used but very powerful language construct eval(). Basically it evaluates some string passed through it as PHP code. It may seem easy, but there are a few thing one need to know before using this construct. [Note, this is not a function]. Sometime the usage gets so much confusing which often leads to hours of debugging and loads of frustrations… So in this tutorial I will try my best to show you the actual and proper usage of eval(). So lets start… But before, as usual
#1: The syntax behind the eval();
It is very simple and straight forward… You pass any string argument through the eval construct. The string will be treated as any PHP code. The basic syntax is:
mixed eval( string $code_str )
It has a mixed return value which we would get into a little later. The $code_str is the string which would get evaluated as PHP script. For now have a look at this example: Do note the semicolon inside the eval string.
<?php echo '<p>Hi There</p>'; eval( 'echo "<p>I am supposed to get echoed after evaluation</p>";' ); echo '<p>And I am a normal echo</p>'; ?>
If you run this code it would output something like this:
I am supposed to get echoed after evaluation
And I am a normal echo
Quite simple right? Basically it is same as the code below:
<?php echo '<p>Hi There</p>'; echo "<p>I am supposed to get echoed after evaluation</p>"; echo '<p>And I am a normal echo</p>'; ?>
Now you may wonder, why we need eval ? Well good question… But we will get into that a little later.
#2: Using the proper php tag with eval();
This is the most confusing part. First carefully read the following notes:
- eval don’t like any opening <?php or <? tag at the beginning of the string which it is going to evaluate.
- So, we will make it a practice to not to include any opening <? or <?php to the start of the string passed as evaluation argument.
- Also, at the end of the string eval does not like a full opening tag like <?php . If for some reason we have to append that then we will use a short tag <? …
Now for example, have a look at this code:
<?php echo '<p>Hi There</p>'; eval( '<?php echo "<p>I am supposed to get echoed after evaluation</p>"; ?>' ); echo '<p>And I am a normal echo</p>'; ?>
what we have here is an opening tag <?php at the beginning of our string and a closing ?> tag at the end of it! As obvious, this will throw a Parse Error. Why? Well, the above code, evaluates to something like this:
<?php echo '<p>Hi There</p>'; <?php echo "<p>I am supposed to get echoed after evaluation</p>"; ?> echo '<p>And I am a normal echo</p>'; ?>
Does it make any sense? Obviously no! It will throw a similar parse error on line 3.
#2.1: When to use php tags:
Say we have a code similar to this:
<?php echo "Hi there"; ?> <p>I am a p tag</p> <?php echo "I am echoed by PHP"; ?> <?php echo "<br/>I am also echoed by php"; ?>
Often we mix up HTML and php codes like the code above and it really saves our time… We could have echoed the p tag, but it is not a good practice to do! So now, what we will do, if we are to wrap line 4 and 5 inside a eval tag? If we do something like:
<?php echo "Hi there"; ?> <?php eval( '<p>I am a p tag</p> <?php echo "I am echoed by PHP"; ?>' ); ?> <?php echo "<br/>I am also echoed by php"; ?>
It will again throw a parse error! It is because of the same reason stated above… Now lets have a look at this:
<?php echo "Hi there"; ?> <?php eval( '?><p>I am a p tag</p> <?php echo "I am echoed by PHP"; ?><?' ); ?> <?php echo "<br/>I am also echoed by php"; ?>
As obviously this would run perfect. If we break the eval, then we can see that the code is actually something like this:
<?php echo "Hi there"; ?> <?php ?> <p>I am a p tag</p> <?php echo "I am echoed by PHP"; ?> <? ?> <?php echo "<br/>I am also echoed by php"; ?>
Which is logically just the same we wanted to wrap inside eval. So, that’s how we work with php tags within eval…
#3: Understanding the return of eval:
This is the most interesting part. As of now, you should have thought, that eval just does the manipulation of string as PHP code. Well almost right, except of its return values. What happens if you put a code like this:
<?php $my_eval = eval( '$name = "Swashata";' ); var_dump( $my_eval ); ?>
The output will be a simple NULL. Why? because by default eval does not return any value. So why to discuss about it? You bet 😉 eval has a more to do with return 😉 …
As said in the php documentation:
- Eval Return NULL unless return is called in the evaluation code.
- In case of any parse error, eval return FALSE and the evaluation continues for the following codes.
So, you can see, there is some thing unless return is called in the evaluation code . Obviously this is what we are going to discuss. For a startup lets see the following example:
<?php $my_name = eval( 'return $name="Swashata";' ); echo $my_name; ?>
The output will be:
Quite simple! So basically what it does, when it founds a return statement, it returns the whatever value assigned. And if we try to store it in a variable, then it just stores it! Now, lets look into another complicated example…
<?php $eval_code = '$my_site = ( ( $_SERVER["HTTPS"] == "on" )? "https://" : "http://" ) . $_SERVER["SERVER_NAME"];' . '$my_site .= $_SERVER["REQUEST_URI"];' . 'return $my_site;'; $the_site = eval( $eval_code ); echo '<p>This site URL is: ' . $the_site . '</p>'; ?>
It not only returns, but actually does something before returning! Quite effective? right…
Another important thing about the return is, it stops evaluating any further code, when it founds the first return statement. Wondering how? Have a look at this…
<?php $eval_code = '$my_name = "Swashata";' . '$your_name = "John";' . 'return $your_name;' . 'echo $my_name;'; $the_name = eval( $eval_code ); echo '<p>$the_name has got a value ' . $the_name . '</p>'; ?>
It does not echo $my_name as return was found before it. So only $your_name stores inside the variable…
For a better understanding do check our online demo. Also dont forget to download the source codes!
#4: Usage of eval():
Depending on your program, it can have several usage… Here are a few:
- We can load remote PHP files when http wrapper is disabled for include.
- We can encode our PHP source code and then decode and use eval to run the code. Especially useful for base64 decode.
Possibilities are countless. We would cover the topics mentioned one by one! You can also check the official documentation and the comments there to understand the usage… It is indeed a good piece of code.
I hope, it was useful for you. Any doubt, feel free to ask. I will try my best to solve your problem… Also don’t forget to give your feedback.
Nice article! useful
Hi Swashata, I liked your articles n I am regular visitor. This week I am facing problem with my my blogs indexing. Actually only home page is getting indexed instead of title page. Why it is happening Plz help me if u=you can I am waitng for your reply
Thats strange! I saw your sitemap and everything seems to be fine there! What does your webmaster tool say about indexing and sitemap?
Thanks for your reply. Actually in webmaster tools all things are “OK” no error assuch, crawling,downloading all ok. But site url submitted increasing and not the site indexed……….I am getting tensed and dont know what to do?
Hey there! I think you should wait a bit… It happened with me also! That time I was at blogger! It got fixed automatically! There is practically nothing I can do with Google! btw, why did u removed the stylesheet from ur sitemap?
(Thanks from being so friendly with this blogger friend)
I didnt remove stylesheet……Its same as from the beginning. Even I didnt change my theme and anyother else from the start…..
Check your mail nitin
This function returns the rest of the string from the matching point if matching occurs. Otherwise( i-e if the string to search for is not found)it will return FALSE.
When using eval I think it is crucial to whitelist input or something otherwise this can be a real dangerous technique.
Yeah thats true! This is exactly the reason why I decided not to give something really LIVE on the online demo 😉
O/p Will be :
This is a $string with my $name in it.
This is a cup with my coffee in it.
I went through many documents but still i am not able to understand the line
eval(“\$str = \”$str\”;”);
Can you please help me !
hi….friends i am new to this web site i do want to learn php . so please help me friends . how could i get the material and all.
Pingback: Understanding PHP eval function and usage Do more than just evaluating
Very useful artical, thanks!
This topic really helped me so much..Even I was unable to understand the eval() function from either php.net or w3schools.com:)
awesome article (:
eval() is evil.
If you think you need to use eval(), review your design because it is *wrong*.
Amateurs. Amateurs everywhere… (T_T)
There are some services which provide us nothing but raw PHP codes to evaluate. This post was intended for the safe usage of eval(how not to use it like amateurs) 😛
Very useful explanation! Thanks!
Comments are closed.