?
Solved

PHP array script and writing the array to HTML.

Posted on 2007-10-01
8
Medium Priority
?
327 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>






0
Comment
Question by:VeeVan
  • 5
  • 3
8 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 19989886
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>";
     }
}
0
 
LVL 1

Author Comment

by:VeeVan
ID: 19990018
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
0
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 1500 total points
ID: 19990177
Sorry "path to images" is a typo. YOur question was very similar to this one

http://www.experts-exchange.com/Programming/Languages/Scripting/Perl/Q_22861045.html

which I did a few days ago so I pinched the code. It should, of course, be $pathToFolder. If you are going to store these images in a database table then "pathToFolder" is OK, if OTOH you want them to be displayed on a page then $pathToFolder would need replacing with the web URL of the images folder as in the answer above.


With regard to "it must be in an HTML document", if you want to use PHP then you must do one of two things

1) Put all your code in a .php file, or

2) Alter your webser to process .html as a PHP extension.

Option 1) is the usual solution.

Your code would look something like that below. To simplify, I have removed the javascript so you can see how the PHP fits in. Save this as a .php rather than a .html. Also I have used the code from Simon's question which was specific towards .jpg images so a change may be needed there.

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

<?php

$pathToFolder = "/path/to/folder/";
$webserverUrl = "http://server-name/any-folders-or-subdirectories/images/";

$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='82' height='108' />";
     }
}


?>
<!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 echo $imageSTring; ?>


</body>

</html>

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:VeeVan
ID: 19990624
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
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 19991742
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?
0
 
LVL 1

Author Comment

by:VeeVan
ID: 19992995
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>
0
 
LVL 1

Author Comment

by:VeeVan
ID: 19993253
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.
0
 
LVL 1

Author Comment

by:VeeVan
ID: 19994106
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>
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month13 days, 12 hours left to enroll

755 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question