HTML Escaping/Encoding in Javascript/PHP - javascript

I have multiple pages of html code saved into a database. I want a file to be able to flip through each of these pages without reloading.
I created a PHP file to pull all the pages into a database.
The page shows the first page and navigation buttons.
There is also javascript to put all the other pages into an array so I can quickly switch pages.
var pages = new Array();
<?php foreach ($coursePages as $page): ?>
pages[pageCount] = "<?php echo ($page['body']) ?>";
pageCount++;
<?php endforeach ?>
My problem is creating the javascript array. How can I escape the data from the echo properly so it can eventually change the page content using the following:
$(document).ready(function() {
$('.navNext, .navPrevious').click(function({
if ($(this).hasClass('navNext')) {
page++;
if (page > pageCount) {
page = 0;
}
} else {
page--;
if (page < 0) {
page = 0;
}
}
$('.page').html(pages[page]);
}))
});

Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). It will always produce valid JavaScript and handle all data types. Example:
<script>
var a = <?php echo json_encode($var)?>;
</script>

you can use this function to escape js values:
function js_escape_string($str)
{
$str = str_replace("\\", "\\\\", strval($str));
$str = str_replace("'", "\\'", $str);
$str = str_replace("\r", "\\r", $str);
$str = str_replace("\n", "\\n", $str);
$str = str_replace("\t", "\\t", $str);
$str = str_replace("</script>", "</'+'script>", $str);
return $str;
}
NOTE: use single quote ' around JS values, like:
<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Related

preg_match not Working php and java script

I need to extract a value (id value) from html web page .
this value is included in JavaScript code.
my scraper php >
<?php
if (isset($_POST['submit']))
{
$handle = fopen($_POST['website_url'], "r");
if ($handle)
{
while (!feof($handle))
{
$text .= fread($handle, 128);
}
fclose($handle);
}
$result = preg_match('(?<=id: ")(.*)(?=",)', $text);
echo $result;
}
?>
My javaScript Code is >
<script type="text/JavaScript">
var geoInstance = gioFinder("geo");
geoInstance.setup({
id: "126568949", // i need this
geometre: "triangle",
type: "html",
image: 'https://example/126568949.jpg',
});
</script>
I need to extract id value but preg_match not working
It looks like you are missing the /s wrapping your pattern.
You will also want to set the matches array
$result = preg_match('/(?<=id: ")(.*)(?=",)/', $text, $matches);
echo $matches[0];

Can't read csv in PHP and pass it to javascript in a html file

