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);
}
Related
In this blog, I will teach you how to display existing files or image on server in dropzone js. I will learn to show you existing image on dropzone js in php.
You can simply and easily to upload files or image on server using dropzone js. if you used dropzone js for uploading files and image then you might be need to show existing files or image from database using php mysql.
You will create just two files and one "upload" folder to make it done this example ,so just follow bellow example.
Create Index.php File
<!DOCTYPE html>
<html>
<head>
<title>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css' type='text/css' rel='stylesheet'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js' type='text/javascript'></script>
<style type="text/css">
.dz-preview .dz-image img{
width: 100% !important;
height: 100% !important;
object-fit: cover;
}
</style>
</head>
<body>
<div class="container" >
<h1>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</h1>
<div class='content'>
<form action="upload.php" class="dropzone" >
</form>
</div>
</div>
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 'fetch'},
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
}
});
</script>
</body>
</html>
Create upload.php File
<?php
/* Upload directory*/
$targetDir = "upload/";
$request = "upload";
if(isset($_POST['request'])){
$request = $_POST['request'];
}
/* Upload file */
if($request == "upload"){
$msg = "";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetDir.$_FILES['file']['name'])) {
$msg = "Successfully uploaded";
}else{
$msg = "Error while uploading";
}
echo $msg;
exit;
}
/* Read files from */
if($request == 'fetch'){
$fileList = [];
$dir = $targetDir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$file_path = $targetDir.$file;
if(!is_dir($file_path)){
$size = filesize($file_path);
$fileList[] = ['name'=>$file, 'size'=>$size, 'path'=>$file_path];
}
}
}
closedir($dh);
}
}
echo json_encode($fileList);
exit;
}
It's because the internal function of react-native-weekday-picker mutates the same object (repeatDays in your case) passed to the library.
see here
and thought, you are setting a new state before rendering component the React compares prev value and current value but since it's of the same reference it doesn't rerender
const RepeatDaysHandle = (repeatDays) => {
console.log(repeatDays);
setWeekDays({...repeatDays});
}
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 am trying to make a web ftp explorer like Monsta FTP. Currently I'm trying to make a function that will switch the current directory to the directory I click on.
This is how it currently looks like:
The PHP (index.php):
<?php
if(isset($_POST['file_name'])) {
$file_name = $_POST['file_name'];
ftp_chdir($ftp_conn, $file_name);
echo "<p>".ftp_pwd($ftp_conn)."<p>";
}
// connect to the FTP server
$ftp_server = "xxxxxxxxx";
$ftp_username = "xxxxxxxxx";
$ftp_userpass = "xxxxxxxxx";
$ftp_conn = ftp_connect($ftp_server, 21) or die("Could not connect to $ftp_server");
if ($ftp_conn === false) {
echo "Unable connect to the ftp server.<br>";
} else {
echo "Succesfully connected to the ftp server.<br>";
}
//login to the FTP server
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
if ($login === true) {
echo "Succesfully logged in to the ftp server.";
} else {
echo "Unable to log in to the ftp server.";
}
//get a list of all files and folders
$contents = ftp_nlist($ftp_conn, '/');
echo "<ul>";
for ($i = 0 ; $i < count($contents) ; $i++) {
echo "<li>".$contents[$i]."</li>";
}
echo "</ul>";
// close connection
ftp_close($ftp_conn);
?>
<!DOCTYPE html>
<html>
<head>
<title>FTP file menager</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/functions.js"></script>
</body>
</html>
The JS (functions.js):
function post(vally) {
var name = vally;
$.post('index.php', {file_name:name}, function(data) {});
console.log('posted');
}
When I click on one of the links with the folder name, I get "posted" in the console meaning that JQuery (I'm using JQuery 3.2.1 downloaded from jquery.com) posted the data but I don't get any alerts or echos from PHP. I tried putting the if () before and after the connection to the ftp server has been established, but I still get nothing.
Does anyone have an idea on why my code doesn't work?
Try removing ftp_close($ftp_conn); because it closes the ftp connection before the js gets loded and therefore php can no longer execute ftp commands, unless you open the ftp connection in the isset().
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>
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>