escaping "<?php" and "?>" when outputing to a file - nowdoc/heredoc - php

What I was trying to do (and could, actually but only on my local testserver) is to output a php-file with php.
The problem seems to be the opening and closing tags of php.
I looked up nowdoc in php.net but could not find a clue to the solution.
If I use it like this:
$fh = fopen($filenameandpath, 'w') or die("can't open file");
$stringData = <<<'WWR'
<?php
echo('test');
?>
WWR;
$suc = fwrite($fh, $stringData);
fclose($fh);
I get a parsing error:
Parse error: syntax error, unexpected T_SL in /home/ua000154/public_html/test.php on line XX
The linenumber of this parsing error is always where the opening php-tag is found. My problem seems to be that I need to escape this tag (I presume I should do the same with the closing tag)
How could I do this? This actually worked on my test server but would not once I uploaded it to the final location on another server.
Any help is apreciated. Thanks you for your time!

If you're intentionally using NOWDOC syntax, make sure your PHP server is running 5.3 or later, since that was when it was introduced. (You can check using phpinfo();). That would explain why it worked on your dev server but not on production.

Ok, so this is an old question that has been answered, however this may be of use for anyone who wants to implement a similar concept to NOWDOC in earlier versions of php. it uses output buffering to capture text verbatim from the source file, without any variable parsing etc. ie not a lot of use if you WANT to insert variables, but you can literally put anything in it, as long as it does not include the characters "?>", which terminates it.
note that it differs from HEREDOC and NOWDOC that used >>>TERMINATOR and >>>'TERMINATOR' in that the variable is defined after the document.
<?PHP
function NOWDOC_() {
ob_start();
}
function _NOWDOC(&$buf=false) {
$buf_ = ob_get_contents();
ob_end_clean();
if ($buf!==false) $buf .= $buf_;
return $buf_;
}
NOWDOC_(); ?>random garbage, not shown, but captured into $myvar
it has all sorts ] [* \%& of characters in it
and completely ignores things like {$this} or $_SERVER['REMOTE_ADDR';
<?PHP _NOWDOC($myvar);
NOWDOC_(); ?><HTML><HEAD></HEAD>
<BODY>Here is some <B>nice</B> HTML & .
<SCRIPT>
alert("javascript!");
</SCRIPT>
this also demonstrates using $var = _NOWDOC() syntax.
</BODY>
</HTML><?PHP $myhtml = _NOWDOC();
echo "the html will be [".$myhtml."]";
?>

Related

Poedit does not parse all strings in PHP files in "path"

Today i runt into this trouble when i tried to scan my plugin for translations and to create the localisation files for it, but i saw that Poedit scanned all files but did not parse all the strings.
For example if i had strings like this
<?php _e('test string')?> it's parsed, but if i had it in context like this
if($a == $b){
_e('Everything is ok');
}else{
_e('Error');
}
poedit did not parse any string.
Then i did a simple test and i put my messages in a line like this
<?php_e('test string'); _e('test string 2');?> and poedit extracted them!
Note:
No error were thrown by poedit. All keywords are there, and searching by (_,__,_e).
I sometimes have that Poedit doesn't seem to recognize strings after a comment somewhere in the file.
Today, it wouldn't see a lot of my strings. So I made a test.
This is a piece of code in the middle of the file:
//
// Check for valid address
//
echo __('Dit is een simpele test');
The string wasn't recognized, nor were any of the strings after that.
Removing the comment and a few other made Poedit see all the strings in the file.
To me, it seems it does it randomly, because a lot of files contain comments and it does recognize those strings. So it seems like a bug.
A colleague of mine noted that it only happens with single-line comments // and # and not using multi-line comments /* */. I tested it and it works, so that seems like a simple fix.
I'm using version 1.5.5 and I've had this problem with older versions.
(why can't I add comments?)
Changing line endings on the file to Unix (from Mac OS 9) caused my missing strings to show up in Poedit.
Removing comments also worked but this is a better solution if it's universal. The comments issue seems to be a bug in Poedit.
I finally managed to fix it by just re-indenting heredoc code.
see, i used a code like this :
$title = _x("Publish Later?","notif-panel","mytd");
echo <<<a
<tr><td ><label class="text-primary" for="notifaddedit-schedule-check">$title</label></td>
<td>$datepicker</td></tr>
a;
then i changed it to:
$title = _x("Publish Later?","notif-panel","mytd");
echo <<<a
<tr><td ><label class="text-primary" for="notifaddedit-schedule-check">$title</label></td>
<td>$datepicker</td></tr>
a;
note the position of final a; that closes the heredoc, it souldn't have any tab or space before itself!

Output PHP delimiter (<?php, ?>) without PHP interpreting the delimiters

I run PHP in JavaScript files, e.g....
var = '<?php /*some code*/ ?>';).
I need to use JavaScript to scan a string for PHP delimiters (the < ? php and ? > that open and close PHP).
I already know the code using JavaScript...
if (b.value.indexOf('<?php')>-1) {alert('PHP delimiter found.');}
What I'm having trouble with is that I need to keep the ability for PHP to be interpretted in JavaScript files (no exceptions). I simply need to output the delimiter strings to the client in JavaScript and not have them interpreted by the server.
So the final output (from the client's view) would be...
if (b.value.indexOf('<?php')>-1) {alert('PHP delimiter found.');}
With the following code...
if (b.value.indexOf('<?php echo '<?php'; ?>')>-1 || b.value.indexOf('<?php echo '?>'; ?>')>-1)
I get the error: "Parse error: syntax error, unexpected T_LOGICAL_AND"
Javascript will never find the <?php in your strings because simply, they have already been parsed by your PHP Server. Javascript is a client-side script and is executed after your server-side scripts.
You could take advantage of Javascript's ability to parse hex as a character:
if (b.value.indexOf('<\x3fphp')>-1) {alert('PHP delimiter found.');}
In Javascript '<\x3fphp' is exactly the same thing as '<?php', but it has no meaning in PHP.
Use output buffering on the PHP, then htmlspecialchars() on the buffered output. You then search for the HTML entities with the JavaScript.
the first thing that came into my mind and should work is this simple, little "cheat":
<?php echo '<'.'?php'; ?>
the php interpreter doesn't see a <?php, but the output is as desired.
<?php echo '<?php'; ?> ... <?php echo '?>'; ?>

PHP assign variable definition from a string

Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.
eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!
First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.

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

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.

PHP text output in clauses

I am working on a PHP project. There, I often use following syntax to output text in a cluase:
if($boolean){
?>
output text
<?
}else{
?>
alternative
<?
}
On my computer, this works perfectly well. I use XAMPP foer Mac OS X. But when I send the files to my coworker, these outputs often do not work and the compiler complains about having reached an unexpected $end of file. This occurs especially often when there is a tag in the output. We have to replace the means of output with echo.
What's the reason for this strange behavior of the compiler? Is the above-mention syntax of outputting text wrong?
Use <?php instead of <? he might not have short tags enabled.
I think you'll find this topic useful;
Are PHP short tags acceptable to use?

Categories