So, I had a small doubt.
Will a piece of PHP code like this, which echoes a <script>
tag within it, go about the expected output (making that particular element #signupEmailExists
visible)? If so, what is the logic behind it?
echo '<script>document.getElementById("signupEmailExists").style.visibility = "visible";</script>';
2
Answers
Yes, with this code, it generates JavaScript code that manipulates the visibility of an HTML element on the client-side.
Your PHP code runs on your server (which is usually even a different computer than those your users are running their browsers on) and therefore it cannot directly run programs on client-side browsers.
But it can inject content into them.
So, your PHP code echoes out a
script
, which, if being inside or added into an HTML a browser displays, then it will attempt to get an element whoseid
issignupEmailExists
and set itsstyle.visibility
to"visible"
.Now, if you run this PHP code from the command-line or as a response to a POST request, then it will not enter a browser’s HTML, so the very fact that you
echo
ascript
will not necessarily end up putting thatscript
into an HTML.Yet, if this
echo
is part of a markup generation that’s being responded to a page that’s being loaded, then it will end up being generated into the HTML. Also, if this is a response to a request that’s sent from a page already loaded (via AJAX), then you will be able to inject this into the HTML as long as you trust the response of this request.In short: such an echo adds a string to an output, in this case, this string is logically a script and it may end up becoming an HTML tag, in which case it will be executed.