Why i'm getting error: "SyntaxError: Unexpected token <"? - javascript

This is the code i'm using:
<?php
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($"http://newsxpressmedia.com/files/radar-simulation-files")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
$files[] = $file;
$curimage++;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
#Timer_Countdown{
background:black;
color:yellow;
font-weight:bold;
text-align:center;
}
</style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
var images = <?=json_encode($files)?>;
//var images = [];
var x = -1;
var swap_hours = 0;
var swap_minutes = 0;
var swap_seconds = 5;
var down_counter_hours;
var down_counter_minutes;
var down_counter_seconds;
function initTimer() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
counter = setInterval(switcher, 1000);
}
function restartCounter() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
}
function switcher() {
down_counter_seconds--;
if (down_counter_hours <= 0 && down_counter_minutes <= 0 && down_counter_seconds <= 0) {
swapColor();
restartCounter();
}
if (down_counter_seconds <= 0 && down_counter_minutes > 0) {
down_counter_seconds = 60;
down_counter_minutes--;
}
if (down_counter_minutes <= 0 && down_counter_hours > 0) {
down_counter_minutes = 60;
down_counter_hours--;
}
document.getElementById("Timer_Countdown").innerText = down_counter_hours+":"+down_counter_minutes+":"+down_counter_seconds;
}
function swapColor() {
displayNextImage();
}
</script>
<div id="div_hours" class="div_box"></div>
<div id="div_minutes" class="div_box"></div>
<div id="div_seconds" class="div_box"></div>
<div id="div_switcher" class="div_box"></div>
</head>
<body onload = "initTimer()">
<div id="Timer_Countdown"> </div>
<img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
<button onclick="displayPreviousImage(); restartCounter()">Previous</button>
<button onclick="displayNextImage(); restartCounter()">Next</button>
</body>
</html>
The error is on the line:
var images = <?=json_encode($files)?>;
If i change this line to this line:
var images = [];
Then the code is working fine but without using the php files variable.
Something is wrong with the line: var images = <?=json_encode($files)?>;
I tried to change this line to: echo json_encode($images); or to var images = echo json_encode($files); but same error.
I'm using weebly to build my site and my site server is on ipage.com
How can i fix the error ?

It looks like you don't have short tags enabled(and are using a pre 5.4 php version), thus the line <?=json_encode($files)?> is not parsed by php and is just send straight through. var images = <... is not a valid javascript expression. Here's some information about php's short_open_tag parameter: http://php.net/manual/en/ini.core.php#ini.short-open-tag

A couple of changes. Change
$pattern ="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)";
to
$pattern = '/\.(png|jpg|jpeg|gif)$/i';
and
eregi($pattern, $file)
to
preg_match($pattern, $file)
and see what happens. eregi deprecated as PHP 5.3.0.

You are using '=' inside the PHP tags. Try this:
var images = <?json_encode($files)?>;

Related

JS image pixels change

