PHP `file_get_contents()` output pass to JavaScript and calculate length - javascript

I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>

Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;

Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...

Related

placing php inside javascript

<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link = "<?php if(isset($_GET["ggg"])) {
echo $_GET["ggg"].".php?width=800&height=460";
} else {
echo "page1.php?width=800&height=460";
}
?>";
</script>
this is my script, php inside javascript. how do i place this variable strWidth inside
php?width=800&height=460
so becomes some how like this
php?width=strWidth&height=460
EDIT 2
well, the only thing i am trying to do here to show variable value between those line is it a big deal ?
it might be done by separating like using concatenation or something ?
Add an input-field in PHP, hide it (if necessary) and read the value of this field with JS.
First of all if you want to use php values in javascript you need the script to be written in a php file. Suppose you do this then you can do this in this way:
<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link='<?php echo (isset($_GET["ggg"]))?isset($_GET["ggg"]):''; ?>'; // this assigns the valueto link variable
if(link==''){
// your logic starts here
}else{
// your logic starts here
}
</script>
Add an input-field and assign a value to the hidden element and then get value through javascript.
It is not a good idea to combine PHP and Javascript.
Refer this about explanation on client-side vs server-side coding.
you can't really do that. but this works
<?php
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
if(isset($_GET["ggg"])) {
echo "var link =" . $_GET["ggg"] . ".php?width=800&height=460';\n";
}
else {
echo "var link ='page1.php?width=' + strWidth + '&height=' + strHeight + '';\n";
}
echo "</script>\n";
?>
the reference to ggg completely confuses the understanding of this process so really it should be taken out:
__ page1.php
<?php
if (!isset($_GET['foundWidth'])){
//stops double hit
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
echo "var link ='/page1.php?foundWidth=true&width=' + strWidth + '&height=' + strHeight + '';\n";
echo "window.location = link;"
echo "</script>\n";
}
elseif (isset($_GET['foundWidth']) && ($_GET['foundWidth']=='true')) {
if (isset($_GET['width']) && is_numeric($_GET['width'])){
//use your width here SERVER SIDE
// or
echo "<script> alert('Width is: '+ " . $_GET['width']) . "); </script>\n";
}
if (isset($_GET['height']) && is_numeric($_GET['height'])){
//use your height here SERVER SIDE
// or
echo "<script> alert('Height is: '+ " . $_GET['height']) . "); </script>\n";
}
}
?>
using this "trick" you can then write the PHP params into the javascript url with whatever get string you like, including triggering a reload of the page with the width as a param, so if you want to test if $_GET['width'] is set to a number you can insert it etc

PHP Variable inside PHP -> Echo -> Javascript

so I have issue I don't even know how to tell it. But here it is.
//Coupon Code?
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo '<td>
<input type="text" onKeyup="trackChange(this.value)" id="myInput">
<script type="text/javascript">
var dID = <?php echo $dID; ?>;
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open("/functions.php?cCODE="+value+"&ccID="+dID)
}
</script>
</td>';
All I need is to get "user ID" from $dID=$row['ID']; but as it seems It just echo out that to the result and don't do any job. How can I get php variable inside php -> inside Echo -> inside Javascript.
I thought by going other way but I need text box and then submit to url. But I can't seem to get it working. Only 1 request at a time and I need 2. (User ID, and text to text box response)
echo " <td><form action= functions.php?cID= method= 'post'><input
type='hidden' name='cID' value=$dID />
<input type= 'submit' name= 'type' value= Confirm></form></td>";
So I can't get them both to submit that. Only found a way inside javascript.
Picture of text field
You'll want to use string concatenation (using the . character) to insert a variable into your string. Like this:
echo '
[...]
<script type="text/javascript">
var dID = ' . $dID . ';
function wait(ms){
[...]
';
A . will concatenate two strings together. For example:
echo 'hello ' . ' world'
You can also insert a variable directly into a string, if you use double quotes. Single quotes do not allow you to do this:
$text = "world";
echo "hello $text";
In general, you should wrap your variables in curly brackets ({ and })
$text = "world";
echo "hello {$text}";
You can just concatenate the variable there
To concatenate use .
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo "<td>
<input type='text' onKeyup='trackChange(this.value)' id='myInput'>
<script type='text/javascript'>
var dID = '".$dID."'
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open('/functions.php?cCODE='+value+'&ccID='+dID)
}
</script>
</td>";

