0

I have tens of php file in of my site folder. All of them have a comment line at the very beginning which is:

//This is a php file

Whenever I include a file, I want to check if it has the following comment line at the beginning. How shall I approach this?

j08691
  • 204,283
  • 31
  • 260
  • 272

3 Answers3

1

Use this:

$f = fopen('yourFile.php', 'r');
$line = fgets($f);
fclose($f);

(Source: Quickest Way to Read First Line from File)

Then you can check $line, like so:

if (strpos($line,'//This is a php file') !== false) {
    echo 'true'; //Found
}

Note: as mentioned by @salathe, you will need to do something like this: PHP: Read Specific Line From File

Community
  • 1
  • 1
funerr
  • 7,212
  • 14
  • 81
  • 129
0
$file = 'text.php';
if($f = fopen($file, 'r')){
  $line = fgets($f); // read until first newline
  fclose($f);
}

where text.php is the file you include.

geryjuhasz
  • 184
  • 1
  • 15
0

Not exactly answering your question, but probably a better solution for checking whether an included file is actually part of your system is like thus:

Your main file, which is including other files has the following line:

define("SYSTEM_LOADED",true);

or use a different global variable. Now in the included file test like thus:

if(!defined("SYSTEM_LOADED")) die("System is not loaded");

This approach puts testing in the included file, instead of the main file. The drawback of your approach is that for each file the file has to be opened, which is fine for one or a few files, but which will have an impact on your application after multiple files.

Luceos
  • 6,629
  • 1
  • 35
  • 65
  • you are true #Luceos, but in each page there at most will be 6 or 7 files included. I want to make a class, and then a method, to include each php file from database configuration all to html pieces. this comments adds a little bit more security, while a hacker might add a php file without such comment, which anyways makes it file failed. –  Jun 15 '13 at 19:15
  • 1
    @MostafaTalebi If you need to do security this way, something is very wrong elsewhere in the system. – Pier-Luc Gendreau Jun 15 '13 at 19:22
  • can you please explain more –  Jun 15 '13 at 20:30
  • @Pier-LucGendreau means that if you would need a system to check for a defined variable or for a comment in the file, you're protecting yourself against vulnerabilities in your system. You should probably fix the vulnerability. – Luceos Jun 16 '13 at 14:18