I have a problem. I am currently working on an project that changes image pixels. I am doing it as a web app using javascript. The problem is that when I change them using getImageData and then downloads the picture with toDataURL and link download it works. But when I then upload the image and read data with getInamgeData some of the pixels change.
Where can be the problem and how can I fix it.
const original_canvas = document.getElementById('original_canvas');
const edited_canvas = document.getElementById('edited_canvas');
const orig_ctx = original_canvas.getContext('2d');
const edit_ctx = edited_canvas.getContext('2d');
var start = document.getElementById("start");
var textfield = document.getElementById("textField");
var message = "";
var download = document.getElementById("download");
var loadFile = function(event){ //
var uploaded_image = new Image();
uploaded_image.src = URL.createObjectURL(event.target.files[0]); //
uploaded_image.onload = function (){ //resizes canvas and image after its loaded
//original_canvas.width = 400;
//original_canvas.height = uploaded_image.height/(uploaded_image.width/400);
//orig_ctx.drawImage(uploaded_image,0,0,original_canvas.width,original_canvas.height); //draws resized image into canvas
//toto rozostruje obrazok
original_canvas.width = uploaded_image.width;
original_canvas.height = uploaded_image.height;
orig_ctx.drawImage(uploaded_image,0,0);
};
};
function toBinary(input){ //converts text to binary
var output = "5";
for(i = 0; i < input.length; i++){
output += input[i].charCodeAt(0).toString(2) + "2"; //first to ASCI code then to binary
}
output += "5";
return output
}
function toText(input){ //converts binary to text
var output = "";
var binary = "";
for(i = 0; i < input.length; i++){
if(input[i] == "2"){ //divides string by spaces
asci = parseInt(binary, 2); //binary to ASCI code
output += String.fromCharCode(asci); //ASCI code to char
console.log(asci);
binary = "";
}
else{
binary += input[i];
}
}
return output;
}
function closest_point(number, change){ //finds number ending in 1 or 0 and changes it to it
var result = 0; //this should help reduce the vissible changes
function up(){
result = (((number-number%10)/10)+1)*10+change;
return result;
}
function down(){
result = number-number%10+change;
return result;
}
if(Math.abs(number-up()) < Math.abs(number-down()) && up()<255){
return up();
}
else{
return down();
}
}
function encode(){
message = toBinary(textfield.value);
console.log(message);
let imgData = orig_ctx.getImageData(0, 0, original_canvas.width,original_canvas.height);
if(message.length > imgData.data.length){
alert("Message is too big.");
}
else{
for (i = 0; i < imgData.data.length; i += 4){
if(i >= message.length){
break;
}
else{
imgData.data[i] = closest_point(imgData.data[i],Number(message[i]));
imgData.data[i+1] = closest_point(imgData.data[i+1],Number(message[i+1]));
imgData.data[i+2] = closest_point(imgData.data[i+2],Number(message[i+2]));
imgData.data[i+3] = closest_point(imgData.data[i+3],Number(message[i+3]));
}
}
console.log(imgData);
edited_canvas.width = imgData.width;
edited_canvas.height = imgData.height;
edit_ctx.putImageData(imgData, 0, 0);
var jpg = edited_canvas.toDataURL('image/png', 1.0);
console.log(jpg);
download.href = jpg;
}
}
function decode(){
message="";
counter = 0;
let imgData = orig_ctx.getImageData(0, 0, original_canvas.width,original_canvas.height);
console.log(imgData);
for(i=0; i < imgData.data.length;i+=4){
if(imgData.data[i]%10 == 5){
counter += 1;
}
if(counter == 1){
message += (imgData.data[i]%10).toString();
message += (imgData.data[i+1]%10).toString();
message += (imgData.data[i+2]%10).toString();
message += (imgData.data[i+3]%10).toString();
}
if(counter == 2){
message = message.substring(1);
if(message.includes("5")==true){
message = message.substring(0,message.indexOf('5'));
}
console.log(message);
break;
}
}
console.log(toText(message));
}
function main(){
encode_check = document.getElementById("encode_check");
decode_check = document.getElementById("decode_check");
if(decode_check.checked == true){
decode();
}
else{
if(encode_check.checked == true){
encode();
}
else{
alert("Fill everyhing");
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Steganography</title>
</head>
<body>
<div style="position:relative; left:50px; top:10px;">
<input type="text" id="textField" placeholder="O polnoci na vrsku">
<button id="start" onclick="main()">Start</button>
<a href="" id="download" download>Download</a>
<input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)">
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="decode_check">
<label class="form-check-label" for="flexRadioDefault1">
Decode
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="encode_check">
<label class="form-check-label" for="flexRadioDefault2">
Encode
</label>
</div>
</div>
<canvas id="original_canvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
<canvas id="edited_canvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
</body>
</html>
I managed to fix it. The problem was that the pixels changed only when the forth value changed- the alpha channel. I suppose it is caused by gamma correction of the web browser.

ERROR Synchronous XMLHttpRequest on the main thread is deprecated

I am attempting to load a graph with options to show data between select dates. When I run it on my webpage, I get an error "Table has no columns." 1, but when i set the IF statement (buildchris) to NOT EQUAL to maincampus, the chart will load. I believe it has something to do with the xmlhttp .send, the variables seem to not be sending over POST (buildingchartchris). Does anyone have a solution to this problem?
buildchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$p = $_POST['purpose'];
if($p == "maincampus")
{
$sm = $_POST['sm'];
$sd = $_POST['sd'];
$sy = $_POST['sy'];
$em = $_POST['em'];
$ed = $_POST['ed'];
$ey = $_POST['ey'];
//$start_date = Date("Y-m-d", mktime(0, 0, 0, $sm, $sd, $sy));
//$end_date = Date("Y-m-d", mktime(0, 0, 0, $em, $ed, $ey));
$start_date= "2014-01-01";
$end_date= "2016-01-01";
$result = $dbc->query('SELECT SUM(actual_hours) as act_hours, Buildings.bld_name, Buildings.bld_location FROM work_orders INNER JOIN Buildings ON work_orders.building = Buildings.bld_no WHERE work_orders.actual_completion_date > "'.$start_date.'" AND work_orders.actual_completion_date < "'.$end_date.'" AND Buildings.bld_location ="0" AND Buildings.bld_name <> "N/A" AND work_orders.actual_completion_date IS NOT NULL GROUP BY Buildings.bld_name');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Building', 'type' => 'string'),
array('label' => 'Hours', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['bld_name']);
// Values of the each slice
$temp[] = array('v' => (int) $r['act_hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
}
?>
buildingchartchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$page_title = 'Dashboard';
include ('includes/header.html');
?>
<html>
<head>
<title>Dashboard</title>
<link rel="icon" href="images/NKU.png" type="image/png" sizes="16x16">
<link rel="stylesheet" href="includes/as.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js?libraries=geometry"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script>
<!--
//hides or shows the table given by nm
function hide_table(nm)
{
// alert(is_fullscreen);
var table_selector = "#table_" + nm;
$(table_selector).toggle();
//table_width = (table_width == 24)? 35:24;
//$("#iframeholder").animate({width: table_width + "%"});
}
// -->
</script> </head>
<div id="content">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Set a callback to run when the Google Visualization API is loaded.
// google.setOnLoadCallback(drawChart);
function drawChart() {
var maincamp_sm, maincamp_sd, maincamp_sy, maincamp_em, maincamp_ed, maincamp_ey;
if( document.getElementById("maincamp_dates_quarter").checked )
{
var maincamp_q = document.getElementById("maincamp_quarter").value;
maincamp_ey = Number(document.getElementById("maincamp_quarter_year").value);
maincamp_sy = maincamp_ey;
if( maincamp_q == 0 )
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
}
else if( maincamp_q == 1)
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 9;
maincamp_ed = 30;
}
else if( maincamp_q == 2 )
{
maincamp_sm = 10;
maincamp_sd = 1;
maincamp_em = 12;
maincamp_ed = 31;
}
else if( maincamp_q == 3 )
{
maincamp_sm = 1;
maincamp_sd = 1;
maincamp_em = 3;
maincamp_ed = 31;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
else if( maincamp_q == 4 )
{
maincamp_sm = 4;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
}
else
{
maincamp_sm = document.getElementById("maincamp_start_month").value;
maincamp_sd = document.getElementById("maincamp_start_day").value;
maincamp_sy = document.getElementById("maincamp_start_year").value;
maincamp_em = document.getElementById("maincamp_end_month").value;
maincamp_ed = document.getElementById("maincamp_end_day").value;
maincamp_ey = document.getElementById("maincamp_end_year").value;
}
if(!( (maincamp_ey < maincamp_sy) || ( (maincamp_em < maincamp_sm) && (maincamp_ey == maincamp_sy) ) || ( (maincamp_ed < maincamp_sd) && (maincamp_em == maincamp_sm) && (maincamp_ey == maincamp_sy) ) ))
{
var xmlhttp;
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()//Function called when there is a change of state for the server
{ //request
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)//when request is complete and no issues
{
//var str = xmlhttp.responseText;
var jsonData = $.ajax({
url: "buildchris.php",
type: "POST",
dataType: "json", // type of data we're expecting from server
async: false // make true to avoid waiting for the request to be complete
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData.responseText);
var options = {
title: 'Labor Hours for Main Campus',
is3D: 'true',
width: 1200,
height: 2000,
chartArea:{width:"40%"},
bar: {groupWidth: "50%"}
};
var maincamp_view = new google.visualization.DataView(data);
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(maincamp_view, options);
}
};
xmlhttp.open("POST","buildchris.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("purpose=maincampus&sm=" + maincamp_sm + "&sd=" + maincamp_sd + "&sy=" + maincamp_sy + "&em=" + maincamp_em + "&ed=" + maincamp_ed + "&ey=" + maincamp_ey);
}
else
{
alert("Your end date cannot be before the start date.");
}
}
google.load('visualization', '1', {'packages':['corechart']});
function cursor_hand(x)
{
x.style.cursor = "pointer";
}
function cursor_default(x)
{
x.style.cursor = "default";
}
function hide_element(nm)
{
var table_selector = "#" + nm;
$(nm).toggle();
}
</script>
<body>
<p onclick = "hide_element(operational_effectiveness_div);" style = "text-decoration: underline; font-size:x-large; font-weight:bold;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Operational Effectiveness Reports</p><br>
<div id = "operational_effectiveness_div" >
<p onclick = "hide_element(maincamp_div);" style = "text-indent: 15px; text-decoration: underline;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Show Total Labor Hours for Main Campus 2015-16</p><br>
<div id = "maincamp_div" style = "display:table;">
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_quarter" name = "maincamp_dates" value = "1" checked> Report by quarter </legend>
<p><select id = "maincamp_quarter">
<option value = 0 selected>All Quarters</option>
<option value = 1>Q1</option>
<option value = 2>Q2</option>
<option value = 3>Q3</option>
<option value = 4>Q4</option>
</select>
<input type = "number" id = "maincamp_quarter_year" min = "2015" value = "2015"></p>
</fieldset><br>
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_range" name = "maincamp_dates" value = "2"> Custom date range </legend>
<p>Start date (mm-dd-yyyy): <input type = "number" id = "maincamp_start_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_start_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_start_year" min = "2015" value = "2015"></p>
<p>End date (mm-dd-yyyy): <input type = "number" id = "maincamp_end_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_end_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_end_year" min = "2015" value = "2016"></p>
</fieldset>
<br>
<p onclick = "drawChart()" style = "border: thin solid black; padding: 2px; width: 95px; margin-left: 550px;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Generate report</p>
<div id="chart_div" style="width: 1000px; text-indent: 50px;"></div>
</div>
</div>
</body>
</html>
<?php
//Release the used resources
mysqli_close($dbc);
include ('includes/footer.html');
?>

Ordered list with random numbers between 1 and 49

I have some problems to Code an simple PHP ordered list that print out a random number list between 1 and 49.
The Main Code
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>AJAX</title>
<meta name="viewport" content=
"width=device-width; initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="lib/css/stil.css" />
<script type="text/javascript"
src="lib/js/script.js"></script>
</head>
<body>
<h1>Ziehung der Lottozahlen</h1>
<button id="frage">Starte die Ziehung</button>
<div id="antwort">
</div>
</body>
</html>
Here the external PHP Code to randomize the numbers
<?php
$zahlen = range (1, 49);
shuffle($zahlen);
for ($i = 0; $i < 6; $i++) {
echo $zahlen[$i] . " ";
}
?>
And here the Java script
var resOb = new XMLHttpRequest();
window.onload = function() {
document.getElementById("frage").onclick =
function () {
resOb.open('get', 'lottozahlen1.php', true);
resOb.onreadystatechange = function () {
if (resOb.readyState == 4) {
document.getElementById("antwort").innerHTML =
resOb.responseText;
}
};
resOb.send(null);
};
};
T
Now my question...how i can let Show the numbers in a ordered list?
use PHP code below way
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
You could split the string, map the values as number and sort the array. Then generate the wanted list items and put it to the wanted unordered list.
var lotto = '22 34 14 10 99',
list = lotto
.split(' ')
// .map(Number)
// .sort(function (a, b) {
// return a - b;
// })
.reduce(function (list, a) {
var li = document.createElement('li');
li.innerHTML = a;
list.appendChild(li);
return list;
}, document.createElement('ol'));
document.body.appendChild(list);
Extending Kool-Mind's answer:
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
Try adding the code below(to generate the list):
<script>
$('#button').click(function(){
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
})
</script>
Hope it helps =)
EDIT
This should be working fine now, hope it helps =)
<button id="button">Button</button>
<div id="newDiv"></div>
<script>
var clicked = false;
$('#button').click(function(){
if (!clicked){
<?php
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] = rand(1,49);
}
sort($arr,1);
?>
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
clicked = true;
}
})
</script>

Fetch data from excel sheet using Javascript

I am using following code to extract data from excel sheet using javascript. This is working good and after opening the HTML page, getting the data that I want and closing the page, I am unable to open and edit the excel sheet as it is throwing the exception, "File already held by the user and unable to be edited". Is there anyway to handle the closing of excel sheet at the end of the code? Please help me.
<!DOCTYPE html>
<html>
<body>
Enter Salomon account:<br>
<input type="text" id="myText" name="SalAccount">
<br>
<button onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script language="javascript" >
function myFunction()
{
alert("hello");
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:/Users/bv15457/Desktop/test1.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var x = document.getElementById("myText").value;
var lo = 1;
var hi = 682220;
var mid;
var element;
var Flag = 0;
while(lo <= hi && Flag != 1)
{
mid = Math.floor((lo + hi) / 2, 10);
element = excel_sheet.Cells(mid,1).Value;
if (element < x)
{
lo = mid + 1;
}
else if (element > x)
{
hi = mid - 1;
}
else
{
document.getElementById("demo").innerHTML = excel_sheet.Cells(mid,2).Value;
Flag = 1;
}
}
if (Flag != 1)
{
alert("Account is not found in XREF file");
}
}
</script>
</body>
</html>

PHP post variable is not being rendered

I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>

Categories

Resources