Load Random Image From Directory on Page Load Without a Listed Array of File Names

前端 未结 4 946
一向
一向 2021-01-26 21:32

I\'ve done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image

4条回答
  •  星月不相逢
    2021-01-26 21:49

    So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:

    1. Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
    2. Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.

    Code Block:

    ";
    ?>
    

    Thank you @bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)

    Thanks again to everyone that helped me out!

提交回复
热议问题