Šime Vidas
Šime Vidas

Reputation: 185933

Check if file exists that starts with given string

Given a name

$path = 'articles/001.html';

I can check if such a file exists like so:

if ( file_exists( $path ) ) {
    // include it
} else {
    // redirect to articles index
}

However, I was thinking about modifying the URL of the article by adding the title of the article to it. So, if the user requests this URL:

"http://foo.com/articles/001"

I would like to transform the URL to this:

"http://foo.com/articles/001/the-title-of-the-article-here"

Now, this of course means that I have to store the title of that article (and all other articles) somewhere. The title is located in the <h1> element of the article, but I doubt that reading the article (file) on the server just to retrieve the title is a good idea.

So, I was thinking about putting the title in the file name like so:

"001-the-title-of-the-article-here.html"

Then I could just extract it from the file name and add it to the URL. However, I'm not sure how to check if such a file exists in the articles directory - all I got is the article ID (001 in this case).

So, based on an ID, I would like to check if there exists an HTML page inside the articles directory that starts with that ID, and if yes, I would like to retrieve its file name.

Can this be done? Is this a good approach? Suggestions are welcome.

Upvotes: 2

Views: 6036

Answers (1)

deceze
deceze

Reputation: 522081

glob can match files according to a pattern for you:

$files = glob('articles/001-*.html');

It gives you back an array of all matched files.

Upvotes: 12

Related Questions