Displaying an image gallery from a folder of images automatically - javascript

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>

Related

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

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>

Passing php objects to Javascript without exposing php object values in page source

I have an index.php, a navbar.php landingpage.php, and a landingpage.js
The navbar.php file is where I retrieve user information upon successful login on index.php As shown below, I use if-else to select which navigation items to display per user. In this case, we have Settings navigation item.
navbar.php
<?php
require_once 'core/init.php';
require_once 'dbutil/dbconnection.php';
require_once 'functions/sanitize.php';
require_once 'functions/redirect.php';
$user = new User();
$user->setId($_SESSION['userId']);
$user->setUsername($_SESSION['username']);
$user->setPassword($_SESSION['password']);
$user->setLastname($_SESSION['lastname']);
$user->setFirstname($_SESSION['firstname']);
$user->setMiddleinitial($_SESSION['middlename']);
$role = new Role();
$role->setRoleId($_SESSION['roleId']);
$role->setRolename($_SESSION['rolename']);
?>
<?php if ($role->getRolename() === 'Administrator') : ?>
<a class="nav_tab" id="admin_settings" href="#">
Settings
</a>
<?php endif; ?> ....
landingpage.php has the navbar.php attached to it.
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<!-- this div gets filled with different content/page depending on what was clicked on the navbar. -->
<!-- end of container-->
</div>
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
GOAL: I had to pass the php $user variable and $role to landingpage.js (in other words, make their values visible within the landingpage.js)
PROBLEM: The way I have it setup to make $user and $role variables' values visible in landingpage.js, exposes $user and $role properties when you view the page source code. I can't think of another way or setup to pass php objects $user and $role values to my external javascript file without exposing its properties.
The reason I am passing the json_encode($user) and json_encode($role) to landingpage.js is so that I can show or hide parts of the landing page depending on the role of user who is logged in.
landingpage.js
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
$(document).ready(function(){
loadDashboard();
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
Sorry for the long description. I'm fairly new with integration of PHP AJAX and JQuery and still trying to really understand how to properly setup the pages to avoid repetition of codes.
I'd appreciate any suggestion. I just thought that it's really wrong to expose the php object values during json_encode()
Thank you.

Why the fetching of php query in javascript doesn't worked?

I have php inside javascript, and I made a query inside php, but the query cannot be fetched even in php area itself, why?
I have tried that query in PHPmyAdmin manually and it works fine. The "ca" field value is 1 not 0, but after i apply on code the result of "ca" is 0. What is wrong exactly? And there's no error message shows in console log.
image:
simple code:
<?php
include('ckcon.php');
include('logincheckmember.php');
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
<script>
function kampret(){
var ssloginmember = document.getElementById('id1').textContent;
var ambilun = document.getElementById('id2').textContent;
<?php
$ssloginmember=ssloginmember;
$ambilun=ambilun;
$q=mysql_query("SELECT COUNT(ai) AS ca,unnum FROM t_follow WHERE username='$ssloginmember' AND username2='$ambilun'");
$f=mysql_fetch_object($q);
$unnum2=$f->unnum;
$ca=$f->ca;
if($ca==0){
$status='follow';
$unnum=0;
}else{
$status='unfollow';
$unnum=$unnum2;
}
?>
var status='status = '+<?php echo json_encode($status);?>;
var unnum='unnum = '+<?php echo json_encode($unnum);?>;
var output1='output1 = '+<?php echo $ssloginmember;?>;
var output2='output2 = '+<?php echo $ambilun;?>;
document.getElementById('status').innerHTML = status;
document.getElementById('unnum').innerHTML = unnum;
document.getElementById('output1').innerHTML = output1;
document.getElementById('output2').innerHTML = output2;
}
</script>
</head>
<body>
<div id="status">status</div>
<div id="unnum">unnum</div>
<div id="output1">output1</div>
<div id="output2">output2</div>
<br>
<button onClick="kampret()" >button</button><br>
<br>
<div id="id1">melisavirgi</div>
<div id="id2">ririnputrian</div>
<br>
<?php
echo "ssloginmember=$_SESSION[ssloginmember]";
?>
</body>
</html>
result:
The problem seems to be that you are trying to get a javascript value in the PHP, ie $ssloginmember=ssloginmember;.
The PHP code is run before the page is loaded in the browser and generates parts of your javascript code. Your script seems to be acting as if it is run every time the javascript function is called, and as if both languages are the same.
AJAX is probably going to be your best solution - post the data to a PHP script that returns the values you need.
I suspect you may need to brush up on the difference between client side and server side code, too.

How to scan mp3 files and list them on a web player?

I just built a mp3 player from playlist.me the script looks like this:
<!-- Song Player http://playlist.me -->
<script
type="text/javascript"
src="http://playlist.me/w/script.js"
data-config="{'skin':'skins/black/skin.css','volume':50,'autoplay':false,'shuffle':false,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'Song TItle','url':'http://sourcemp3.com/music.mp3'}]}" >
</script>
<noscript>
SCM music player
</noscript>
<!-- playlist.me script end -->
The problem is that I have to manually edit the script to add more MP3 files, how do I add files without manually edit the script? My MP3 files are located in /mnt/usb. I can do find with bash to list all the music files but how do I put them in the script above? My goal is that I want to be able to update my MP3 files by just copying and pasting my files to /mnt/usb/ and they'll show in my web player automatically.
UPDATE as suggested, I edited my script to be like this:
<?php
$glob = glob('/mnt/usb/*.mp3');
$url = '/mnt/usb/';
$playlist = array();
foreach ($glob as $mp3) {
$playlist[] = array('title' => $mp3, 'url' => $url . $mp3);
}
echo '
<html>
<head>
<title> MP3 Player</title>
</head>
<body>
<script
type="text/javascript"
src="http://playlist.me/w/script.js"
data-config="{\'skin\':\'skins/black/skin.css\',\'volume\':50,\'autoplay\':false,\'shuffle\':false,\'repeat\':1,\'placement\':\'bottom\',\'showplaylist\':false,\'playlist\':[{\'title\':\'Song TItle\',\'url\':\'http://sourcemp3.com/music.mp3\'}]}" >
</script>
<noscript>
SCM music player
</noscript>
</body>
</html>';
echo sprintf("'playlist':%s", json_encode($playlist));
?>
But I get the following error: Fatal error: Call to undefined function json_encode() in /www/music.php on line 25 and the music won't load either. Please help
UPDATE AGAIN I got that json part sorted out, now the problem is like this:
My script:
<?php
$glob = glob('/mnt/usb/*.mp3');
$url = '/mnt/usb/';
$playlist = array();
foreach ($glob as $mp3) {
$playlist[] = array('title' => $mp3, 'url' => $url . $mp3);
}
echo sprintf("'playlist':%s", json_encode($playlist));
echo '
<html>
<head>
<script
type="text/javascript"
src="http://playlist.me/w/script.js"
data-config="{"skin":"skins/black/skin.css","volume":50,"autoplay":false,"shuffle":false,"repeat":1,"placement":"bottom","showplaylist":false,"playlist":" >
</script>
<title> MP3 Player</title>
</head>
<body>
<noscript>
SCM music player
</noscript>
</body>
</html>';
echo sprintf("'playlist':%s", json_encode($playlist));
?>
How do I solve this?
Can't be done in pure clientside Javascript because it can't read the servers filesystem. Need at least 1 Serverside language:
Embed this PHP into your Javascript, to fill the playlist variable.
<?php
$glob = glob('/mnt/usb/*.mp3');
$url = 'http://localhost/usb/';
$playlist = array();
foreach ($glob as $mp3) {
$playlist[] = array('title' => $mp3, 'url' => $url . basename($mp3));
}
echo sprintf("'playlist':%s", json_encode($playlist));
Symlink (type in console):
ln -s /mnt/usb /www/usb

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