Reputation: 2007
I would like to check if a page exists. My file is article.php . The article's URLs are article.php?id=1 article.php?id=2 etc. But when I check it this way it doesn't work:
$filecheck = "article.php?id=$id";
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
But it always returns "Sorry this article does not exist." How could I fix this?
Upvotes: 1
Views: 1483
Reputation: 79
Well the reason it is not finding the file is because you have a querystring in it. If you are by chance getting this data from some other source and can't control if a querystring is sent with it then you can do this:
$yourFile = 'article.php?id=$id'; // Or wherever you get this value from
$yourFile = strstr( $yourFile , '?' , TRUE );
echo $yourFile; // now has a value of article.php
Upvotes: 1
Reputation: 2831
The file "article.php?id=$id" will not exist as it is not a physical file.
I am assuming that you are using the $id to find an article that exists in a database. If this is the case then the file_exists function is not what you need.
What you will need to do is write a quick MySQL statement to check if the article exists and then go from there.
Something like this perhaps:
$query = "SELECT * FROM articles WHERE id='$id'";
$result = mysql_query($query);
// Check if result is there (ie article exists)
if ($result) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
I hope that helps. Let me know if you need anything else.
Upvotes: 1
Reputation: 81721
If they are physical page instead of dynamically created content use this way:
$filecheck = "article_1.php"
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
Otherwise check the ID whether it is in the DB.
Upvotes: 1
Reputation: 72672
It's because there is no file called: article.php?id=$id
There probably is a file called: article.php though :)
Upvotes: 1
Reputation: 47776
Don't pass the query string to it.
$filecheck = 'article.php';
Upvotes: 4