I am trying to include a file if it exists, if the file doesn't exist i would like it to include another file instead.
I have the following code which seems to work correctly, The only problem with my code is if the file does exist then it displays them both.
I would like to only include
include/article.php
if
include/'.$future.'.php
doesn't exist.
if
include/'.$future.'.php
exists i don't want to include
include/article.php
<?php
$page = $_GET['include'];
if (file_exists('include/'.$future.'.php')){
include('include/'.$future.'.php');
}
else{
include('include/article.php');
}
?>
Your variable $future was never even defined, so how is it ever being included? I think you meant for $page and $future to be the same variable. Also including a file specified by the user in a get request doesn't make much sense to begin with, but is probably also a security risk.
Perhaps this is what you need?
Make sure any variable you're going to use IS defined before you'll
use the variable...
<?php
$page = ''; // show emptyness is there is nothing dome below
$page = isset($_GET['include']); // Do you have a variable in your URL that IS called "include" and is the include variable set? for example: http://www.example.com/index.php?include=....... you might want to check for empty value and write a default value as well but I didn't here ;)
// REMEMBER: $future must be defined BEFORE this line!
if (file_exists('include/' . $future . '.php') && is_file('include/' . $future . '.php')){ // file exists on server: true/false and is it a file or a directory? If Directory it will NOT be included as I used is_file()!
include('include/' . $future . '.php');
}elseif{
(file_exists('include/article.php') && is_file('include/article.php')){
include 'include/article.php';
}else{
echo 'WOW, No article found! You just found a error...<br />We will repair all errors ASAP! Thank you for visiting us...';
}
?>
Related
I use a php script to include another php file. When someone goes to the index.php with the wrong string, I want it to show on the screen an error message.
How do I make it show a custom error message like "You have used the wrong link. Please try again."?
Here is what I am doing now...
Someone comes to the URL like this...
http://example.com/?p=14
That would take them to the index.php file and it would pick up p. In the index.php script it then uses include ('p'.$p.'/index.php'); which finds the directory p14 and includes the index.php file in that directory.
I am finding people, for what ever reason, are changing the p= and making it something that is not a directory. I want to fight against that and just show an error if they put anything else in there. I have too many directories and will be adding more so I can't just us a simple if ($p != '14'){echo "error";} I would have to make about 45 of those.
So what is a simple way for me to say.... "If include does not work then echo "error";"?
$filename = 'p'.$p.'/index.php';
Solution1:
if(!#include($filename)) throw new Exception("Failed to include ".$filename);
Solution2: Use file_exists - this checks whether a file or directory exists, so u can just check for directory as well
if (!file_exists($filename)) {
echo "The file $filename does not exist";
}
You should never use this include solution, because it can be vulnerable to code injection.
Even using file_exists is not a good solution, because the attacker can try some files in your server that was not properly secured and gain access to them.
You should use a white list: a dictionary containing the files that the user can include referenced by an alias, like this:
$whiteList = array(
"page1" => "/dir1/file1.php",
"page2" => "/dirabc/filexyz.php"
)
if (array_key_exists($p, $whiteList)) {
include_once($whiteList[$p]);
} else {
die("wrong file");
}
In this way you do no expose the server files structure to the web and guarantee that only a file allowed by you can be included.
You must sanitize the $p before using it:
$p = filter_input(INPUT_GET, "p", FILTER_SANITIZE_STRING);
But depending on the keys that you use in the dictionary, other filters should be used... look at the reference.
if(!file_exists('p'.$p.'/index.php')) die('error');
require_once('p'.$p.'/index.php');
I includet lessphp with this code:
require_once(__DIR__.'/less/lessc.inc.php');
$less = new lessc;
$less->checkedCompile(__DIR__."/less/style.less", __DIR__."/css/style.css");
But because I include som other less files in the style.less I have to remove everytime after any change on any imported less file the output.css that I see the changes... anyone have any idea how I can tell the script that he have to check the whole folder "less" for any changes?
And please explain it easy for me.. my english is verry bad and I have no idea about php, maybe with a code example
Have a nice day!
From the documentation of lessphp.
There’s a problem though. checkedCompile is very basic, it only checks the input file’s modification time. It is unaware of any files from #import.
For this reason we also have cachedCompile. It’s slightly more complex, but gives us the ability to check changes to all files including those imported. It takes one argument, either the name of the file we want to compile, or an existing cache object. Its return value is an updated cache object.
So it seems that cachedCompile is the method for you.
This is the code for your case:
require_once(__DIR__ . '/less/lessc.inc.php');
$inputFile = __DIR__ . "/less/style.less";
$outputFile = __DIR__ . "/css/style.css";
$cacheFile = $inputFile . ".cache";
if (file_exists($cacheFile)) {
$cache = unserialize(file_get_contents($cacheFile));
} else {
$cache = $inputFile;
}
$less = new lessc;
$newCache = $less->cachedCompile($cache);
if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
file_put_contents($cacheFile, serialize($newCache));
file_put_contents($outputFile, $newCache['compiled']);
}
I wonder what ist he best way to do the following.
I am creating a webseite CMS. Through CMS I am creating new folders with index.php files in them. For example I have created folder with the site new_folder_name/index.php
I wonder what ist the best way to make an interaction between the created index.php files and database. For example I am creating the php file with another php file
<?php
$dir = "../new_folder_name";
$file_to_write = "index.php";
$content_to_write = '
<?php
//// php code
$foo=‘3‘:
?>
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
fwrite($file, $content_to_write);
fclose($file);
include $dir . '/' . $file_to_write;
?>
I am putting a variable $foo that needs to be changed with every new php file created. I could create $foo=GET(´SOEMTHING´) but this GET is making problems since this variable needs to be changed, and only for this file a unique value. I do not know if I explained it properly but I hope I did. In which way can I create a php file with specific $foo value or change the created file with php in order to get the $foo value which I want.
you can do
$content_to_write = '
<?php
//// php code
$foo=\'$_GET[\'something\']\';
?>';
this is make your new script to read $_GET['something']
OR
this example, read this script's $_GET['something'] and put it's value in script...
$content_to_write = '
<?php
//// php code
$foo=\''.$_GET['something'].'\';
?>';
since you use single quote $_GET didn't get parse with original script. If you want to use that simply concatenate it. Alternatively you can concatinate '$' in between string to make variable just variables.
When using the PHP include, how can I find out which file is calling the include? In short, what is the parent's file filename?
An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.
Parent File:
$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';
Included File:
if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";
You could also mess around with get_included_files() or debug_backtrace() and find the event when and where the file got included, but that can get a little messy and complicated.
$fileList = get_included_files();
$topMost = $fileList[0];
if ($topMost == __FILE__) echo 'no parents';
else echo "parent is $topMost";
I think this should give the right result when there's a single parent.
By that I mean the situation where the parent is not a required or an included file itself.
Late answer, but ...
I check the running parent filename by using:
$_SERVER["SCRIPT_NAME"] // or
$_SERVER["REQUEST_URI"] // (with query string)
You could use debug_backtrace() directly with no additional changes from within the included file:
$including_filename = pathinfo(debug_backtrace()[0]['file'])['basename'];
This will give you the name of the file that's including you.
To see everything you have access to from within the included file, run this from within it:
print_r(debug_backtrace());
You will get something like:
Array
(
[0] => Array
(
[file] => /var/folder/folder/folder/file.php
[line] => 554
[function] => include
)
)
Got this from here: https://stackoverflow.com/a/35622743/9270227
echo "Parent full URL: ";
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
I was searching same information on web for complement my online course about php and found two ways. The first was
$file = baseline($_SERVER['PHP_SELF']);
echo $file; //that outputs file name
BUT, in include or require cases it gets the final file that it's included or required.
Also found this, the second
$file = __FILE__;
echo $file; //that outputs the absolute way from file
BUT i just was looking for the file name.
So... I mix it up and it worths well!
$file = basename(__FILE__);
echo $file; //that outputs the file name itself (no include/require problems)
In the parent file, add this line before including the child file:
$_SESSION['parent_file'] = $_SERVER['PHP_SELF'];
And then in the child file, read the session variable:
$parent_file = $_SESSION['parent_file']
In my script, I set the include path (so another part of the application can include files too), check that a file exists, and include it.
However, after I set the include path, file_exists() reports that the file does not exist, yet I can still include the same file.
<?php
$include_path = realpath('path/to/some/directory');
if(!is_string($include_path) || !is_dir($include_path))
{
return false;
}
set_include_path(
implode(PATH_SEPARATOR, array(
$include_path,
get_include_path()
))
);
// Bootstrap file is located at: "path/to/some/directory/bootstrap.php".
$bootstrap = 'bootstrap.php';
// Returns "bool(true)".
var_dump(file_exists($include_path . '/' . $bootstrap));
// Returns "bool(false)".
var_dump(file_exists($bootstrap));
// This led me to believe that the include path was not being set properly.
// But it is. The next thing is what puzzles me.
require_once $bootstrap;
// Not only are there no errors, but the file is included successfully!
I can edit the include path and include files without providing the absolute filepath, but I cannot check whether they exist or not. This is really annoying as every time a file that does not exist is called, my application results in a fatal error, or at best a warning (using include_once()).
Turning errors and warnings off is not an option, unfortunately.
Can anyone explain what is causing this behaviour?
file_exists does nothing more than say whether a file exists (and the script is allowed to know it exists), resolving the path relative to the cwd. It does not care about the include path.
Yes Here is the Simplest way to implement this
$file_name = //Pass File name
if ( file_exists($file_name) )
{
echo "Exist";
}
else
{
echo "Not Exist";
}