We help IT Professionals succeed at work.

PHP array script and writing the array to HTML.

VeeVan
VeeVan asked
on
373 Views
Last Modified: 2008-01-09
I am a complete PHP novice and I have modified/written this script that is supposed to send the contents of a folder to an array.

Then, within my document, it is supposed to write that array to image thumbnails. Except it doesn't work. I keep getting the error GalleryImages not defined.

If I modify the code so that I am dimensioning galleryimages, it doesn't throw any errors, however, it doesn't actually DO anything either. I am certain that I am doing something wrong (obviously) but don't know enough to correct it.

Any help is appreciated.


Here is the PHP file:

<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname=".") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}

closedir($handle);
}
return($files);
}

echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>



=============================================

Here is my html doc:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<script type="text/javascript" src="photo_gallery/getimages.php"></script>
<script language="javascript" type="text/javascript">

function writethumbnails()
{
  var code = '';
  for (var l = 0; l < galleryarray.length; l++)
    code = code + '&nbsp; &nbsp;' + '<A HREF=photo_gallery/"' + galleryarray[l] + '"><img src="photo_gallery/' +
             galleryarray[l] +
            '" height="25%" alt="photogallery"/><\/A><BR>';
      return code;
}

</script>
</head>

<body>
<script type="text/javascript" language="javascript">
writethumbnails();
</script>


</body>

</html>






Comment
Watch Question

CERTIFIED EXPERT

Commented:
You could just use scandir to get the files in a folder


$pathToFolder = "/path/to/folder/";
$fileArr = scandir( $pathToFolder );

if ( count($fileArr) > 0 ) {
     foreach( $fileArr as $aFile ) {
          echo "<p>$pathToImages$aFile</p>";
     }
}

Author

Commented:
Great. Looks very simple.

Two quick questions, though:
What is the "PathtoImages" variable? and Don't I have to set that somewhere?
Then how do I implement that in my html file? (my final document has to be an html doc.)

Thanks.
V
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
OK. I appreciate the additional code.
When I run the code on my web server, I get the following error:

Fatal error: Call to undefined function: scandir() in /home/bjcycles/public_html/thumbnails.php on line 14
Also, there needs to be an opening body tag and closing head tag in there. I put them prior to the echo statement. I hope that was where they were supposed to go.

Also, what I am trying to do is this:

Create an array in a php file, which I can then use the <script> tag to reference my PHP file.

I then want to use javascript to pull the array from the PHP file and use IT to write the array to html.

I am using SunShop and as such, my templates have to be in HTML format. The final page will run in PHP, but I have to store my custom PHP code in another separate PHP file. I cannot put my own script in the final page.

Thanks again.
V
CERTIFIED EXPERT

Commented:
I do not understand why you would be getting a scandir error. I have checked the code and it runs OK. Obviously you would need to replace the values in $pathToFolder and $webserverUrl. The only problem with the code was that it had

<?php echo $imageSTring; ?>

instead of

<?php echo $imageString; ?>


VeeVan wrote: "Also, there needs to be an opening body tag and closing head tag in there. I put them prior to the echo statement. I hope that was where they were supposed to go."

Should be OK



VeeVan wrote: "Also, what I am trying to do is this:

Create an array in a php file, which I can then use the <script> tag to reference my PHP file.

I then want to use javascript to pull the array from the PHP file and use IT to write the array to html."

You need to be clear about something. Javascript is a client side technology, PHP is server side and they don't really meet unless you want to use AJAX and for a beginner that's not a good idea. Without AJAX javascript won't be pulling anything from PHP.

Your other option is to have PHP write the javascript which seems an awkward way to proceed. Is there some reason that you *must* use javascript?

Author

Commented:
I'll try and make the PHP work directly with my Sunshop page.... but for right now, and to test, I have saved the following exactly as thumbnails.php.

When I try and open it directly using the following link, I get the error message listed above:

http://www.bjcyclesupply.com/thumbnails.php


Here is the exact code in my doc:

========================================

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>

<?php

$pathToFolder = "/photogallery/";
$webserverUrl = "http://www.bjcyclesupply.com/photogallery/";

$fileArr = scandir( $pathToFolder );
$imageString = "";

if ( count($fileArr) > 0 ) {
     foreach( $fileArr as $anImage ) {
          $filename = strtolower( $anImage );          
          if ( strpos( $filename, ".jpg" ) !== false )
               $imageString .= "<img src='$webserverUrl$anImage' width='25%' height='25%' />";
     }
}


?>

</head>
<body>
<?php echo $imageString; ?>


</body>

Author

Commented:
Also, I found this out:

scandir() is PHP 5 CVS only
http://us3.php.net/manual/en/function.scandir.php

My webserver is not using PHP5, they are using PHP4.

Author

Commented:
I have solved the problem. I have modified the script from my first post, and it all lives in one PHP file now. Thanks for putting me on the right track. For future users:

THIS IS THE SOLUTION
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

<table>
    <tbody>
        <tr>
            <td align="center" valign="middle">
   

<?php

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="/home/bjcycles/public_html/photo_gallery/") {
$pattern="(.jpg$)|(.png$)|(.jpeg$)|(.gif$)"; //valid image extensions
$files = array();
$curimage=0;
$imageString = "";
$pathToFolder = "/home/bjcycles/public_html/photo_gallery/";
$webserverUrl = "http://www.bjcyclesupply.com/photogallery/";


if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo '<a href="http://www.bjcyclesupply.com/photo_gallery/'.$file .'" target="_blank"><img src="http://www.bjcyclesupply.com/photo_gallery/'.$file .'" height="125px"  /></a> &nbsp; &nbsp;';
$curimage++;
}
}

closedir($handle);
}
return($files);
}

?>

<?php

returnimages() //Output the array elements containing the image file names

?>

</td></tr></tbody></table>
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.