Environment
Windows 8.1 64bit
Google Chrome
What I'm trying to do
Ultimate goal
Make a pet monitoring system using Raspberry Pi. Create a webpage where you can check streaming image of a pet and the temperature and humidity.
Current issue
Can't read csv data (temperature and humidity) using PHP and pass it to javascript in a html file.
The following gives me a blank page.
test.html
<?php
$data = array();
$fp = fopen('temphumid.csv', 'r');
$row = fgetcsv($fp); // skip the header
while ($row = fgetcsv($fp)) { $data[] = sprintf("['%d', %d, %d] ", $row[0], $row[1], $row[2]); }
$str = implode(', ' . PHP_EOL, $data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ ['day', 'avg_temp', 'avg_humid'],
<?php $str; ?>
]);
var options = { title: 'This is a test graph' };
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 80%; height: 400px;"></div>
</body>
</html>
temphumid.csv is in the same directory as test.html.
temphumid.csv
dateandtime,temp,humid
1,20.0701749938488,48.0275514992728
2,20.2401044696121,57.2354245801184
3,19.1474087424506,45.5657495890199
4,18.8319188605772,62.4405658353862
5,20.8854516366497,46.5185590247232
6,20.7459481702926,47.4137986506082
7,20.9609524855751,48.5064890268627
8,17.0936718055156,46.1276393517355
9,18.4273511669417,42.4825830307023
10,20.9669696456074,51.5502032331834
I tried a lot of things including adding echo to php clause, hard-coding a sample array in javascript, etc... in vain.
Changing the line of <?php echo $str; ?> to [0, 5, 4], [1, 9, 10], [2, 20, 23] works fine. So there's something wrong with PHP but I can't figure out what it is.
I also referred to this post.
- How to pass variables and data from PHP to JavaScript?
But this wasn't helpful.
Also, the javascript console told me the following message.
The console tells me Uncaught SyntaxError: Unexpected token <
How can I solve this issue? Thanks in advance.
update1
I added echo and ran the program in a web server in Raspberry Pi. However, I still see a blank page and Uncaught SyntaxError: Unexpected token < on console.
update2
I changed the extension to php and now it works fine. Thanks, folks!
Replace <?php $str; ?> with <?php echo $str; ?>, change the extension of your file to .php instead of .html, and everything will work well.
Maybe it's because the php file doesn't have a .php extension. Try renaming test.html in test.php.
Some similar code I wrote:
$seperator = $_POST['seperator'];
$escape = $_POST['escape'];
$default_val = $_POST['default_val'];
$files = $_FILES['filesToUpload']['name'];
$files_array = array();
//no files selected
if ($files[0] == "") {
echo "You have to select at least 1 file";
exit();
}
//preprocess by creating an array per file with it's path and name
$count = 0;
foreach ($files as $file) {
$current_file = array();
$current_file['name'] = $file;
$current_file['path'] = $_FILES['filesToUpload']['tmp_name'][$count];
$files_array[$file] = $current_file;
++$count;
}
$translation_array = array();
$languages = array();
foreach ($files_array as $file_key => $file_value) {
$text_file = file($file_value['path']);
$languages[] = $file_value['name'];
foreach ($text_file as $line_number => $line) {
$line = rtrim($line, "\n");
$line_parts = explode('=', $line);
$translation_key = $line_parts[0];
if ($file_value['name'] != 'brndportal.properties') {
$translation_array[$translation_key][$file_value['name']] = $line_parts[1];
} else {
$translation_array[$translation_key][$file_value['name']] = $line_parts[0];
}
}
}
$translation_csv = fopen("files/translation.csv", "w") or die("Unable to open file!");
//headers
$txt = "key" . $seperator;
foreach ($files as $file) {
$txt .= $file . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
//translations
foreach ($translation_array as $translation_key => $translation_arr) {
if (array_key_exists('brndportal.properties', $translation_array[$translation_key])) {
$txt = '';
$txt .= $translation_key . $seperator;
foreach ($languages as $language) {
if(array_key_exists($language, $translation_arr)) {
$translation_value = $translation_arr[$language];
}
else {
$translation_value = $default_val;
}
if (strpos($translation_value, $seperator) !== false) {
$translation_value = $escape . $translation_value . $escape;
}
$txt .= $translation_value . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
}
}
fclose($translation_csv);
It reads 1 or more CSV files and parse the lines. You can insert you own separator and stuff.
I think it would be best to read everything to arrays and serialize it to JSON, that way you can pass it to javascript with an ajax call. I'd suggest using jQuery for that part.
I had the same difficulty with Uncaught SyntaxError: Unexpected token < on the console.
The <?php echo $str; ?> solution works for certain variables. I had an array though.
So I used var myArray = <?php echo json_encode($myArray); ?> and it worked.

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

Serve Javascript with PHP: Return/Echo URL/URI

EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)

Simple PHP array to Javascript array

I have an array in php lets call it:
$nums = array(10,25,52,32,35,23);
I want to send it to my javascript function like this:
var nums=[10,25,52,32,35,23];
How can i do this?
(My javascript file name is "nums.js")
Edit:
nums.js is a javascript code. It changes the values of table in the html. But the values only exist in php. So i have to send the values to javascript.
PHP >= 5.2
The json_encode function is for this purpose:
<?php echo 'var nums=' . json_encode(array(10,25,52,32,35,23)) . ';'; ?>
Docs: http://php.net/json_encode
PHP < 5.2
If you can't use json_encode, take a look at this post for a way to define an equivalent.
As long as your javascript file is being parsed by PHP before being sent to the client, then this should work:
<?php echo "var nums=[" . implode(',', $nums) . "];"; ?>
Just json_encode() the array and then output it as an array literal in javascript.
<?php
$nums = array(10,25,52,32,35,23);
$nums_json = json_encode($nums);
?>
<script type="text/javascript">
var nums = <?php echo $nums_json; ?>;
</script>
you can also use json_encode() but only possible from php 5.2
see more: http://us3.php.net/manual/fr/function.json-encode.php
or you can use this function:
function php2js ($var) {
    if (is_array($var)) {
        $res = "[";
        $array = array();
        foreach ($var as $a_var) {
            $array[] = php2js($a_var);
        }
        return "[" . join(",", $array) . "]";
    }
    elseif (is_bool($var)) {
        return $var ? "true" : "false";
    }
    elseif (is_int($var) || is_integer($var) || is_double($var) || is_float($var)) {
        return $var;
    }
    elseif (is_string($var)) {
        return "\"" . addslashes(stripslashes($var)) . "\"";
    }
    return FALSE;
}

Categories