I have a text file storing strings. The text file will be changing every 1 minute. I want to show whole string in my php page.
My php code just fetchs the data from text file. I want my php page to refresh every minute and show the updated data.
My data.txt file is:
1~1~10,56,82,34,22,78,56,15,41,25,47,33,48~82-I am Aakash,83- I am Vijay
my php code for fetching data is:
<?php
$myFile = "data.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>
You can use stream_get_contents. Simply, stream your text file like tailing. Your client html will make ajax call every minute to your server side script written in php. For example;
PHP: file_read.php
<?php
if (isset($_GET['tail'])) {
session_start();
$handle = fopen('your_txt_file.txt', 'r');// I assume, a.txt is in the same path with file_read.php
if (isset($_SESSION['offset'])) {
$data = stream_get_contents($handle, -1, $_SESSION['offset']);// Second parameter is the size of text you will read on each request
echo nl2br($data);
} else {
fseek($handle, 0, SEEK_END);
$_SESSION['offset'] = ftell($handle);
}
exit();
}
?>
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery.min.js"></script><!-- give corrected jquery path -->
<script>
setInterval(function(){get_contents();}, 10000*60);
function get_contents() {
$.get('file_read.php.php?tail', function(data) {
$('#contents').append(data);
});
}
</script>
</head>
<body>
<div id="contents">Loading...</div>
</body>
</html>
Related
how do i get a list of all the filenames of files in C:\xampp\htdocs\dump\uploads in php varible them get the value of php varible in js
Serverside
Read the files.
$files = [];
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$files[] = $entry;
}
}
closedir($handle);
}
Render the page and echo $files in script tag. like below:
<script type="text/javascript">
const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>);
console.log('myFiles', files);
</script>
To pass a variable from PHP to JS
First you need to know that PHP is rendered on server side; However JS is executed on client side; So a way to send vars from PHP to JS is using JSON
<!-- In your file of PHP you have: -->
<!-- some code of php to generate variable of all your files... -->
<?php $files = ['dir1','file1.txt','img.jpg']; ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- here inside the same file you have your script js -->
<script type="text/javascript">
// call your variable with format JSON
var filesJSON = <?php echo "'".json_encode($files)."'"; ?>;
console.log(JSON.parse(filesJSON)); //['dir1', 'file1.txt', 'img.jpg']
</script>
</body>
</html>
I have this below code in a file named test.php, whose task is to create a JSON object and transfer it to a function in JS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
var msg = {$encodedJSON};
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');'
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
alert(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I have this piece of script, but I can only write it inside PHP - because the value the function requires, is stored in a PHP variable. All it should do is fetch the PHP's encodedJSON variable's value and store it in a local JS variable msg. Then, I created a function whose task is to POST a message, and called it next. All this worked perfectly when run in a separate HTML file, in which JS was written individually.
What should I do, to make the JS piece of code run inside PHP code? Thanks!
Given that $myjson contains the json string in php, then
var msg = {$myJSON};
to understand better above code is equivalent to:
var msg = JSON.parse('{$myJSON}')
is the way to convert it to js object from php variable.
Please see comments in the code for further help.
Please run below code and see how console.log is printing the json object:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
//started with hard coded data to show a working copy paste example
$row = array('date'=>'09-Oct-2020','txnid'=>1234,'atomid'=>456,'amount'=>21345);
if($row) {
$obj = new stdclass(); //op should add this to avoid warning
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
//to see the json encode value in php
//var_dump($myJSON);
//this is not needed in op code
//$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
//php json string is converted to js object here
var msg = {$myJSON};
//see msg object printed in console
console.log(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I want to send an ajax call to a PHP file, in which I have Javascript code to send data to SurveyJS (https://surveyjs.io/).
Calling ajaxOriginator.html using "localhost/testSurvey/ajaxOriginator.html" successfully calls receiver.php and the JavaScript in receiver.php runs but does not send out the request to SurveyJS.
If I call receiver.php directly using "localhost/testSurvey/receiver.php", it successfully sends out the request to SurveyJS and I can see the data received.
Here is ajaxOriginator.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Ajax originator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.get('receiver.php', { "name": "Julia", "car": "Kia" });
</script>
</head>
This is receiver.php
<?php
$name = $_GET["name"];
$car = $_GET["car"];
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://surveyjs.azureedge.net/1.0.16/survey.jquery.min.js"></script>
<script>
var json = {};
window.survey = new Survey.Model(json);
//To test if ajax call works and it does
var values = ["<?php echo $name; ?>", "<?php echo $car; ?>"];
//To send data directly to SurveyJS
values = ["John", "somecar"];
var deepSurveyCopy = $.extend(true, {}, survey);
console.log(deepSurveyCopy);
deepSurveyCopy.data.name = values[0];
deepSurveyCopy.data.car = values[1];
deepSurveyCopy.sendResult(my access key to surveyJS);
</script>
<?php
echo "Welcome ". $name. "<br />";
echo "You want ". $car;
?>
Here are screenshots from Chrome and SurveyJS:
I am not very well-versed in PHP and would appreciate any help in understanding how all these work (and not work) together.
Basically ajaxOriginator.html is to simulate a plugin which is going to send data out to receiver.php, in which I am trying to wrap the data received in a format SurveyJS accepts and resend to SurveyJS.
Any help is much appreciated. Thanks!
I am working on an image gallery for a client and have run across some trouble.
I don't want the client to have to change code at all so what I'm trying to do is make it so they simply have to put whatever images they want into the folder and the code will automatically add everything to the gallery.
I have come up with a few solutions so far but am stuck with what to do next.
The gallery plugin I want to use is Magnific Popup located here:
http://dimsemenov.com/plugins/magnific-popup/
The problem is that I need to pass every image url to the plugin but I can't hard code the image urls because I have no idea what they will be.
What I've tried so far is based off this guide to get the path for all of the image files using php:
https://daveismyname.com/creating-an-image-gallery-from-a-folder-of-images-automatically-bp
The main issue is that I don't know how to pass a php array of urls to a js array.
This is my php code so far:
<?php
$dirname = "images/gallery/";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
images.push({src: ".$dirname.$curimg"});
}
}
?>
images is a js array that i defined previously:
var images = [];
What can I do to pass my php array to js array? Or if this isn't the best method to do this, I would love to learn.
Edit:
Here is my code so far since some were asking. As of now I'm just trying to get the images to load. I can add everything else I need and make it look pretty after I get this working.
<!DOCTYPE html>
<html>
<!-- Magnific Popup core CSS file -->
<link rel="stylesheet" href="css/magnific-popup.css">
<head>
<title></title>
</head>
<body>
<ul>
<?php
$dirname = "images/gallery/";
$images = scandir($dirname);
echo json_encode($images);
/**shuffle($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
images.push({src: ".$dirname.$curimg"});
}
}
*/
?>
</ul>
<script type="text/javascript">
var imgs = eval('<?php echo json_encode($images) ?>');
for(var i = 0; i < imgs.length; i++) {
document.write("<img src=imgs[i]>");
document.write("imgs[i]");
console.log(imgs[i]);
}
</script>
<footer>
<!-- jQuery 1.7.2+ or Zepto.js 1.0+ -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!-- Magnific Popup core JS file -->
<script src="magnific-popup.js"></script>
</footer>
</body>
</html>
To pass an array from PHP to JavaScript you should convert it to JSON
PHP
<?php
$dirname = "images/gallery/";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
$array = array();
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
$array[] = $dirname.$curimg;
}
}
?>
JavaScript
<script>
var array = <?php echo json_encode($aray) ?>;
</script>
You have a number of choices. You should understand that you can put the PHP section in the middle of a script (Javascript) tag as shown below. In the script section in the header below, a new array is created, and then push statements are created for each element.
Please also note that the body has a PHP section that prints the list directly and a script tag that prints using the Javascript variable created in the header.
I used the list of files in the document root of the Apache server because that should work on all web sites. If you load the page on your test site, look at the source code that the browser receives. You don't put the PHP code (material between ) in its own file. The entire file below is sent to the PHP module because the file type is php. The PHP module then replaces the sections between with the material it generates and sends the modified page to your browser.
You can add JSON and AJAX, but I don't think that that is where your problem lies, and it isn't necessary. Try running this page on your server (I used the name array_demo.php for the file.) and see if you can understand it. It runs fine on my development server, so it should run correctly on yours.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP demo with arrays</title>
<?php
$root = $_SERVER["DOCUMENT_ROOT"];
$list = scandir($root);
?>
<script>
<?php
$number = count( $list);
print ("var jlist = new Array();");
foreach ($list as $item) {
if ($item == ".") { continue; }
if ($item == "..") { continue; }
print("jlist.push(\"$item\");");
}
?>
</script>
</head>
<body>
<h1>PHP demo with arrays</h1>
<p>In this example, PHP lists the contents
of the files contained in the PHP variable $list</p>
<ul>
<?php
foreach($list as $item) {
if ($item == ".") { continue; }
if ($item == "..") { continue; }
print("<li> $item </li>");
}
?>
</ul>
<p>Printing the list via Javascript element created
in script in header</p>
<ul>
<script>
for (var i = 0; i < jlist.length; i++) {
document.writeln("<li>" + jlist[i] + "</li>");
}
</script>
</ul>
</body>
</html>
Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help