Inserting value in a JavaScript variable from php code

I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?

Storing a value of a variable in a text file

I have created a simple mechanism to grab a persons First and Last name (this is of course the very basic code). However I want to write the value of a variable to a text file. I have used some php, however it does not seem to work:
<?php $handle = fopen("log.txt", "a");
foreach($_GET as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
Therefore, I was wondering if there was any of code I could use to place this information into the text file? Your help is appreciated.
Initial code:
<head>
<script>
function getDetails()
{
var firstName = document.getElementById("firstName");
var nameElement = document.getElementById("lastName");
var theName = firstName.value;
var theLastName = lastName.value;
document.getElementById("someDiv").innerHTML += theName += theLastName;
}
</script>
</head>
<html>
<div id="someDiv">
Details:
</div>
<br><br>
<input id="firstName" type="text">
<input id="lastName" type="text">
<input type="button" value="Go!" onClick="getDetails();">
<br>
</html>
I would however prefer Javascript.
To write on a file via php, you can use the file_put_content() function.
Here's a simple code example:
// The file where to write
$file = 'db.txt';
// The content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content);
You can also append content to the file:
// The file where to write
$file = 'db.txt';
// Old content
$file_content = file_get_contents($file);
// Old + new content
$file_content .= $your_variable;
// Write the content
file_put_contents($file, $file_content);
You can also append to a file file_put_contents flags:
// The file where to write
$file = 'db.txt';
// New content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content, FILE_APPEND | LOCK_EX);
// FILE_APPEND: used to append the new contents at the end of the file
// LOCK_EX : used to avoid another user to write on the same file at the same time

Notice: Undefined variable: output in ser.php on line 24

Notice: Undefined variable: output in C:\xampp\htdocs\tests\ser.php on line 24
i got this problem i don't know why this show ! try everything
any fix !?
this is my code php
the idea of code live search like google
<?php
require_once("conf.php");
if(isset($_POST['SearchValue'])){
$se=$_POST['SearchValue'];
$s=preg_replace("#[^0-9a-z]#i","",$se);
$query=mysql_query("SELECT * FROM search WHERE P_A LIKE '%$s%'");
$connect=mysql_num_rows($query);
if ($connect == 0){
$output="no reset";
}
else {
while ($row = mysql_fetch_array($query)){
$pA = $row ['P_A'];
$pB = $row ['P_B'];
$pC = $row ['P_C'];
$pD = $row ['P_D'];
}
$output .= '<div>' . "" . $pA . "" . $pB . "" . $pC . "" . $pD . '</div>' ;
}
}
echo ($output);
?>
and this is my html code
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function mysearch(){
var sText =$("input [name='Search']").val();
$.post("ser.php",{SearchValue:sText},function(output){
$("#output").html(output);
}
);
};
</script>
</head>
<body>
<form action="#" method="post">
<input type="text" name="Search" onkeydown="mysearch();" />
<input type="submit" value="search" />
</form>
<div id="output" >
</body>
</html>
Yes, you have not defined $output variable first and joining it like $output .= ....
So, use this at the top of your code:
$output = '';
if $_POST['SearchValue'] is not set the variable $output is never defined. That's the error you see.
Also in your jquery code there is an error finding your text. Change:
var sText =$("input [name='Search']").val();
To:
var sText =$("input[name='Search']").val();
In the first one you are searching an item with name 'Search' inside an input. In my code you search an input with the atribute name = 'Search'

Categories