Showing PHP variable in Javascript - Security point - javascript

Originally I had the following structure:
index.html file:
...
<script src="myfunctions.js" />
...
myfunctions.js file:
...
function one() {
....
}
function two() {
....
}
function three() {
....
}
That way I got over 2 500 lines of Javascirpt written but then I had to add a PHP variable to a function so I had to rename index.html to index.php, rename myfunctions.js to myfunctions.js.php and do the following changes:
index.php file:
...
<?php
include("myfunctions.js.php");
?>
...
myfunctions.js.php file:
<script>
...
function one() {
....
}
function two() {
....
}
function three() {
....
}
function four() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
</script>
I have achieved my purpose of using PHP variable in JavaScript but I have noticed that the web page in the browser started to show all the included function, i.e. if in the first case when I was looking at the page with a debug tool or by saving that page on a disk I saw just some little JavaScript code contained in index.html but now looking at or saving the index.php file I see all the functions from myfunctions.js.php visible. Of course the visible content didn't change but the actual output got 2 500 lines longer. Would that be a security problem? Should I avoid this way of showing a PHP variable in JavaScript or I shouldn't be concern about it and leave it how it is?
My concern is that in the second case all my functions gets open so a malicious user can see all the server-side PHP scripts names and required parameters which gives more ways to attack.

The PHP code is processed on the server so all anyone will see if the output of that PHP. So your PHP code is still hidden.
If you're seeing PHP code in your HTML output then either your server is configured incorrectly or you have a syntax error which echo's out what you intend for the parser to process.

Using index.php is fine but you don't really want to do a PHP include of a JS file like that.
The simplest way to go about it is to include the JS file like you were doing
<script src="myfunctions.js" />
and then add a small amount of Javascript to the PHP file which outputs the user_id.
function userId() {
return <?php echo $_conf['user_id'];?>
}
Then function four can access it like
function four() {
console.log(userId());
}
Ideally you will want your functions as part of an Object or module.
Another approach would be for function four to query the server for the user_id and then cache it in some way.

Careful you aren't introducing a XSS vulerability. If $_conf['user_id'] is an integer then you should be fine, but be careful of mixing client side and server side script like this. #Paul S's comment is the way to go.
See here for more tips https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Related

How To Pass Arguments to Javascript File From PHP Exec

After a form is submitted from my php file it checks it, and then is supposed to call an exec function that will execute a binary file using the second file listed in the code. Shown below:
if (isset($_POST['admin']) && !empty($_POST['admin'])) {
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js');
}
The problem here is that the preceding javascript file bigdaddy.js has to take three arguments of its own in order to function. To solve this issue, I tried the following:
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js' $_POST['admin'] $_POST['user'] $_POST['password']);
This bricked my site.
Does anybody have any ideas how this may be done? All of the possible solutions I have found detail PHP to PHP, NOT PHP to Javascript. Thanks all!
you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Calling PHP function nl2br in html doc

I am working on a site in which I have a user entry field that I would like to insert line breaks after every new line in the user input without making an entirely new php page. Here's my code (js):
var newstreamSummary = document.getElementById("addNewstreamSummaryBox").value;
if(newstreamSummary !== ""){
document.getElementById("previewNewstreamSummary").innerHTML = newstreamSummary;
/* newstreamSummary = <?php echo nl2br(newstreamSummary);?> */
}
That block lives in a js function called showPreview(), when running it says the showPreview() is not defined. It also does not work when I put the php call in a separate <script> tag. I would like to call this function without having a new page as this is the only time in the project where I'm using php currently. Or if there's a js function that does the same thing. Thanks all for any advice.
Php is server side. The only way of using php in that case would be making an Ajax call
to a php script which processes your test and returns this text processed.
There is no need for that in your case. Just add this line after your if statement:
newStringSummay = newStringSummay.replace(/\n/g, "<br>");

How to access a PHP array from JS "in another file"?

I have seen this answer (and a couple others as well) and it provides an understandable way of accessing a PHP array. But in the example, the PHP and the JavaScript are in the same file.
However, I can not write Javascript in my PHP file for some reasons, and what I am rather doing is invoking the JS present in another file. So I need to access an array from the PHP in the JS file. How can I do that?
I prefer it without AJAX (if possible) because I have not yet started learning AJAX.
You could use a JSONP approach:
Make your PHP file output your data wrapped in a function call - something like this:
callback(
['your', 'data', 'here']
);
To do this with a PHP variable you can do this:
callback(<?php echo json_encode($data) ?>);
Then in your JavaScript file do this:
function callback(data) {
alert( data.join(' ') ); // will alert 'your data here'
}
In your HTML file just include the above JS file and afterwards include another script tag that points to your php file:
<script src="/path/to/local.js"></script>
<script src="http://yourserver.com/path/to/server.php"></script>
The browser will grab the first file, and evaluate the function declaration. Then it will grab the second file, and see that it is a function invocation and immediately execute your function with the data as the argument.
A quick and dirty solution would be to make your JavaScript file a PHP file and pass all the variables you need when including the script:
<script type="text/javascript" language="javascript" src="./script.php?var=<?php print(json_encode($var)); ?>"></script>
In the JavaScript file you can use the PHP variables like so:
var a=JSON.parse(<?php print($_REQUEST['var']); ?>);

