How to prevent PHP echo from ending a JS string? - javascript

I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Sign up page</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1>Sign up page</h1>
<form action="test.php" method="post">
<input placeholder="Enter your username" name="username"/><br/>
<input type="password" placeholder="Enter your password" style="margin-bottom:5px" name="password"/><br/>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
if(isset($_POST["username"],$_POST["password"],$_POST["submit"])){
if(mb_strlen($_POST["username"])<8){
?>
<script>
alert("Your username must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[0];
i.value="<?php echo $_POST['username']; ?>";
i.focus();
</script>
<?php
}else if(mb_strlen($_POST["password"])<8){
?>
<script>
alert("Your password must be at least 8 characters long.");
var i=document.getElementsByTagName("input")[1];
i.value="<?php echo $_POST['password']; ?>";
i.focus();
</script>
<?php
}else{
echo "Successfully signed up!";
}
}
?>
</body>
</html>
It works fine most of the time, but if you try entering ";f(); into the username field, you get an error in the console and no alert.
As is clearly visible, that is happening because when PHP receives the input, it echoes it in the JS string. "; ends the string and the statement, while f(); causes an error which prevents the input from focusing. This occurred under 8 characters, therefore causing it to fall under mb_strlen($_POST["username"])<8.
Usually I would just use htmlspecialchars, but if you try adding that, then if you put ";<!--, it comes out with < instead of <. Some users may want < (or other &*; characters) in their username, and (if they weren't developers) would be surprised what < means.
So how do I prevent the JavaScript Injection from occurring while still keeping User Friendliness?

You should be using json_encode to output your values (and note you no longer need the enclosing "s):
i.value=<?php echo json_encode($_POST['username']); ?>;
This will ensure that quotes within the string are escaped and the entire value is treated by JavaScript as a string. For your example data, this will produce
"\";f();"

The problem is the double-quote in this example. Try addslashes:
i.value="<?php echo addslashes($_POST['username']); ?>";
Though Nick's answer may be better for JS. I'm more PHP than JS.

You should never inject unsanitized code into anything. This can cause XSS attacks at the least.
I think the easiest way to sanitize your code while keeping the user friendliness would be to use json_encode()
<?php
}else if(mb_strlen($_POST["password"])<8){
$data = json_encode(['password' => $_POST['password']]);
?>
<script>
alert("Your password must be at least 8 characters long.");
var user_data = <?php echo $data; ?>;
var i=document.getElementsByTagName("input")[1];
i.value=user_data.password;
i.focus();
</script>
However!
You should really be putting this in the Input element:
<input type="password" value="<?=htmlspecialchars($_POST['password'] ?? '',ENT_QUOTES); ?>" placeholder="Enter your password" style="margin-bottom:5px" name="password"/>

Related

How to display javascript alert without reset form

I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.
I tried this way:
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
I also tried the one below but still the same thing happened:
if($pwd != $pwd2) {
?>
<script type="text/javascript">
alert("Password does not match!");
</script>
<?php
}
Your validation is on server side, once you hit the server the form gets reset everytime, for showing validation error from server you need to pass the values to the form again with errors.
If you want to show the alert on validation error, use client side validation with jQuery or simple JS. In this way your form's values remain the same and the alert will be popped up.
if you really need using php
<?php
$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : "";
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2'] : "";
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
>
<input name"pwd" value="<?php echo $pwd; ?>">
<input name"pwd2" value="<?php echo $pwd2; ?>">
If you want other input fields not to be empty after submission you should try this using php.
Let's say your input field is username.
$username = $_POST['username'];
<input type="text" name="username" value="<?php echo htmlentities($username); ?>">
When you use this, after you clicked ok and get the alert, your username field will not be empty. The value you entered will appear in the text field.
Try this code to solve your problem.
$username = $_POST['username'];
$password = $_POST['password'];
<input type="text" name="username" value="<?php echo htmlentities($username);
?>">
<input type="password" name="password">

calling for javascript function in php form

I am using a contact form on my website and I want it to use a javascript function to use a popup box to tell the user that they have not filled all fields. I have this code:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "Email sent!";
}
}
?>
</script>
However, the website displays this error:
Fatal error: Call to undefined function requiredfields() in /home/a8502709/public_html/test/contact.php on line 46
The line above is the line that it echoes the calling for the function. How can I properly call the function in echo?
You didn't quote your echo output:
echo requiredFields();;
It should be:
echo "requiredFields();";
Otherwise you're telling PHP to execute the requiredFields() function, which doesn't exist in PHP. Hence the error. Your intent here is to tell the JavaScript on the rendered page to execute the function. So as far as PHP is concerned you're just outputting a string to the page.
Note also that this is a syntax error:
echo "Email sent!";
What this will do is emit the following to the JavaScript in your <script> block:
Email sent!
Which, of course, isn't valid JavaScript. You probably meant to output that somewhere else in the page.
Edit: You also seem to have a significant logical error in your code. If you remove the unrelated lines, your structure is essentially this:
if ($action=="") /* display the contact form */
{
?>
<script type="text/javascript">
<?php
} else {
echo "requiredFields();";
}
?>
</script>
So... You only open the <script> tag in the if block, but you use that tag in the else block. By definition both can't execute. Only one or the other. So you're going to have to restructure this a bit.
Maybe close the <script> tag in the if block too, and then open another one in the else block? Or have multiple if/else blocks for the HTML and for the JavaScript? There are a couple of different ways to structure this. But you should see what I'm talking about when you view the page source in your browser. You'll see that, in the event of the else block, you're never creating a <script type="text/javascript"> line and therefore aren't actually executing any JavaScript.
Though, thinking about this some more, it doesn't make sense at all to have the JavaScript start in the if block. Since only the else block uses it. You can't define the function in the if and then try to use it in the else because, again, by definition only one or the other would execute. Maybe just move all of the JavaScript to the else:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
}
else /* send the submitted data */
{
?>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "alert('Email sent!')";
}
?>
</script>
<?php
}
?>
Honestly, this mix of PHP/HTML/JavaScript you have here is a little confusing. Which isn't making this any easier for you. You'll probably want to re-structure this a bit once you get it at least working.

