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 '?>'; ?>
Related
Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
I have a following question. I have put a long text (variable type LONGTEXT) into MYSQL database - through command line. Somewhere in this text there's a <br> tag, and near the end of text there's <?php phpinfo(); ?>. If i type SELECT * FROM mytable WHERE id=1, this whole text shows as it is, so it is unaltered (read: both <br> AND <?php phpinfo(); ?> are there. But when I submit query via php like this:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
Then the text is displayed exactly as I want it on my webpage, that means that <br> tag is processed by the browser as newline, AND <?php phpinfo(); ?> part is IGNORED. That is actually exactly what I want. But my question IS: WHY doesn't <?php phpinfo(); ?> part get processed via browser?? Does the PHP's echo function ignore the <?php tag??
Thanks in advance for explanations.
Because echoing a string is not the same as evaluating it.
PHP generates HTML, which is then processed by the browser. However a string containing PHP code won't be evaluated unless you specifically put it through eval() (hint: DON'T!)
Browsers don't process PHP. It is a server side technology.
Your PHP is reading some text from the database and outputting it to the browser. That the text includes the string <?php is immaterial, it is output from the PHP programme, not part of the script.
When the browser parses it, it just looks like invalid HTML and it tries to perform error recovery (more or less ignoring it as an unrecognised tag).
try this in a new empty browser window:
javascript:document.write('<b>hello <?php ?> is here!</b>');
Then open up firebug/inspector.
In safari, the <?php ?> thing seems to be interpreted as/converted to a comment.
PHP echoes anything you throw to it. If you want to execute the longtext, use eval, if you want to properly display it, you could use the http://php.net/manual/en/function.htmlentities.php function for example.
I'm attempting to file_get_contents and output php code as a string without being rendered. The idea is to grab the raw un-rendered file contents so they can be edited in a textarea...
// file "foo.php" I'm needing the contents of
<h1>foo</h1>
<? include 'path/to/another/file' ?>
// php file that's calling the file_get_contents
<?php
echo file_get_contents('foo.php');
?>
The above code is stripping out the php include in foo.php which outputs:
<h1>foo</h1>
Does anyone know how I can get foo.php contents as a raw un-rendered string where output will be?:
<h1>foo</h1>
<? include 'path/to/another/file' ?>
Any help is greatly appreciated!
As far as I know you can't get php content unless it's on the same server.
Make sure you're trying to access a locally hosted file and not something remote and it should work.
Also if you try to echo code it will try to parse it, so pass it through htmlspecialchars($source) and it should work.
Something like this:
<?php
echo "<pre>";
echo htmlspecialchars(file_get_contents('file.php'));
echo "</pre>";
?>
Would echo formatted source code of the php file, including comments and any other text in it without being parsed. And since it looks like it's important to you, I'd also say that it shows in the DOM of course since it's no longer code, now it's text. You can place it inside a container, style it and do whatever you want with it.
You can also do :
<?php
highlight_file('file.php');
// or alternatively
echo highlight_file('file.php',true);
And that will output the file like with htmlspecialchars and file_get_content but within <code> tags and with some syntax highlighting.
highlight_string :
(PHP 4, PHP 5, PHP 7)
highlight_string — Syntax highlighting of a string
highlight_file :
(PHP 4, PHP 5, PHP 7)
highlight_file — Syntax highlighting of a file
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?
This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";