fingerprintjs2 to php variable - javascript

I like to get fingerprint as php variable, I get the follow but do not want to work.
<p>fingerprint2: <strong id="fp2"></strong></p>
<script src="/fingerprintjs2/fingerprint2.js"></script>
<script>
var fp2 = new Fingerprint2();
fp2.get(function(result) {
console.log(result);
$("#fp2").text(result);
});
</script>
$myphpvar = "<script>document.write(fp2.get());</script>";
echo $myphpvar;

That's really not how PHP works at all. PHP cannot process client side JavaScript. If you want access to client side information in PHP then you should probably put it in a form and post it to another page in PHP. There are many good tutorials on PHP forms, such as this one.

The Javascript is run after the PHP has completed. Client side VS server side code. I have solved this in the past by running the PHP within a PHP file that renders an image. This method is often referred to pixel tracking.
Here are the basics, you need to pass your variables in Javascript to a PHP file that renders an image:
document.write("<img src=fingerprint.php?x="+x+"&y="+y+" width=1 height=1>");
In the above case it passed Javascript variables x and y to the PHP image.
Then the fingerprint.php script looks like:
<?php
header("Content-type: image/png");
session_start();
$x = $_REQUEST['x'];
$y = $_REQUEST['y'];
$_SESSION['x'] = $x;
$_SESSION['y'] = $y
// SHOW THE IMAGE
$im = imagecreatefrompng("fingerprint.png");
imagepng($im);
imagedestroy($im);
?>
The png image can be anything you want as it will just be a 1 x 1 image on your final screen. You now have the Javascript variables in your PHP. As the code starts a session you could write the variables to a session and collect them later in another script, or write them to a database and recover later. Try with my simple example to ensure you have it working then expand from there.

There are lots of ways you can send data from JavaScript back serverside
set a cookie and read it in the next request
request further content by injecting a script / IMG / iframe tag (but not using document.write) adding the fingerprint in the query of the url
make an AJAX request
add a hidden input to a form on the page - requires the user to navigate out of the page using the form

Related

PHP method calls from Javascript not showing up in Wordpress source

I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
    var dataURL = canvas.toDataURL ();
    <? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.

Print a javascript variable in php

I am selecting a payment method and making an AJAX call But I am not able to print the paymentOption parameter
I tried storing it in a cookie
if(paymentOption == "default_cod"){
processOrderWithCOD();
optionPayment = Cash;
}
document.cookie = "$payment_option = $this.optionPayment";
PHP:
<?php
$paymentOptionDisplay = $_COOKIE['payment_option'];
echo $paymentOptionDisplay ?>
I am just trying to print paymentOption but later on its value is changed so need to save it and print
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
$paymentOptionDisplay = $_COOKIE['payment_option'];
Cookies usually will not be available until the page is reloaded / refreshed, which is why you're not getting the value that you're expecting. You'd really have to do the payment calculation in PHP and store it in a $_SESSION if you're looking for it to persist like a cookie.

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

Merge JavaScript output with PHP?

I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.

Store javascript data into PHP SESSION VARIABLE?

I'm wondering if it's possible to store a number generated from a javascript script into a PHP SESSION variable. I basically want to store my code '+.res.id+' and '+.res.level+' into a PHP SESSION. Those 2 javascript codes generate a random number and inputs that number in a html form. IS there anyway I could take that number and store it in a PHP SESSION? For example
<script>
JAVASCRIPT CODING
'+res.level+'
'+res.id+' // BTW it actually does generate a number I just can't echo it in another page or store it in a SESSION
</script>
<?php
$_SESSION['.res.id.'] = $idnum;
$_SESSION['.res.level.'] = $levelnum;
?>
Then after in a seperate page I want to call that SESSION and echo the number that the code generated. But my only problem is that when I echo the $_SESSION it echo's as ".res.id." instead of the randomly generated number. How do I fix this to make it echo the random generated number?
First of all javascript is running on a client side and php is running on a server side. It means you can't just store the generated number. But there is a workaround on that. You can do that by means of AJAX request.
In your js you can do this.
var res_id = your_random_number;
var res_level = your_random_number
$.post("/any/url/that/contains/your/php/code", {res_id:res_id, res_level:res_level});
In your php.
$_SESSION["res_id"] = $_POST["res_id"];
$_SESSION["res_level"] = $_POST["res_level"];

Categories