How to set php varible set in php and get filenames fromfolder - javascript

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>

Related

How to execute a JS function which is inside PHP tags?

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>

Dynamically inject PHP as form action redirects to 404 page

So what I'm doing is dynamically creating a form and input elements in a document with JS like so:
document.ondblclick = function(e) {
if (e.clientX < 50 && e.clientY > window.innerHeight - 50
&& !document.querySelector('form')) {
const b = document.body
const f = document.createElement('form')
const i = document.createElement('input')
b.style.width = '100vw'
b.style.height = '100vh'
b.style.margin = '0'
b.style.display = 'flex'
b.style.justifyContent = 'center'
b.style.alignItems = 'center'
i.setAttribute('type', 'password')
i.setAttribute('name', 'password')
i.setAttribute('id', 'form')
f.setAttribute('method', 'post')
f.setAttribute('action', '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>')
f.appendChild(i)
b.appendChild(f)
i.focus()
i.onblur = function() {
i.focus()
}
}
}
However, it's as if the browser ignores the PHP and, instead of returning to the current file, consequently gets redirected to the 404 page.
Below is the HTML, PHP, and the file structure of the directory.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST" && !empty($_POST["password"])) {
include "php/connect.php";
$stri = "SELECT password FROM account";
$stat = $conn->prepare($stri);
$stat->execute();
$resu = $stat->fetch(PDO::FETCH_ASSOC);
if (password_verify($_POST["password"], $resu["password"])) {
$_SESSION["session"] = $resu["password"];
$conn = null;
echo 'SUCCESS';
}
$conn = null;
}
?>
<!DOCTYPE html>
<head>
<title>‎</title>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
The directory is structured like so...
public_html >
trading-toolbox >
css > index.css
js > index.js
php > connect.php
index.php
Why is it redirecting to the 404 page? What am I doing wrong here? Is the action attribute of the form treated as a string since it is set dynamically with JS?
The problem is your index.js file. Notice the file ending? .js is a javascript file, and will be treated by your server as a static file, only serving the contents and not processing the file. The easiest solution is to rename it to index.php and then include it like normal:
<script type="text/javascript" src="js/index.php"></script>
You need name your .js file as .php and send headers for expose the file as javascript and use $_SESSION to send the action file from index to JS
<?php
header('content-type:application/javascript; charset=utf-8');
?>
...
f.setAttribute('action', '<?php echo htmlspecialchars($_SESSION["formFile"]); ?>')
...
Then in your index file add and change
<?php $_SESSION["formFile"] = $_SERVER["PHP_SELF"]; ?>
<script type="text/javascript" src="js/index.php"></script>

Displaying an image gallery from a folder of images automatically

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>

search folder on server and display results

How do I search a folder on my server and display the results on my webpage? I found a similar question at How can I create a search form that searches files in a folder? but I can't figure out how to connect the php script to my html:
<!DOCTYPE html>
<html>
<body>
<div>
<input id="query" type="text"/><button id="search-button" onclick="?????">Search</button>
</div>
<script>
var q=document.getElementById("query");
</script>
<?php
$dir = "/uploads/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
echo(''. $file .''."\n");
}
}
closedir($dh);
}
}
?>
</body>
</html>
You can post info to a php script seamlessly (asynchronously) with jQuery's post method. Then you can return the data to the calling page and display it.
So have the php script that lists/finds the files and the html page separate. Then in the html page use javascript and jQuery to post to that php finder script. Something like:
$.post('phpFileFinder.php', {fileName: fileNameJSvar}, function(data){
$("#divId").html(data);
});
Then in your php script you can have:
$dir = $_POST['fileName'];
$fileArray = array();
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
array_push($fileArray,''. $file .''."\n");
}
}
closedir($dh);
}
print_r($fileArray);
}

fetch data from text file and update web page every minute

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>

Categories

Resources