Home > Software design >  How would you echo the content of a file in php?
How would you echo the content of a file in php?

Time:11-29

So I'm making a whitelist through my own website. I'm using a php to handle a request where it checks if your key matches the whitelisted keys and then echoes. My current code is:

$keys = array(
"Key", "key1");
 
$sub = $_GET["key"];
if (in_array($sub,$keys,TRUE)) {
    echo "Whitelisted"; 
} else {
    echo "Not Whitelisted";
}
?>

Instead of echoing "Whitelisted", I would like to return some text from a file (actually it is a script in some programming language to be executed on client side to make the whitelist more secure, but it does not matter for this question). I have the file in the public html directory and I was wondering if there was a way to call/access/require the entire content of the file. I'm a complete noob with php so if anyone could offer anything I would be very thankful.

CodePudding user response:

Try something like:

<?php

$whitelistedKeys = array(
    'Key', 'key1'
);
 
$input = $_GET['key'];
if (in_array($input, $whitelistedKeys, TRUE)) {
    echo 'Whitelisted<br>';

    $filePath = __DIR__ . '/my-file.txt';
    echo "Content of \"$filePath\" file is:<br>"; 
    echo file_get_contents($filePath);
} else {
    echo 'Not Whitelisted';
}
?>

Note that I am not using double-quote to improve performance.

And am using __DIR__ to load my-file.txt from same directory which the PHP-script is in.

  •  Tags:  
  • php
  • Related