formatting javascript to be echoed out by php - php

I am trying to echo out some JavaScript, but I can't get the formatting right I start off by putting the javascript I want to out into a string
$javascript = 'onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='white'"';
and then echo it out like this
$hint="<span $javascript>".$artistname->item(0)->childNodes->item(0)->nodeValue."</span>";
any help would be much appreciated

Using the event attributes is considered bad practise. JavaScript should be unobtrusive. Also, I do not see why you would have to store the attributes in a PHP variable instead of simply adding them to the span tag directly. And last but not least, why dont you just use the CSS :hover selector to change the background color when the mouse is over the span? That would be a clean approach.

As you can tell from the coloring in the quoted code, you need to escape your single quotes. You will end up with:
$javascript = 'onmouseover="this.style.backgroundColor=\'blue\'" onmouseout="this.style.backgroundColor=\'white\'"';

You should start with the output string. You want it to look like this:
onmouseover="this.style.backgroundColor='blue'"
onmouseout="this.style.backgroundColor='white'"
Now, in order to put that string in PHP into a variable, you need to surround it with either single or double quotes. Since your string contains both single and double quotes, either of them needs to be "escaped".
Using single quotes:
$javascript = 'onmouseover="this.style.backgroundColor=\'blue\'"
onmouseout="this.style.backgroundColor=\'white\'"';
Using double quotes:
$javascript = "onmouseover=\"this.style.backgroundColor='blue'\"
onmouseout=\"this.style.backgroundColor='white'\"";
Edit:
Final note: read carefully what Gordon has posted.

Related

PHP echo returning blank value

So I am trying to link using data I got from a function but it keeps giving me a blank value for ID. Here's my code for what I'm trying to print
<h3 style="text-align: center;">Seller: <?php $sellername =
getNameFromListingID(); $id = getIDByUsername($sellername); echo "".$sellername."";?></h3>
The functions work properly, I have tried printing both of them and it works. They're in a file called getinfo.php, which I have
Include 'getinfo.php';
At the top of my document.
The link with the name works but I always get seller.php?id=, with no value after. Any clue as to why?
You're ending the href attribute too early.
<a href=\"seller.php?id=".$id."\">
This will put the $id inside the href attribute, where it belongs.
Use single quotes in PHP, it's a good practice to get into, and it's also slightly (a teeny tiny bit) faster for PHP to process. Why? Because, when you use double quotes, you're telling PHP that your string contains variables that may need to be evaluated.
So in truth, you don't even need the quotes around variables here.
echo "$sellername";
But doing it like this would be following a best practice.
And now you don't need to escape \" double quotes that HTML uses.
echo ''.$sellername.'';
Caution: It's also a very good idea to escape special characters in anything you're outputting into HTML markup. That avoids the potential for an XSS vulnerability. See: htmlspecialchars()
echo ''.htmlspecialchars($sellername).'';

Displaying a new image/window with PHP variables when you rollover an image

When I first asked how to achieve something like this: http://backpack.tf/ (Mouse over on any item) I got pointed to JQuery.
Then I tried achieving the same by using; http://jqueryui.com/tooltip/
I was able to create the window but I couldn't figure out how to set it up so that it displays $object->level or some other variables like that.
I than tried; http://stevenbenner.github.io/jquery-powertip/
Again I was able to create the tooltip. And it lets you create tooltips using the data-powertip="" tag. Like this;
Some Link</div>
But still, I can't place my variables in there. I'm using echo to print this into HTML body and all the quotation marks start to be a problem.
Please help me with this. How to create eye-candy tables like when you hover on an item in this page: http://backpack.tf/
you may need to escape your quotes.
For instance,(assuming your tooltip plugin works by showing some data from an attribute), try this:
Make your html element use double quotes for attribute like(assuming it uses data-tooltip for tooltip data, you need to change that to whatever your plugin uses.)
<img data-tooltip="your data will go here" ... >
^ ^
Used double quotes for attribute
you would be echoing that from php using single quotes because you have double quotes there, like:
echo '<img data-tooltip="your data will go here" ... >';
Now your problem is you need to put html inside that attribute, fortunately you can use single quotes for html attributes too but unfortunately you also used single quotes to echo from php.
What you need to do is escaping the inner quotes! like:
echo '<img data-tooltip="<span class=\'some-css-class\'>Some Text '.$somePhpVariable.'</span>" ....>';
you escape your quotes with backslash. You will see that stackoverflow code highlighter will highlight the above code properly.

