I am redirecting all page requests through a file called index.php which looks at the URL the visitor requested and sees if there is a template file to match.
For example, http://www.website.com/contact will actually route to the index.php script and should check to see if the file /var/html/template/contact.tpl exists and include it if it does.
My concern is with regards to security and null characters, extra dots and slashes, etc. Does any kind of filter need applying to the code below or is the use of pathinfo and the directory prefix enough? Obviously I don't want anyone to be able to maliciously include files outside of the designated template directory.
<?php
define ('TEMPLATES', '/var/html/templates');
$page = pathinfo ($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);
if (file_exists (TEMPLATES . '/' . $page . '.tpl')) {
include (TEMPLATES . '/' . $page . '.tpl');
} else {
header ('HTTP/1.0 404 Not Found');
echo 'Sorry page not found';
}
?>
To be 100% safe, make a list of allowed pages and check that it's in that array before returning the page.
You could even try a php glob() e.g..
define ('TEMPLATES', '/var/html/templates/');
$page = TEMPLATES . pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME) . '.tpl';
if (in_array($page, glob(TEMPLATES . '*.tpl'))) {
include ($page);
} else {
header ('HTTP/1.0 404 Not Found');
echo 'Sorry page not found';
}
This will validate that it's in that folder and that the extension is '.tpl'
Sorry - just edited to make glob() behaviour correct.
Related
I am working with codeigniter. I want to display images but if some image is not exist it should show image-not-found-medium.jpg which is dummy image..
below is my code
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";
if (file_exists($image_name_with_path)) {
echo $image_name_with_path;
} else {
echo $image_not_found_medium;
}
?>
but it always shows $image_not_found_medium i think there is problem with my if condition.
Please help.
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your image url
$image_file_path=FCPATH.'assets/images-products/medium'. $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your file path
if (file_exists($image_file_path)) //file_exists of a url returns false.It should be real file path
{
echo $image_name_with_path;
}
else
{
echo $image_not_found_medium;
}
?>
You are using absolute path for file existence which is wrong. You have to use real path because the file_exists() function checks whether or not a file or directory exists on the current server.
If your assets folder is placed in root then just use getcwd() - Gets the current working directory as
$image_path_medium = getcwd().'assets/images-products/medium';
Otherwise give the proper path to the assets folder like
$image_path_medium = getcwd().'application/views/assets/images-products/medium';
Instead of file_exists() prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.
Use like this.
$g = base_url().'upload/image.jpg';
if(file_exists($g) !== null){//your code..}
This is works for me in CI.
I'm attempting to try and debug the following code with the file_exists function. I've ran a var_dump on the avatar directory and it always returns as bool(false). I'm not sure why. I tested the code below and it gets to the file exists but it proves the if statement false everytime. Any thoughts? I have looked and the image is in the directory correctly.
$default_avatar = 'default.jpg';
$avatar_directory = base_url() . 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists($avatar))
{
$user_data->avatar = $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
$default_avatar = 'default.jpg';
$avatar_directory = 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists(FCPATH . $avatar))
{
$user_data->avatar = base_url() . $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = base_url() . $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
from the name base_url seems like a function that will get a url like http://www.mysite.com, which will not work for doing local directory functions.
you need something like getcwd, or a full path
getcwd will get the current working directory (the directory where the initial script was executed from):
//If say script.php was exectued from /home/mysite/www
$avatar_directory = getcwd() . '/assets/globals/images/avatars/';
//$avatar_directory would be
/home/mysite/www/assets/globals/images/avatars/
Well this works both CLI and via Apache etc...:
$avatar_directory = substr(str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', __FILE__), 0, -1) . '/assets/globals/images/avatars/'
The did returned is the one that the php file itself is in, not the root.
assuming you meant base_url() to point to the root of your project -
$file = __DIR__ . "/path/to/file.ext";
if (file_exists($file)) {
//...
}
Or some variation thereof. This also works:
__DIR__ . "/.."
it resolves to the parent directory of __DIR__.
see PHP's magic constants:
http://php.net/manual/en/language.constants.predefined.php
If you are looking for a remote resource - a file not located on your local filesystem - you have to change your php.ini to permit that. And it's probably not a good idea, this is not usually considered safe or secure. At all.
http://php.net/manual/en/features.remote-files.php
And note:
"This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir."
-- from http://php.net/manual/en/function.file-exists.php
-- edited to add relevant information based on a comment from OP.
I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas?
Broken code or a better way of doing it (that works!)?
Beside #hek2mgl answer which i think is correct, i also think you should switch to is_file() instead of file_exists().
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== #getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== #getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png instead of http://locathost/blah/images/image.png
You missed the directory separator / between path and filename. Add it:
if (file_exists(realpath(dirname(__FILE__) . '/' . $user_image))) {
Note that dirname() will return the directory without a / at the end.
I tryed to use file_exists(URL/robots.txt) to see if the file exists on randomly chosen websites and i get a false response;
How do i check if the robots.txt file exists ?
I dont want to start the download before i check.
Using fopen() will do the trick ? because : Returns a file pointer resource on success, or FALSE on error.
and i guess that i can put something like:
$f=#fopen($url,"r");
if($f) ...
my code:
http://www1.macys.com/robots.txt
maybe it's not there
http://www.intend.ro/robots.txt
maybe it's not there
http://www.emag.ro/robots.txt
maybe it's not there
http://www1.bloomingdales.com/robots.txt
maybe it's not there
try {
if (file_exists($file))
{
echo 'exists'.PHP_EOL;
$curl_tool = new CurlTool();
$content = $curl_tool->fetchContent($file);
//if the file exists on local disk, delete it
if (file_exists(CRAWLER_FILES . 'robots_' . $website_id . '.txt'))
unlink(CRAWLER_FILES . 'robots_' . $website . '.txt');
echo CRAWLER_FILES . 'robots_' . $website_id . '.txt', $content . PHP_EOL;
file_put_contents(CRAWLER_FILES . 'robots_' . $website_id . '.txt', $content);
}
else
{
echo 'maybe it\'s not there'.PHP_EOL;
}
} catch (Exception $e) {
echo 'EXCEPTION ' . $e . PHP_EOL;
}
file_exists cannot be used on resources on another websites. It's intended for local filesystem. Have a look here on how to perform the check properly.
As other have mentioned in the comments and as the link says it's (probably) easiest to use get_headers function to do this:
try {
if (strpos(get_headers($url,1),"404")!==FALSE){
... your code ...
} else {
... you get the idea ...
}
}
Just to second what other people said,
it's best to use cURL in php to find out if that http://example.com/robots.txt returns a 404 status code. If it does, then the file does not exist. If it returns a 200 it means it exists.
Be wary of custom 404 pages though, I'm never looked to find out what they return.
The http:// wrapper does not support stat() functionality, which file_exists() needs; you will need to check the HTTP response code from e.g. cURL.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
I'm a newbie that really needs help, been trying to make this php script work with no luck, when I'm running the site locally it works but after I move the files to the server Im getting the following error, hope someone can help me:
Warning: include(/var/chroot/home/content/16/5976816/html/inc/header.php) [function.include]: failed to open stream: No such file or directory in /home/content/16/5976816/html/vtr/test/index.php on line 49
This is the scrip that I'm using:
<?php
// Include the header:
include($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php');
?>
<div id="contents">
<div id="content">
<?php
// Define our array of allowed $_GET values
$pass = array('intro','about','vincent-tran','philip-roggeveen','estate-planning','criminal-case','personal-injuries','bankruptcy','inmigration','deportation','family-law','litigation','corporations-and-llcs', 'payments','consultation','request-callback','contact-us');
// If the page is allowed, include it:
if (in_array($_GET['id'], $pass)) {
include ($_SERVER['DOCUMENT_ROOT'] . '/inc/' . $_GET['id'] . '.php');
}
// If there is no $_GET['id'] defined, then serve the homepage:
elseif (!isset($_GET['id'])) {
include ($_SERVER['DOCUMENT_ROOT'] . '/inc/intro.php');
}
// If the page is not allowed, send them to an error page:
else {
// This send the 404 header
header("HTTP/1.0 404 Not Found");
// This includes the error page
include ($_SERVER['DOCUMENT_ROOT'] . '/inc/error.php');
}
?>
</div>
</div>
<!-- end OutsideWrap-->
<?php
// Include the footer:
include($_SERVER['DOCUMENT_ROOT'] . '/inc/footer.php');
?>
The error shows that the file you want to include could not be found.
Make sure that:
you are specifying the correct path
directory has right permissions, chmod to 755
You can check the resolved path by echoing it:
echo $_SERVER['DOCUMENT_ROOT'] . '/inc/header.php';
And as far as I can remember, you don't need / after $_SERVER['DOCUMENT_ROOT']
if (strpos($system_folder, '/') === FALSE)
{
if (function_exists('realpath') AND #realpath(dirname(__FILE__)) !== FALSE)
{
$system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
}
}
else
{
// Swap directory separators to Unix style for consistency
$system_folder = str_replace("\\", "/", $system_folder);
}
here's a function that gets the base directory of your application
just replace $system_folder with your site's folder name like if that is on htdocs/somewebapp
$systemfolder = "somewebapp";
Thank you guys for all your help, I wasn't using the correct path.
<?php
// Define our array of allowed $_GET values
$pass = array('intro','about','vincent-tran','philip-roggeveen','estate-planning','criminal-case','personal-injuries','bankruptcy','inmigration','deportation','family-law','litigation','corporations-and-llcs', 'payments','consultation','request-callback','contact-us');
// If the page is allowed, include it:
if (in_array($_GET['id'], $pass)) {
include ($_SERVER['DOCUMENT_ROOT'] . '/vtr/today/inc/' . $_GET['id'] . '.php');
}
// If there is no $_GET['id'] defined, then serve the homepage:
elseif (!isset($_GET['id'])) {
include ($_SERVER['DOCUMENT_ROOT'] . '/vtr/today/inc/intro.php');
}
// If the page is not allowed, send them to an error page:
else {
// This send the 404 header
header("HTTP/1.0 404 Not Found");
// This includes the error page
include ($_SERVER['DOCUMENT_ROOT'] . '/vtr/today/inc/error.php');
}
?>
Now is working just fine.