Javascript array for all the files in a directory - javascript

I need to assign the list of all files of a directory (site_img) to a javascript array but not getting any luck.Can any one pls help .
i:e In the below code I want to assign the value of filename to an javascript array in each iteration of the for loop.
<?php
foreach(glob('./site_img/*.*') as $filename){
echo $filename;
echo "<br>";
}
?>

With PHP, here is a snippet that I use on one of my sites:
<?
$fileList = '';
$homePath = "a5780630"; //Dev
$homePath = "a2092434"; //Live
if ($handle = opendir('/home/'. $homePath .'/public_html/images/gallery/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$fileList = $fileList . ',' . $file;
}
}
closedir($handle);
}
?>
That will give you a comma delimited string of all the files. Then in JS:
<script language="javascript">
var listOfImages = "<?php echo $fileList; ?>"
listOfImages = listOfImages.split(",");
</script>

Related

Returning array values (image file names to javascript) from php

Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed

How to replace the variable from controller to into a (.php) file

I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);

Fill a javascript array with php variable

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want
Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()

image retrieval from directory and session variable issues - php

I have a problem when retrieving the images from a directory on my server, so what the main sequence is: in a page (multiupload.php) I added the input, allowed the image to be previewed and when the user submitted, a new directory with their session id would be created, the images would then be stored in the unique directory and the page would then be directed to (drag.php). The newly loaded page has a canvas with different divs to controls filters that are attached to that canvas. My problem lies with retrieving the image with the specified s_id as a directory name from one page to the other.
Q: Am i retrieving session variables properly? or using them appropriately?
This is the necassary snippets from multiupload.php's upload script.
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
I define the directory, whole path and the id for the directory. I would like to retrieve the id in the next page, but it's not doing it correctly.
and this is the retrieval code from drag.php
$realPath = 'uploads/'. echo $_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
My end result is that I would like all images to be drawn on the page. For now I would like them to be drawn anywhere aslong as they're visible.
If my question isn't clear, feel free to edit or comment where I should change. If you need more code or information, please let me know.
Please modify your code to this code:
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="'.$realPath.'/'.$file.'" border="0" width="200" />';
}
}
?>
I have use this code an I get the o/p like this:
<?php
$dir_id = session_id(md5(uniqid()));
session_start();
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
In any file.php, which u need get session:
<?php
session_start();
$realPath = 'uploads/'.$_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
?>
I advice to you read that: http://www.w3schools.com/php/php_sessions.asp when i was started with php 6 years ago - it was rly helpful
session_start does not take any argument. It's just to put a cookie and to read the session variables. (exposed in $_SESSION). You have to use session_start() on every pages to be able to read the $_SESSION variables.
this will give only image file from directory using session variable.
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
if(fnmatch('*.jpg', $file) || fnmatch('*.png', $file) || fnmatch('*.jpeg', $file)){
echo '<img src="'.$realPath.'/'.$file.'"/>';
}
}
}
?>

how to know all file names of the images from whole website?

I want to get all images of my whole website in an array, and all of my images are in a folder called images and within that folder many subfolders are there, So now how can I get all the images' path in an array?
Is it possible just with jquery, javascript? If not, php is ok.
I found this recursive function that can give you the tree of a given directory, you can use the $exclude param to filter only image files
<?php
/**
* Get an array that represents directory tree
* #param string $directory Directory path
* #param bool $recursive Include sub directories
* #param bool $listDirs Include directories on listing
* #param bool $listFiles Include files on listing
* #param regex $exclude Exclude paths that matches this regex
*/
function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DIRECTORY_SEPARATOR . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, directoryToArray($directory. DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
?>
source
And about the jQuery way, you can't access to the directory directly, you have to provide the list with an ajax call to your backend and give a json object so you render it with jQuery
try this PHP Script:
$dir = "images/*/";
//get all files with .jpg
$images = glob("" . $dir . "*.jpg");
$imgs = array();
// store images in $imgs - after that optional display
foreach($images as $image) {
$imgs[] = $image;
}
//display
foreach ($imgs as $img) {
echo '<img src="'.$img.'" />';
}
to store in a JS array:
$JSarray = json_encode($imgs);
echo "var JSarray = ". $JSarray . ";\n";
Use RecursiveDirectoryIterator , RecursiveIteratorIterator and RegexIterator to achieve this .
$imagesExtensions = array('jpg','png','gif'); //<=-- Add your extensions
$extensions = implode('|',$imagesExtensions);
$directory = new RecursiveDirectoryIterator('images');
$iterator = new RecursiveIteratorIterator($directory);//RecursiveDirectoryIterator::SKIP_DOTS);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $filename=>$object) {
echo $filename . '<br>';
$images[] = $filename; //<----- All images are stored in this array sequentially
}
OUTPUT :
images\google\client\ext\resources\themes\images\access\boundlist\trigger-arrow.png
images\google\client\ext\resources\themes\images\access\box\corners-blue.gif
images\google\client\ext\resources\themes\images\access\box\corners.gif
//....... Goes on..

Categories

Resources