What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.
Related
Is it possible? If so, how?
If its not, do I have to abandon pug if I need to write PHP in my documents?
After searching around I didnt find anyone that has adressed this.
You can embed PHP in Pug templates the same way you would any literal plain text that you want passed through relatively unmolested[*]. There are a number of options covered in the docs, but I think these are most likely the best options for embedding PHP:
After an element, it will just work. For example, p Good morning, <?php echo $user->name ?>.
On a single line by itself. Since any line beginning with "<" is passed as plain text, any one line PHP statement (e.g., <?php echo $foo; ?>) will just work.
Multi-line PHP is the one case where it gets a bit complicated. If you're ok with wrapping it in an HTML element, you can use Pug's block text syntax: Put a dot after the element, then include your plain text indented underneath.
p.
<?php
if ($multiline) {
echo 'Foo!';
}
?>
If you need it outside an element, the other option is to prefix every line with a pipe:
|<?php
|if ($multiline) {
| echo 'Foo!';
|}
|?>
(Technically, the first line doesn't need to be prefixed due to point 2 above, but if using this method I would prefix it anyway just for consistency.)
To use PHP in attributes, you just need to prevent escaping by prefixing the equals sign with a bang: p(class!="<?php echo $foo ?>"). (Interestingly, support for unescaped attribute values was added specifically for this use case.)
Of course by default .pug files are compiled to .html files, so if you're using them to generate PHP, you'll want to change the extension. One easy way to do this is to process them using gulp with the gulp-pug and gulp-rename plugins, which would look something like this:
var gulp = require('gulp'),
pug = require('gulp-pug'),
rename = require('gulp-rename');
gulp.task('default', function () {
return gulp.src('./*.pug')
.pipe(pug())
.pipe(rename({
extname: '.php'
}))
.pipe(gulp.dest('.'));
});
I haven't worked extensively with Pug, so I don't know if there are any potential gotchas that would come up in real world use cases, but the simple examples above all work as expected.
[*] Pug still performs variable interpolation on plain text, but it uses the #{variable} format, which should not conflict with anything in PHP's standard syntax.
Since PHP doesn't care whether the "outside" code is HTML or really anything specific, you could simply use PHP as you normally would and have it output Pug-formatted code instead of HTML. For instance:
myPugTemplate.pug.php
html
head
title "<?= $this->title ?>"
body
<?php
// Since we're outputing Pug markup, we have to take care of
// preserving indentation.
$indent=str_repeat(' ', 2);
if ($this->foo) {
echo $indent . 'bar= myPost';
} else {
echo $indent . 'baz= myNav';
}
?>
footer
+footerContent
And if your Pug is processed on the server then you'd also include a Pug-processing step, for instance if you use Apache you could use
mod_ext_filter configured in such fashion with pug-cli installed:
ExtFilterDefine pug-to-html mode=output intype=text/pug outtype=text/html \
cmd="pug"
<Location />
SetOutputFilter pug-to-html
</Location>
Have you checked out the pug-php project? I personally have no experience with this particular module, but it seems to do just what you're trying to accomplish: Being able to use PHP in Pug.
You can use the scape syntax with quotes:
!{'<?php #php code ?>'}
For example:
p Hello !{'<?php echo "My name"; ?>'}
Will render:
<p>Hello <?php echo "My name"; ?></p>
You can test it here: https://pug-demo.herokuapp.com/
There is a well-known and well-maintained Pug processor written natively in PHP. You can use it to process your Pug files into HTML, just like the original Pug, with the advantage that it allows you to embed and use PHP code in your Pug file with ease. If you're working with PHP inside Pug, check it out:
Phug - the Pug template engine for PHP
p Hello !{'<?php echo "My name"; ?>'}
works but
link(href="../assets/css/style.css?v=!{'<?=$AppsVersion?>'}" rel="stylesheet" type="text/css")
don't work
I'm looking for something that Is really hard for me to do.. I really tried to search all over the net for Solution, But I couldn't seem to find any. I also tried doing this for hours.
What I'm doing: Making a theme for PHPBB2, Installed a MOD that can include PHP in themes.
What is the problem: When I'm doing {} tags in php, It just can't echo those tags.
Let's say I have a function that creates a Table for me, like that:
CreateMyTable(Name,Size,Color);
I put in the function those strings:
CreateMyTable("{FORUM_NAME}",1000,red);
The title stays blank, I actually want it to echo {FORUM_NAME}.
How can I do this?
P.S: I can't do this
CreateMyTable(?>{FORUM_NAME}<?php , 1000, red);
It's not going to work becuase <? = <!-- PHP --> , ?> = <!-- ENDPHP -->.
Thanks for your help :)
If you look in the PHPbb2 template class, you'll find that the template is simply an evaluated set of PHP using the eval() function. You can either print the contents of the PHP before it is parsed using eval() and then use the variable name that the template gives, IE something like (which may not work depending how your template is setup):
CreateMyTable(((isset($this->_tpldata['.'][0]['FORUM_NAME'])) ? $this->_tpldata['.'][0]['FORUM_NAME'] : '' ),1000,randomcolor());
Please note, in order to do it similar to the way above you'd actually have to insert this into your template class.
An much better solution is to avoid using the mod that allows PHP in templates and use JavaScript in the templates to create the function, then print a call to that JavaScript function.
This will work:
CreateMyTable(FORUM_NAME,1000,red);
I also noticed that red is used without quotes - is this also a constant? If it's a variable it needs to have a $ in front of it. If it's a string it should be between quotes.
CreateMyTable(FORUM_NAME,1000,"red");
Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php
I am trying to pass a php variable inside javascript bt it is not working.
Comment
Is it possible to do so or I may be incorrect somewhere...
Thanks for your response in advance! :)
First of all, you probably should change 'java' tag to 'javascript'.
Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:
<script type="text/javascript">
var foo = <?php echo $yourData; ?>;
alert(foo);
</script>
Comment
You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:
<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>
As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.
Now, your inline code can be simpler:
Comment
A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.
Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks.
However, I think you will have to pass UTF-8 strings to this function.
And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.
Comment
You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.
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.