send PHP variable to javascript function via HTML

I am trying to send a PHP variable to a Javascript funtion using HTML. I dont know if it is possible or not. I am a newbie.
This is all the code in both the files, index.php and abc.php
P.S. I have changed the file name from index.html to index.php
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<?php
require("../php/abc.php");
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Some Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="file.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="here.js"></script>
</head>
<body onload="init();">
<noscript>
Your browser does not support Javascript!!
</noscript>
<table id="content">
<tr>
<td>
<div id="scroll"></div>
</td>
<td id="colorpicker" valign="top">
<img src="palette.png" id="palette" alt="Color Palette" border="1" onclick="getColor(event);" />
<br />
<input id="color" type="hidden" readonly="true" value="#000000" />
<span id="sampleText">
(text will look like this)
</span>
</td>
</tr>
</table>
<div>
<input type="text" id="userName" maxlength="50" size="10" onblur="javascript: check('<?php echo $phpVariable; ?>');" />
<input type="text" id="messageBox" maxlength="2000" size="50" onkeydown="handleKey(event);" />
<input type="button" value="Send" onclick="sendMessage();" />
<input type="button" value="Delete All" onclick="deleteMessages();" />
</div>
</body>
</html>
Javscript function
function check(param_name)
{
var oUser=document.getElementById("userName");
oUser.value = param_name;
}
abc.php
if(isset($_POST['user_name'], $_POST['action'])) {
$user_name = $_POST['user_name'];
$action = $_POST['action'];
if($action == 'joined') {
$phpVariable = user_joined($user_name);
}
function user_joined($user_name) {
$servername = "";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_name = mysql_real_escape_string(htmlentities($user_name));
$sql = "INSERT INTO table_name (column_name) VALUES ('$user_name')";
$query = "INSERT INTO table_name2 (column_name) VALUES ('$user_name')";
$result = $conn->query($query);
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error in inserting: " . $sql. "<br>" . $conn->error;
}
return $user_name;
$conn->close();
}
Try something like that
HTML
<input type="text" id="nametxt" />
<button id="btn-check"></button>
Javascript
$(document).ready(function (){
$("#btn-check").click(function(){
var name = $('#nametxt').val();
var login = {
parameter: name
};
$.ajax({
type: 'POST',
url: 'file.php',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
});
});
PHP
<?php
//do some
echo information; -- this way return parameters
?>
As you have written, the way to output the value of a PHP variable to an HTML page is by doing <?php echo $phpVariable ?>. In newer versions of PHP (and in older ones where the setting was turned on), you can shorten this to <?= $phpVariable ?>.
You are getting an 'undefined variable' warning probably because the $phpVariable is not getting set. In your code, this variable is only initialized if $action == 'joined'. If you want it to have a default value, give it one first:
$phpVariable = null;
// note that three equals signs are not necessary here
// but a good habit for cases where it matters
if ($action === 'joined') { ... }
When you output the PHP variable into a JavaScript string, you should escape the output so that you don't leave your visitors vulnerable to XSS (cross-site scripting) attacks. In this case, json_encode should be sufficient. However, since your JavaScript is not within a <script> tag, but rather within an onblur attribute, you have to escape any characters which are special in HTML. Since you're using double quotes around the attribute value, htmlspecialchars is sufficient for that. So in all, you will output htmlspecialchars(json_encode($phpVariable)). The reason for all this is that you don't want to rely on your input being clean -- mistakes will be made and when they do, you don't want to let someone attack your users.
<input type="text" id="userName" maxlength="50" size="10"
onblur="javascript: check('<?= htmlspecialchars(json_encode($phpVariable)) ?>');" />
Since we've given a default value (null) for $phpVariable and we are calling the check function with it, we should add a "check" to the check function to ensure that we got a real value, like this:
// you should use camelCase or under_scores, but not both, for consistency
function check(paramName) {
// loose equals to match null or undefined
if (paramName == null) {
return;
}
var oUser = document.getElementById("userName");
oUser.value = paramName;
}
Alternatively, if you want to be really careful about your function inputs, you could verify that paramName is a string and that it has a nonzero length, but in a dynamically typed language like JavaScript, doing all these checks manually sometimes becomes a losing battle.
This is not going to work as-is because PHP is executed server-side and JavaScript is executed client-side.
In order to do this, you're going to have to make an AJAX call to a PHP file and then use JavaScript on the results.

Error: Permission denied to access property '$'

everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.

Javascript - cannot get login script to only accept set password

I am trying to make a basic login screen using Javascript, in which I don't have much experience. I managed to get this much, but for some reason, whenever I enter text into the input box it will redirect me, no matter whether it is the correct password or not.
Also, a second question, to determine whether or not a user has logged in (to redirect them to the login page), would I have to use something other than JS, such as PHP?
Code:
<!doctype html>
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function login()
{
if (password = "cat")
{
location.assign("home.html");
}
}
</script>
</head>
<body>
Password: <input type = "password" name = "password">
<input type = "button" value = "Login" onclick = "login()">
</body>
</html>
currently you are using if(password = "cat") which is actually an assignment operator not used for comparison. If you don't know the type of data to be compared use == otherwise you can use ===.
In otherword
== is used to compare the values only.
=== is used to compare the values as well as type.
Check like this
if(password === "cat")
And for your another query if you want to make a web app or something. You should use server side interaction using PHP or WPF or any other like JSON etc.
This question has been asked by many before. The code needs to use an Ajax request to the server.
Also , you do need a server side language to do the validation . Something like below, example is using Jquery library
HTML
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
PHP code
<?php
session_start();
$username = $_POST['name'];
$password = md5($_POST['pwd']);
$mysqli=mysqli_connect('localhost','username','password','database');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
This is really the wrong way to implement login. Any password checking has to happen on the server, because otherwise the password will be visible on the client, and it will be trivial for users to see the required password. Furthermore, please, please, please, please do not create yet another username/password login... this is what OAuth2 is intended to solve; let the identity experts handle login, and simply delegate to another identity provider.
That being said, the error in your code is that you use a single equals sign ("=") which performs assignment, whereas you really intend to use the double equals ("==") or triple equals ("===") for comparison.

Categories

Resources