What is wrong with this "for dummies" PHP code? - php

I am running PHP5 on a free web server and I am trying to learn PHP reading a "for dummies" book...It gives me some code to run and for some infuriating reason I get errors on every line that echos HTML.
here is the code. specifics have been Xed out but they are accurate:
<?php
/* Program: mysql_up.php
* Desc: Connects to MySQL Server and
* outputs settings.
*/
echo “<html>
<head><title>Test MySQL</title></head>
<body>”;
$host=”XXXX”;
$user=”XXXX”;
$password=”XXXX”;
$cxn = mysqli_connect($host,$user,$password);
$sql=”SHOW STATUS”;
$result = mysqli_query($cxn,$sql);
if($result == false)
{
echo “<h4>Error: “.mysqli_error($cxn).”</h4>”;
}
else
{
/* Table that displays the results */
echo “<table border=’1’>
<tr><th>Variable_name</th>
<th>Value</th></tr>”;
for($i = 0; $i < mysqli_num_rows($result); $i++)
{
echo “<tr>”;
$row_array = mysqli_fetch_row($result);
for($j = 0;$j < mysqli_num_fields($result);$j++)
{
echo “<td>”.$row_array[$j].”</td>\n”;
}
}
echo “</table>”;
}
?>
</body></html>
Whenever it gets to a line that echos HTML I get this error or similar:
Parse error: syntax error, unexpected '>' in /home/a7613610/public_html/mysql_up.php on line 6
I want to learn PHP but when it reports errors in supposedly good code it makes me not want to.

The code is riddled with fancy quotes (“ and ”) which PHP cannot cope with. You could use your text editor to do a find and replace for both characters with the generic double quote character ". Although it definitely looks like you're not using a plain text editor (see Mike Caron's answer), I hope you're using one. Word-processing and rich text editing software is not designed for writing programs and scripts.
OK, so you're using Notepad to write your PHP code. That's great, but be aware that some eBook readers and even some books themselves mess with quote characters in code blocks and turn them fancy. This is one reason why copying and pasting code is frowned on ;)
Also, if you want to learn PHP, or any form of programming in general, you should probably not expect books and tutorials to be perfect ;)

NEVER USE MICROSOFT WORD FOR DEVELOPMENT OF ANY KIND!
I apologize for shouting, but this is really important. Use notepad, or use any other text editor. But, never, ever use Word or any word processor for coding!

The quotes are wrong. Use the normal quotes like " and not the ones you copied (“)!

Your question has been answered, but since you're a rookie in PHP (and apparently in programming), I would like to add, regarding Mike Caron's answer, that you should avoid coding in windows notepad.
I once had a MAJOR white-space problem, because I edited a PHP file in windows notepad (It took me about 2 hours to figure it out).
Notepad++, is a must for starters.

In addition to what others have pointed out, these lines
echo “<table border=’1’>
<tr><th>Variable_name</th>
<th>Value</th></tr>”;
Should be just one line
echo "<table border=’1’><tr><th>Variable_name</th><th>Value</th></tr>";
Marcelo.

Related

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

Getting PHP to write clean html

