Put HTML String in PHP [duplicate] - php

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
So I'm trying to define $picurl1 so that it uses the value in $pic1. So in the end I want it to be:
<img src="./pictures/{definition of pic1}.png">
Right now I use this php code:
$pic1 = '<script src="pic.js"></script>';
$picurl1 = '<img src="./pictures/' + $pic1 + '.png'">';
Sorry if I'm not being very clear. I don't really know how to explain it. I hope you understand.
In other words, please tell me what I should change $picurl1 to.
By the way the script comes up with a random picture name without the '.png'.
Thanks in advance.

For starters, you're using the wrong operator to concatenate strings in PHP. I think you mean this:
$picurl1 = '<img src="./pictures/' . $pic1 . '.png'">';
More to the point, what is "definition of pic1"? Do you mean that the code in pic.js will randomly choose a file name, and you want its result to be the URL used in the img tag?
The problem you're encountering, then, is that PHP runs on the server while JavaScript runs on the client. So your PHP code can't use the result of pic.js because it won't have a result until the browser runs it, after the PHP code is done.
So you need to get that result client-side in JavaScript code.
How does pic.js create that result? That is, is there a function in pic.js? For now I'm going to assume there is, and I'm going to assume that function is called something like getFileName. (Just for the purpose of this example.)
After you included the JavaScript code, and after the img tag is in the document, you can call that function and set the src of the img tag to its results. To help us identify the img tag, let's give it an id:
<img src="default.gif" id="theImage" alt="This is a dynamic image" />
(I gave it a default value for the src since an empty value is invalid. I also have it an alt value for completeness.) To change its src value to the result of a function, you'd do something like the following:
document.getElementById('theImage').src = getFileName();
Remember, this is all client-side code. The only way you can use the "result" in PHP code is if the calculation is done in PHP, not in JavaScript.

You must consider that all the server side codes are executed before the client side codes (javascript, html, css , ...). so your code does not make any sense , you can not embed an undefined code inside another code that is executing sooner.
if your js code must return some thing, so remove php codes and simply use HTML instead

I tested this successfully:
$picName = "greenButterfly7"; //note no spaces inbetween green and butterfly
$picurl1 = "<img src='./pictures/" . $picName . ".png'>";
echo $picurl1;
or in pure HTML form:
<img src='pictures/greenButterfly7.png'>
or in embedded form (PHP inside HTML):
<img src='pictures/<?php echo $picName; ?>.png'>

Related

Adding PHP code in HTML which is already in PHP? [duplicate]

This question already has answers here:
Simple PHP stuff : variable evaluation [duplicate]
(5 answers)
Closed 11 months ago.
Basically, I want to add a PHP variable in HTML, with that HTML already being inserted into a constant, which is in PHP code. Here's what I mean: (obviously this code below is wrong, but imagine I would want to be inserting the $VARIABLE in the URL of the iFrame, for example)
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/$VARIABLE'></iframe>";
?>
What would be the syntax for adding that variable in there?
Thanks in advance!
This is just a basic template. str_replace() should do the trick.
const EXAMPLE = "<iframe src='http://example.com/{{{VARIABLE}}}'></iframe>";
$variable = 'example-sub-category
$merged_content = str_replace('{{{variable}}}', $variable, EXAMPLE);
Note I used {{{}}} to denote the insert. This is not PHP syntax, but you will find templates often use something like that the would not be expected in the text otherwise to denote placeholders.
Have you tried:
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/".$VARIABLE."'></iframe>";
?>
You can insert PHP anywhere in HTML just by defining its tags <?php ?>
<iframe src='http://example.com/<?php echo $VARIABLE; ?>'></iframe>
Using your example:
const EXAMPLE = "<iframe src='http://example.com/" . $VARIABLE . "'></iframe>";
For this kind of task I'd better use sprintf:
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/%s'></iframe>";
echo sprintf(self::EXAMPLE, $VARIABLE);
To move in and out of php within your html, use <? [php code here...] and ?> to end php and continue with html. You can escape characters with a back slash \ and using single quotes as Rujikin mentioned above. Or, within PHP, you can echo your html so that you're not bouncing in and out of php.
For example:
some php...
echo '<span style=\"color:#980000\"><strong>\"{$searchTerm}\"</strong></span>';
more php...
Notice that the html is enclosed in single quotes (end-to-end) and inside the single quotes, double quotes are used where required by html, e.g., for the <style> tag.
This example is basically saying, "echo whatever the value of php variable $searchTerm is, put it in quotes that's required by echo, and make it dark blue (#0000FF) and bold (<strong>).
I hope this helps. :)
You can try something like:
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/$VARIABLE'></iframe>";
$newHtml = str_replace('$VARIABLE', $VARIABLE);
?>
As you mentioned your code was fake, so I guess what you need is to replace some places in your HTML strings by a content which is unknown until you php script is executed, right ?
so what you need is to put some place holders and change them later, as I showed in my snippet above.
Hope this works

How to print code generated by some function in php?