Escaping string before assigning to innerHTML echoed by PHP

I'm encountering a problem involving escaping character that I think it's not simple at all. If this is done in javascript, nothing to say but the context is using echo command (in PHP) to write javascript code like this:
echo "<script>document.getElementById('spanID').innerHTML=\"$x\"</script>";
$x is a variable in PHP environment, which can contain both single and double quotes. What I do here is:
1. Keep the $x not change, and if $x contains any double quote, the above code won't work, the text echoed may look like:
<script>document.getElementById('spanID').innerHTML="leftside"rightside"</script>;
I supposed $x = leftside"rightside, and you can see it surely won't work.
Escape the double quotes in $x (change all " to "), then the text echoed may look like this:
document.getElementById('spanID').innerHTML="leftside"rightside";
The " won't be converted to " when it is assigned to innerHTML attribute of a Span (for e.g), so instead of my want, the innerHTML of my SPAN should be leftside"rightside, it will be leftside"rightside.
If I change the " to ' in the original echo, like this:
echo "<script>document.getElementById('spanID').innerHTML='$x'</script>";
It is the same because $x here can contain both single and double quotes.
I don't find out any other ways to escape quotes in this case. Could you please help me out?
Thanks!
You need to put between the quotes a string that is a valid string of JavaScript containing valid (and safe) HTML.
Your best option is to not use innerHTML and instead use document.createTextNode which means you only need to slash-escape the content.
Otherwise, you need to HTML escape, then slash escape the content. For correctness, your slash-escaping function should escape at least double-quotes, backslashes, and all JavaScript newlines (U+A, U+D, U+2028, U+2029). I believe PHP's addslashes does not handle U+2028 or U+2029 by default but How to escape string from PHP for javascript? has some alternatives.
To put it all together:
$x_escaped = json_encode($x, JSON_HEX_TAG);
echo "<script>document.getElementById('spanID').appendChild(document.createTextNode($x_escaped))</script>"
should do it. The JSON_HEX_TAG makes sure that $x_escaped will not contain </script> or any other content that prematurely ends your script tag. </script> will instead become \u003c/script\u003e.

PHP: literal \n rather than new line

I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n');";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n into the source of the page.
Can anyone point me in the right direction? Thanks.
Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.
Try this:
$str="var lines = data.split('\\n');";
you can escape \ like this: \\.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...
Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.

What is <<<_END?

I'm new to PHP and don't understand what the point of <<<_END is. Could someone please explain when this should be used? I've looked at various examples and they all seem to have HTML embedded within them. But I can use HTML without the <<<_END tags, so why should I use them? I tried searching the manual, but I keep finding the end() method for arrays.
It's the start of a heredoc. you can do:
$data = <<< _END
You can write anything you want in between the start and end
_END;
_END can be just about anything. You could put EOF or STUFF. as long as you use the same thing at the start and the finish.
This signifies the beginning of a heredoc (a multi-line string that allows you to use quotation marks in the middle, unescaped) that ends when you encounter the _END
It can be useful to define HTML in one of these if the goal is to assign it to a variable or pass it to a function rather than printing it to the web server immediately.
That syntax is called heredoc
<<<_END
some text
_END
Basically, it's a way of writing a string without worrying about escaping quotes and so on.
As you've mentioned, it doesn't really provide a lot of benefit over other string formats - although, it does mean you can write a block of HTML without escaping out of PHP with ?>
It also isn't too popular as its use generally goes against the practice of seperating content from logic by embedding the content in the middle of your script.
Does this help? http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
It allows you to echo out a block of text (just the same as with echo "words";), but without using the beginning/ending quotes, and without having to escape contained double quotes. Read the manual link above for more detail.
It's a heredoc. It's just a way of defining a string.

Categories