My PHP tends output html in really long, difficult to read html.
If my PHP is written as:
<?php
echo "<li>";
echo "<strong>Hello</strong>";
echo "</li>";
?>
it outputs HTML like this
<li><strong>Hello</strong></li>
which dosnt look that bad, but imagine if thats within a foreach loop which out putted variants of that, all on one line..
Is there a way to get my PHP to output as neatly composed HTML ?
There is: include the whitespace in your output (for example, add \n after each tag).
However, doing that is really an exercise in futility. If you want to view the HTML yourself, get an HTML pretty printer (or use the one included in your browser's developer tools). If it's meant for a browser, the browser doesn't care.
Use a template engine like SMARTY. This will allow you to keep all your html in completely different files than your PHP (it does compile as PHP). This will improve the readability of all of your code. You can then format the html any way you see fit.
You can use the \n to make a line break.
<?php
echo "<li>\n";
echo "<strong>Hello</strong>\n";
echo "</li>\n";
?>
But why use your time on it? Chrome details console will fix it if its because you use the html source as a debug tool.
Whether this is nice or not is subjective, but it works:
<?php
for ($i = 0; $i < 5; $i++)
{
?>
<li><strong>Hello</strong></li>
<?php
}
?>
What I'm trying to get at here is that you can go in and out of PHP mode, so if you have long strands of HTML, you can format them as such, instead of echoing everything.

PHP Regex problem!

I was creating a Syntax Highlighter in PHP but I was failed! You see when I was creating script comments (//) Syntax Highlighting (gray) , I was facing some problems. So I just created a shortened version of my Syntax Highlighting Function to show you all my problem. See whenever a PHP variable ,i.e., $example, is inserted in between the comment it doesn't get grayed as it should be according to my Syntax Highlighter. You see I'm using preg_replace() to achieve this. But the regex of it which I'm using currently doesn't seem to be right. I tried out almost everything that I know about it, but it doesn't work. See the demo code below.
Problem Demo Code
<?php
$str = '
<?php
//This is a php comment $test and resulted bad!
$text_cool++;
?>
';
$result = str_replace(array('<','>','/'),array('[',']','%%'),$str);
$result = preg_replace("/%%%%(.*?)(?=(\n))/","<span style=\"color:gray;\">$0</span>",$result);
$result = preg_replace("/(?<!\"|'|%%%%\w\s\t)[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);
$result = str_replace(array('[',']','%%'),array('<','>','/'),$result);
$resultArray = explode("\n",$result);
foreach ($resultArray as $i) {
echo $i.'</br>';
}
?>
Problem Demo Screen
So you see the result I want is that $test in the comment string of the 'Demo Screen' above should also be colored as gray!(See below.)
Can anyone help me solve this problem?
I'm Aware of highlight_string() function!
THANKS IN ADVANCE!
Reinventing the wheel?
highlight_string()
Also, this is why they have parsers, and regex (despite popular demand) should not be used as a parser.
I agree, that you should use existing, parsers. Every ide has a php parser, and many people have written more of them.
That said, I do think it is worth the mental exercise. So, you can replace:
$result = preg_replace("/(?<!\"|')[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);
with
//regular expression.:
//#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#
//replacement text:
//$1<span style=\"color:green;\">$2</span>
$result = preg_replace("#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#","$1<span style=\"color:green;\">$2</span>",$result);
Personally, I think your best bet is to use CSS selectors. Replace style=\"color:gray;\" with class="comment-text" and style=\"color:green;\" with class="variable-text" and this CSS should work for you:
.variable-text {
color: #00E;
}
.comment-text .comment-text.variable-text {
color: #DDD;
}
Insert don't use regex to parse irregular languages here
anyway, it looks like you've run into a prime example of why regular expressions are not suited for this kind of problem. You'd be better off looking into PHP's highlight_string functionality
Well, you don't seem to care that php already has a function like this.
But because of the structure of php code one cannot simply use a regex for this or walk into mordor (the latter being the easier).
You have to use a parser or you will fly over the cuckoo's nest soon.

PHP eval issue with PHP + HTML code

I've got PHP and HTML code stored in a database table. When I get this data, I need to echo the HTML and process the PHP. I thought I could use eval() for this, which works, if I do this eval("echo 'dlsj'; ?> EVALED "); I get "dlsjEVALED" printed out.
The problem is, I get a fatal error when I run longer scripts. Things like:
Parse error: syntax error, unexpected '<' in /home/content.php(18) : eval()'d code on line 1
Best advice - never store php and html code in your database. And avoid eval() like the plague.
I can't really tell what's wrong with your code, as you haven't provided enough information. But even if I did have some advice, I don't think I could give it in good conscience.
You should redesign your whole application so that it doesn't require storing such things in the database. I can't imagine why it would be necessary.
just right der...........
eval('?>' . $content .'<?php');
You need to re-open php mode after the EVALED. Apparently you have to do this with <? rather than the full <?php.
As a rule eval is to be avoided. But rules are made to be broken. There's a thread at When is eval evil in php? that gives some less dogmatic advice.
Depending on what you want to do, it might be suitable to use a template file that you source, with text that will vary stored in a local variable prior to sourcing the template.
As for storing code to be executed in the DB... this does happen in some frameworks like Drupal to provide convenient extensibility, but then Drupal is pretty thoroughly scoured for security weaknesses.
Also if you're writing self-modifying code then you need to use eval(). Not sure if anyone has done that in php but it would certainly be interesting.
I would guess that you're trying to eval() something that contains an opening <?php tag. And that leads to the error at hand.
$contents = htmlentities($contents);
echo html_entity_decode(eval($contents));

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories