Note: With plain PHP scripting, it is not possible to access JS vars.
Interesting requirement. Below goes a solution. Lets consider the case if the variable name is passed in the URL. Let the page name be 'index.php'. The browsing URL looks like this localhost/index.php?varName=variableA, where varName is the query param which takes variable name as value. We can pass comma separated values also by tweaking the code a bit. But that is not considered now.
Outlining the steps below
- Get contents of url.php and place it in a hidden div of index.php
- Beneath the captured content, call an Ajax function with var name & var value as param.
- Inside the ajax page, save the name / value to some DB or file.
After the ajax call there is some more DOM where we will print the name / value & remove the record from DB or File after displaying the same.
NB: The main code is in JS - See getVarWithValue(variable) function.
<html>
<body>
<?php
$varName = (isset($_GET['varName']) && trim($_GET['varName']) != "") ? $_GET['varName'] : 'variableA';
?>
<div style="display:none">
<?php
$html = file_get_contents('./url.php');
echo $html;
?>
<script>
//THIS IS THE CORE FUNCTION WHICH GETS THE VAR NAME & VALUE
function getVarWithValue(variable) {
var param = '';
for (var name in this) {
keyValue = [];
if (variable == name ) return param += name+'='+JSON.stringify(eval(name));
}
return false;
}
var http = new XMLHttpRequest();
http.open("POST", "setVariableValue.php", false); // 3rd argument makes sure that the call is NOT async.
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.getElementById("varValue").innerHTML = http.responseText.toString();
}
};
http.send(getVarWithValue( '<?php echo $varName ?>' ));
</script>
</div>
<?php
//$varValue = getValuefromDB(); Get the saved value from DB or file
echo "The variable value of $varName is: ".$varValue;
// Write code to remove the row from DB or file
?>
</body>
url.php (Page from which we need to capture the variable name & value)
<html>
<head>
<script>
var variableA = { name: "A" };
variableA.id = 1;
var variableB = ["Stack", "Overflow"]
</script>
</head>
<body>
Some Text
</body>
</html>
setVariableValue.php
<?php
/**
* Write code for saving var name & value to DB or file
*/