Search code examples
phpincludeglobscandir

glob - scan folder for php news article files


I have a news overview page, and a folder of php files I would like to individually include. Rather than manually including each one into my overview page, I thought I would use php to scan the folder for php files, and print them out as an include statement.

I have the following code:

<?php $articles = glob("/assets/news/form/*.php"); ?>
<?php
if(count($articles)) {
  natcasesort($articles);
  foreach($articles as $article) {
  ?>
      <?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/$article"); ?>

<?php
    }} else {
      echo "Sorry, no articles to display!";
    }
?>

I get no syntax with this, but I do not receive any output. Just a blank space where the articles should be.

The output I am wanting is something like this:

<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/1.php"); ?>
<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/2.php"); ?>
<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/3.php"); ?>
<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/4.php"); ?>
<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/5.php"); ?>
<?php include("$_SERVER[DOCUMENT_ROOT]/assets/news/overview/6.php"); ?>

Ultimately I am wanting to write a php function that scans a folder in ROOT/assets/news/form/ for all php files, and include all the files with the same name from the folder ROOT/assets/news/overview.

My news overview page is currently in /news/index.php

Can anyone help me out with this?


Solution

  • Here, give this a whirl: (TESTED)

    Tested on my server using absolute path.

    <?php
    
    // path to .php files must be absolute path
    // example: /server/user/f/fred/forms/*.php
    // May have to modify your path if it's not absolute
    
    // You may have to use this, if doesn't work
    // $articles = glob("$_SERVER[DOCUMENT_ROOT]/assets/news/forms/*.php");
    $articles = glob("/assets/news/forms/*.php");
    
    if(count($articles)) {
      natcasesort($articles);
      // rsort($articles); // use rsort for descending order
    
    foreach($articles as $article) {
        $article = basename($article);
    
    // You may have to use this, if doesn't work
    // include("$_SERVER[DOCUMENT_ROOT]/assets/news/forms/$article");
    include("$_SERVER[DOCUMENT_ROOT]/assets/news/forms/$article");
    
          }
    
        }
    
    else {
    
    echo "Sorry, no articles.";
    
    }
    
    ?>