0

I'm trying to call PHP variable into HTML input field. Please see below code.

<html>
<?php
    $A_variable = $_GET['some text'];

echo "<script type='text/javascript'>";
echo "document.getElementById('A_input').value = ";$A_variable;
echo "</script>";
?>
<input type="text" id="A_input" name="A_input" placeholder="input" Readonly>
</html>

Please, advice am I trying in a proper way? Your assistance is highly appreciated.

3
  • 1
    You have there syntax error in JS (missing quotes around, if $A_variable isn't a number), syntax error in PHP (; instead of .) and you call the script before input exists. Check the console. Commented Mar 29, 2018 at 8:08
  • Danger: This code is vulnerable to XSS User input needs escaping before being inserted into an HTML document!. Commented Mar 29, 2018 at 8:27
  • stackoverflow.com/questions/14028959/… covers one of the several things that are wrong with tthis code. Commented Mar 29, 2018 at 8:30

1 Answer 1

2

You don't need Javascript to achieve that,

simply,

<html>
<?php
    $A_variable = $_GET['some text'];
?>
<input type="text" id="A_input" name="A_input" value="<?php echo $A_variable; ?>" placeholder="input" Readonly>
</html>

[Edited] Looking at code above we can make it even simpler

<html>
<input type="text" id="A_input" name="A_input" value="<?php echo $_GET['some text']; ?>" placeholder="input" Readonly>
</html>

PS: This way is not advisable since it vulnerable to XSS attack.

Simplest way to prevent XSS attack is by using stip_tags()

<html>
<input type="text" id="A_input" name="A_input" value="<?php echo strip_tags($_GET['some text']); ?>" placeholder="input" Readonly>
</html>
Sign up to request clarification or add additional context in comments.

9 Comments

1. XSS. 2. Why $A_variable, when you can echo $_GET['some text'] directly inside value attribute??
1. XSS - Obviously yes, but it is whole different topic. 2. Agree. Just to make question owner can see how a variable can easily be outputted to html tags.
"XSS - Obviously yes, but it is whole different topic" - It should be included in the answer. People tend to just copy/paste answers here, thinking they are totally fine. If we see security issues, we should point them out and, at least, give them a reference to where they can read more about them.
strip_tags will not protect this code from XSS attacks. some+text="%20onmouseover="alert('xss')"
@anasceym: strip_tags doesn't solve XSS and modify value (why '2 > 1' (two is greater than 1) should be invalid input?). The right way is to use php.net/manual/en/function.htmlspecialchars.php
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.