Using javascript variable in PHP with ajax [duplicate]

This question already has answers here:
Passing Javascript Variable to PHP using Ajax
(2 answers)
Closed 8 years ago.
I am thinking to use Speedof.me api to find out the user download speed accurately.I will use the value of the download speed to determine which video quality will be used to stream video to the user.
<html>
<head>
<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
</head>
<body>
<h2>SpeedOf.Me API Consumer - Sample Page</h2>
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speed = testResult.download;
}
</script>
<?php
//how can i use the speed variable here
}
?>
</body>
</html>
I am a begineer with javascript and i would like to use the javascript variable in the php as shown above without reloading the page.I know that javascript is executed client-side and php is server-side but from what i read online is that ajax is the way to go.Also is there a way in which i can store the result of speedof.me so that i don't need to run the test every time the same user view a video
Thanks for helping me out guys
you can make an ajax call to server to use the javascript variable in php
function onTestCompleted(testResult) {
var speed = testResult.download;
$.ajax({
url:"link to php script" // e.g test/index.php
type:"POST", //method to send data
dataType:"json", //expected data from server
data:{speed:speed}, //data to send server
success:function(data){
alert(data); //alert response data after ajax call success
}
});
}
on php script you can use that javascript variable speed after checking $_POST[]
echo $_POST['speed'];
passing PHP values to javascript can just be echoed. But javascript to PHP is a bit complicated.
Server scripts like PHP are executed first before Browser scripts (i.e. javascript) do their job. this means, after the page has loaded, your php won't do any good anymore, EXCEPT, you use Ajax requests.
what I use is jquery function .post() (if you're wondering why i use post, you can do your own reading about this functions including .ajax() and .get() )
PHP code somewhere found in /project/execute.php
$speed = $_POST["speed"];
echo $speed * 5;
and in your javascript...
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speedresult = testResult.download;
// here's the magic
$.post("/project/execute.php", {speed:speedresult}, function(result) {
alert(result);
} )
}
PS. DON'T FORGET TO IMPORT JQUERY IN YOUR SECTION OR THE BOTTOM MOST PART OF THE BODY
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
You do not seem to understand the fundamental differences between Clientside and Serverside Code.
The PHP Code will be executed serverside; only the output is sent to the browser. Then the browser executes the Javascript.
One solution to your problem would be to load the video dynamically with Javascript (either per Ajax or a simple video link naming convention). To store the speed test results, use a Cookie.
It doesn't work that way. As you said, JavaScript is client side. Your PHP page is processed by the server first--meaning, all PHP code gets executed first before any of your HTML, CSS, and JS. It doesn't matter if your JS is positioned first before PHP since PHP will get evaluated first. After that, it's sent back to the client for the browser to process HTML, CSS, and JS.
For your case, after running the speed test, send the value back to a PHP script via AJAX. You can use jQuery to make AJAX calls easier. Store a cookie using JS to indicate that the test has been executed once. You'll need to modify your JS so that it will check if this cookie is present and skip the speed test.
try this :-
<?php
echo "<script>alert(speed)</script>";
?>

Javascript: How to test JSONP on localhost

Here is the way I test JSONP: I run XAMPP, and in folder htdocs I create a javascript folder . I create json1.json file contain some data to process.
After that, I run this html file locally, and it will call a function in "other machine" (in this case is localhost)
Here is my code in this problem :
<head>
<script>
function updateSales(sales) {
alert('test jsonp');
// real code here
}
</script>
</head>
<body>
<h1>JSONP Example</h1>
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
</body>
But when I run, nothing happen. But if change to other real json on the internet, it will work. It means change line :
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
to line:
<script src="http://gumball.wickedlysmart.com/?callback=updateSales"></script>
It will work smoothly.
So, I don't know how to test JSONP by using localhost, please help me.
Thanks :)
JSONP is generated on the server's side. The server fetches your data, encodes it as JSON and then wrap a function call around it.
So in your case you can either modify your .json file the following way:
updateSales( { /* your data */ } );
This, however, would have a hardcoded call back method, so it wont react on changes you do at retrieving it.
The other way is to write a small PHP wrapper (or use whatever else you like) and add the function around the JSON, before sending it back to the client.
<?php
$json = file( "path/to/your/json" );
echo $_GET['callback'], '(', implode( '', $json ), ');';
?>
(The later code is by no means for any productive use, but only for local testing!)

Categories