Displaying PHP Code as Plaintext - php

I need to do something like this:
header("Content-Type: text/plain");
echo <<<EOT
<?php echo 'arbitrary code using ' . $variables . ' and such.';
echo 'finished';
?>
EOT;
The problem is, PHP still interprets the inline PHP as code and tries to execute it. I would like just to see the code printed in the window.

Use Nowdoc, notice the quotes around 'EOT':
echo <<<'EOT'
<?php echo 'arbitrary code using ' . $variables . ' and such.';
echo 'finished';
?>
EOT;
Or use a single quoted string, obviously escaping single quotes in the string:
echo '
<?php echo \'arbitrary code using \' . $variables . \' and such.\';
echo \'finished\';
?>';

You could use highlight_string function, it receives a string containing your php code and outputs html with the syntax highlight colors.
ex:
<?php highlight_string("<?php echo 'hi'; ?>");?>
You have also the function highlight_file, same thing, but receives a string with the file location.
Doc:
http://php.net/manual/en/function.highlight-string.php
http://php.net/manual/en/function.highlight-file.php

Related

Run PHP code while echoing PHP

I'm using the echo command in PHP, but I want to enter PHP code like <?php echo $variable [id_login]?>, while echoing something else out, but this does not work.
Is this possible to do, and if so, how would I do it?
echo "<script>location='member.php?&id=<?php echo $taruh[id_login] ?></script>";
You cannot use echo or open/cloce php twice like you did, you might want to try something like the line below,
echo '<script>location=member.php?id=' . $taruh[id_login] . '</script>';
after echo you can write enything you'd like, even if it's a php variable, just use single quote and dot where you need it (like I do here), as you can see, echo is only used once..
For example:
<?php
$your_variable = 'some text';
$other_variable = 'some PHP code';
echo 'I wrote: ' . $your_variable . ' and ' . $other_variable . '!';
?>
Output will be:
I wrote: some text and some PHP code!
I hope this will bring you into the right direction..
EDIT
Also important: if you use query string in URLs, the first 1 can be a ? every other part after should be a & for example see the url below
http://www.example.com/index.php?id=12345&coder=yes&country=usa
before id I used a quest sign, for all others I didn't use the quest sign...

php json_array echo tweet text

I am attempting to echo a Tweet button in a table and have the tweet text from a json_array response.
The following code work unless the json response has a single quote(apostrophe) in it.
If the response has a single quote ( example I'm unhappy) this breaks the tweet text and stops after the I
is there away to strip all single quoyes from an array? or is there a better way to do what I am trying to accomplish?
echo "<table border='0'>";
echo "<tr><td><a href='https://twitter.com/share' class='twitter-share-button'{count} data-text='";
echo $json_array["reasons"][0]["author_name"], "says ", $json_array["reasons"][0]["content"];
echo " data-via='OnRecall' data-hashtags='OnRecall'>Tweet</a></td></tr>";
echo "<tr><td>Name: </td><td>", $json_array["reasons"][0]["author_name"];
echo " -> Liked: ", $json_array["reasons"][0]["like_count"], " times.</td></tr>";
echo "<tr><td width= '20'></td><td>", $json_array["reasons"][0]["content"];
echo "</td></tr></table><p><hr></hr></p>";
So if $json_array["reasons"][0]["content"] has a single quote in it, the tweet text stops at it.
Thank you for reading.
You can use PHP's htmlspecialchars function to accomplish this. With the ENT_QUOTES flag, this function will encode all quotes as HTML entities (' becomes ') and also significantly reduce your vulnerability to Cross-Site Scripting attacks -- this is especially important when the data you're displaying comes from an untrusted source (like someone else's Twitter feed):
$content = htmlspecialchars($json_array["reasons"][0]["author_name"], ENT_QUOTES)
. "says "
. htmlspecialchars($json_array["reasons"][0]["content"], ENT_QUOTES);
echo "<a ... data-text='$content'>';
You need to escape all the single quotes in your string. You can use str_replace() function to replace all ' to \', like this:
$content = str_replace("'","\'",$json_array["reasons"][0]["content"]);
// now echo $content
Here's the reference:
str_replace()

Echo javascript with a php function inside?

Oh boy! I cant get this to work. Any ideas on what the heck I'm doing wrong? Here's the code.
I'm trying to echo the script but use a php function to get the directory of the js file!!
Any help would be appreicated!!
echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';
I've tried dif scenerios with escaping but cant get this to output correctly.
Since you're already in the PHP context, you can simply concatenate the strings, like so:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Using sprintf() looks more cleaner, though:
echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());
Instead of opening another script tag inside the string, concat the string and echo. The <?php within your string will not be evaluated.
echo '<script src="'. get_some_function() . '/js/main.js"></script>';
Simple string concatenation:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Don't forget to properly escape the output of your function!
try doing this:
echo '<script src="'.get_some_function().' /js/main.js"></script>';
or this:
$value = get_some_function();
echo '<script src="'.$value.' /js/main.js"></script>';
Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed.
Similar is true for returned data from a function stored in a varaible. If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . If you are using double quotes, then no need to use . .
Like in all above answers, they have used . to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) :
$src = get_some_function();
echo "<script src=$src/js/main.js></script>";
But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes.
Hope this will help...

