views:

94

answers:

4

I have a simple image-looping script that changes the src of an image.

function cycleNext()
{
    ++imgIndex;

    if(imgIndex>imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.

How can I use PHP to supply this script with the number of images in the folder?

+1  A: 
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>

Repeat the 2nd line for each extension you wish to count.

function cycleNext()
{
    ++imgIndex;

    if (imgIndex > <?php echo $filecount;?>)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

That should do it.

EDIT:

function cycleNext(imgCount)
{
    ++imgIndex;

    if (imgIndex > imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

Then when you call cycleNext, call it with the variable.

cycleNext(<?php echo $filecount; ?>);
Gazler
That will work if the script is part of the page. If it's a separate .js file, then I think there would be a problem.
Pointy
Yeah, I just assumed the JS was inline. If the js is not inline, make the imgcount a function variable and pass it through with PHP.
Gazler
Thanks, if a typical source is "graphics/x.jpg" then $directory would be "graphics/", right?
Isaac Lubow
@ Gazler, you mean define imgCount inline and then I can call it with my external .js file?
Isaac Lubow
And, it wouldn't be a problem if the script were in the same directory, right?
Isaac Lubow
I have edited it to show what I meant. And the directory would be 'graphics/' yes.
Gazler
A: 

During the generation of the HTML code, simply insert a <script> line, for instance

  echo '<script type="text/javascript">';
  echo 'var imgCount=' . $NumberOfImages . ';';
  echo '</script>';

Just ensure that line is provided before cycleNext() is called (or imgCount is used).

ring0
+1  A: 

if the .js file is a separate file. then you can do this:

change the .js for a .php

then you can add <?php ?> tags just like you do in your .php files.

just don't forget to add the header in the code, indicating that the file is a javascript file. like that:

<?php header("Content-type: text/javascript"); ?>

and you will call the file with it's actual name src="file.php"

hugo_leonardo
+1  A: 

You can do it in three ways:

  1. Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
  2. include the javascript to the <head> tag of your page
  3. echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:

    <script type="text/javascript">
      var imgCount = <?php echo $imagecount ?>
    </script>;
    
Kau-Boy