I have a code in my CMS that prints content:<?php print $content ?>
I would like to output the actual php and html code behind $content, ideally in the browser. What I mean here is not the result in the browser, but the actual code behind it.Is it possible at all?
EDIT: Just to explain further: I need to print the source code of $content. Basically this variable produce some html and php content. I would like to see the code it produces, change it and replace $content with my custom code. Ideally the source code should be printed in the browser, is there anny php function that does it?
First off install the Devel Module, it has a wonderful function called dpm() which will print the contents of any variable to the Drupal messages area.
Then you need to go into your theme's template.php file and implement hook_preprocess_page():
function mytheme_preprocess_page(&$vars) {
dpm($vars['content']);
}
That will print out the $content array before it's rendered into a string. In the same preprocess function you can also change $vars['content'] as you see fit, and the changes will be reflected in $content in page.tpl.php.
Hope that helps
What do you mean by 'the code'? I think what you want to do is not possible, unless you make some kind of quine it's not possible to output the actual php code of a php file when you run it.
If $content is something like:
$content = 3 + 4 + 5;
echo $content; will output 12 yes? But I'm taking it you want to output 3 + 4 + 5 or something along those lines. The thing is, PHP (although it doesn't feel like it) is compiled. In this trivial example, 3 + 4 + 5 is stored exactly nowhere in your compiled program, it is stored as 12 (since it's static). More complex lines of code will be stored as pointers, values etc., all in nicely obfuscated machine code. Getting back to the 3 + 4 + 5 requires reading the input file and outputting the relevant line, which is difficult (think about what happens if you add or remove some lines, or how your running program knows where in the source file it is, or even if it's in the right source file).
tl;dr: this is not possible.
Well, if you just want to see html source for $content, you should simply use htmlspecialchars :
echo htmlspecialchars($content);
http://php.net/htmlspecialchars
or http://php.net/htmlentities

var reads HTML code as STRING

Very simply, i want to make a variable reads the html code as string ,, i mean dont execute it (run it) .
the problem with the code is : i have a html file , and i want to get the content of it , and make some preg_replace for it (run a function on the html code), the problem is i cant use preg_replace, or any another function because the html code is executed by php (php reads the html code)..
i wish you understand me, i want something like highlight_string, but it save the html code in the variable.
Thank you.
you're probably trying to include or require the HTML code.
which is incorrect since it is evaluated as part of the source.
instead, use a function such as file_get_contents() to read the file into a string.
Use file_get_contents() as #David Chan suggested and then pass the result through htmlentities()... it converts the characters to HTML entities (i.e., < to <).
$getTheContent = file_get_contents($filepath);
echo htmlentities($getTheContent);
It should return the code, not executed.

Formatting HTML code to be output in plain text, with PHP [duplicate]

This question already has answers here:
Converting HTML to plain text in PHP for e-mail
(14 answers)
Closed 8 years ago.
I have this function that takes some user-submitted HTML code from the database:
function Code($code)
{
return "<pre><code>".nl2br(htmlspecialchars($code))."</code></pre>";
}
I'll just be calling it like echo code($query->row('html'));. I know my question lacks 'depth', but is this the best way to do it? Or could the outputted formatting be parsed (e.g. Javascript injections), or not output correctly on some machines, etc.?
Thanks!
Jack
EDIT: I have a new (related) question: I would like to highlight the string using highlight_string(). However, I cannot make it work properly. I think I understand why but am not too sure how I can rectify this.
function Code($code)
{
return "<pre><code>".highlight_string(nl2br(htmlspecialchars($code)))."</code></pre>";
}
As you can see from that I'm using highlight_string() on it all. however, the output isn't highlighted at all, instead it is output as character entities (<, '>' etc). If I reshuffle the function ordering to something like:
return "<pre><code>".nl2br(htmlspecialchars(highlight_string($code)))."</code></pre>";
I find that the character entities aren't output, but the string still isn't highlighted. To clarify, I have no CSS formatting that would affect the text colour applied either. Also, I've checked my PHP settings and there are definitely highlighting colours specified in there.
Nope, that's fine. htmlspecialchars() will turn any HTML control character into its entity equivalent (< => < etc.), there is no way of injecting anything there.

What's the best way to pass a PHP variable to Javascript? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.
Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.
What are good ways to pass variables from PHP to Javascript? And how does our solution sound?
General Data Passing
A commonly used exchange format for JavaScript is JSON, using json_encode. A PHP file like this:
<?php
$data = array("test" => "var", "intvalue" => 1);
echo json_encode($data);
?>
then returns a JavaScript object literal like this:
{
"test" : "var",
"intvalue" : 1
}
You can directly echo it into a JavaScript variable on your page, e.g.:
var data = <?php echo json_encode($data)?>;
...or request it via Ajax (e.g. using jQuery's getJSON).
Outputting to attributes on tags
If you just need to output a string to an attribute on a tag, use htmlspecialchars. Assuming a variable:
<?php
$nifty = "I'm the nifty attribute value with both \"double\" and 'single' quotes in it.";
?>
...you can output it like this:
<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>
...or if you use short tags:
<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>
<?php
$my_php_var = array(..... big, complex structure.....);
?>
<script type="text/javascript">
my_js_var = <?=json_encode ($my_php_var)?>;
</script>
I use to echo them all together at the head of the HTML. Seems clean enough for my needs :)
There are 3 ways you could do it:
Echo them directly into the javascript source:
<?echo "var user = '$user';";?>. Works, but it's messy.
Pass them in via an ajax request. This is the closest you can come to native variable passing, but the downside is it takes an extra HTTP request.
What you're doing, which is passing them by generating hidden form fields and then reading them.

Categories