using ' and " in php syntax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
Ive started on part of my new year resolution and decided to learn php, as part of it im trying to parse in an xml feed, and echo out the name of the events wrapped in <a> tags linking them back to the events page on the xml feed's site.
I think ive got it all in but i cant seem to see why this isnt working im just getting a blank page, if some one could point me in the right direction it would be much appreciated, cheers
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href="$event_attributes['url']">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
</ul>
echo "<a href="$event_attributes['url']">";
try changing that line to
echo "<a href=\"".$event_attributes['url']."\">";
The Php parser is pretty funny about this. Usually you pick one and just stick to it, or use both single quotes and double quotes as you please. Just remember that strings with double quotes are parsed for variables.
$hello = "Hello";
echo "$hello master";
is the same as
$hello ="Hello";
echo $hello.' master';
When you are testing your PHP scripts, you'll find it useful to switch on errors - then PHP will actually tell you why it isn't showing you anything:
error_reporting(E_ALL);
Normally you will have missed a ; or mis-typed a variable name.
in your case the error is here:
echo "<a href="$event_attributes['url']">";
You have accidentally ended the string with a double quote, so PHP thinks the string ends here:
echo "<a href="
This is where using single-quotes can be very handy because your double quotes won't then close the string.
echo '<a href="' . $event_attributes['url'] . '">';
The main difference between single and double quotes in PHP is that double quotes has special clever parsing rules and single quotes doesn't. For example:
$myVar = "BLAH";
echo "Example $myVar"; // Example BLAH
echo 'Example $myVar'; // Example $myVar
In your unordered list, you should use a dot to concatenate your string, and escape your double quotes like this:
echo "<a href=\"".$event_attributes['url']."\">";
Instead of
echo "<a href="$event_attributes['url']">";
Your example throws and error because you haven't used proper string concatenation. However, even with correct concat, it would render as <a href=http://someurl>, and you'd need to add the double quotes according to html standard. Hence you have to double quote.
if you want to not be troubled by having to switch between using a ' or a " then i suggest using the php alternative syntax php alternative syntax
with the given code it would look like
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php foreach($type->market as $event):?>
<li>
<a href="<?php echo $event_attributes['url']; ?>">
<?php echo $event_attributes['name']; ?>
</a>
</li>
<? endforeach;?>
</ul>
one advantage this would bring is that it would produce cleaner code since you can clearly distiguish your php code from your html which is the presentational part at the price writing all those other <?php ?> and as what others would claim a performance degradation. the choice is yours
Change
echo "<a href="$event_attributes['url']">";
for
echo "<a href=".$event_attributes['url'].">";
You are missing the periods in your second echo, where you have your $event_attributes['url']
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href=".$event_attributes['url'].">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
I would recommend you to enable your error log, it would allow you to know the line with problems in any of your scripts.

php link system problem

<?php
$total=3;
echo '
<div class="idsdiv">.$total.<div> ';
?>
i want to appear $total variable number in the link.why is this script not working?
Enclose the whole string with double quotes to embed variables inside:
echo "<div class=\"idsdiv\">$total<div>";
You need to use double quotes around your HTML and single quotes around your attributes or do this...
echo '<div class="idsdiv">' . $total . '<div> ';
PHP doesn't process variable names in strings enclosed in single quotes.
<?php
$total=3;
echo '<div class="idsdiv">',$total,'<div>';
?>
Look at the string section of php.net (http://php.net/string) they talk about how to use each of the types. One of quote being the ' where nothing is parsed.
<?php $total=3;
echo "<div class=\"idsdiv\">$total<div> ";
?>
you had errors with your quotes
You can print HTML without printing it, like so:
<?php
$total = 3;
?>
<div class="idsdiv"><?php echo $total; ?></div>
When I still did PHP, I found it much easier to manage than escaping tons of quotes and things like that.
You can even do it inside of an if block too:
<?php
if ($foo == 'bar') {
?>
<div>Foo is bar</div>
<?php
}
?>
The method I like is
<?php
$total=3;
echo "<div class='idsdiv'><a href='profile.php?id={$total}'>{$total}</a><div>";
?>
It is my method, but there are plenty of ways to do it. Maybe even too many. If you want more information you can always refer to the documentation.
<?php
$total=3;
echo '<div class="idsdiv">'.$total.'<div>';
?>
You're quote are missing before and after the $total

Categories