1

I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.

i have the set the server using xampp.

how to correct this, i make the names of images from that folder printed on screen?

do i need to do anything extra

im a newbie in php. how can i achieve this?

<?php

function findImagesInFolder()
{
    $folder = $_GET['C:\xampp\htdocs\firstsite'];
    $images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);

    echo json_encode($images);
    exit();
}
?>
wtp
  • 249
  • 1
  • 7

1 Answers1

2

It seems you have misused the $_GET variable.

I thing you want to just use the string value, ie.:

$folder = 'C:\xampp\htdocs\firstsite';

And note, the exit() terminates whole script after printing the json_encoded string.

So, to make the function reusable change it to get the path as a parameter $folder:

<?php

function findImagesInFolder($folder, $filter = '*.*')
{
    // note, here we expect the path does not trail with backslash
    $images = glob($folder . '\\' . $filter, GLOB_BRACE);
    return json_encode($images);
}

// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>

Note: output as [] means empty array encoded to JSON.


DaFois
  • 2,121
  • 8
  • 21
  • 35
ino
  • 1,698
  • 1
  • 12
  • 21
  • changed the code and called the function with actual path to scan and it shows [] opening and closing brace – wtp Dec 02 '18 at 12:21
  • 1
    I have updated the code. Note the backslash in glob() function. – ino Dec 02 '18 at 12:22
  • i have seen te update and used the glob the udated backslash, get [] opening and closing bractet as output – wtp Dec 02 '18 at 12:25
  • $images = glob($folder . '\{*.png,*.jpg,*.jpeg,*.gif}', GLOB_BRACE); used this glob parameter and still getting [] openig,closing bracket as output – wtp Dec 02 '18 at 12:31
  • 1
    ok,, so the problem was with the backslash - has to be escaped, of course :D And I have change the function to use second, optional param for the filter. – ino Dec 02 '18 at 12:32
  • if i echo something like`hello` i get `hello[]` – wtp Dec 02 '18 at 12:37
  • 1
    Is the target folder accessible? Try `echo findImagesInFolder('.');` And Always debug your scripts with enabled [PHP Error Reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display)! – ino Dec 02 '18 at 12:40
  • it could be easier if you put the last backslash in the path... without backslashing it in the globe argument – DaFois Dec 02 '18 at 12:49
  • @ino wheni echo findImagesInfolder('.') it is giving me` [][".\\23.jpg",".\\24.jpg",".\\25.jpg",".\\Untitled-1.php"]` – wtp Dec 02 '18 at 13:03