Use realpath() for both files and images - php

I have a directory tree like the below
root
index.php
/inc
1levelData.php
1level.php
/images
db.png
What I am trying to figure out is a way I can set an absolute path that can be used for both including files and images. In addition, a method that will work when loading both index.php as well as root\inc\1level.php I have put in some sample code below for what I am currently working with. This code seems to work well for include() but doesn't function for images. Is there a possible fix?
root/Index:
<?php
$fullPath = realpath($_SERVER['DOCUMENT_ROOT']);
echo "<img src = '".$fullPath."/inc/images/db.png'><BR>";
include $fullPath.'/inc/1levelData.php';
?>
root/inc/1levelData.php
<?php
echo "<img src = '".$fullPath."/inc/images/db.png'><BR>";
include ($fullPath.'/inc/images/2levelData.php');
?>
root/inc/1Level.php
<?php
$fullPath = realpath($_SERVER['DOCUMENT_ROOT']);
include ($fullPath.'/phpinfo.php');
?>
root/inc/2LevelData.php
<?php
echo "<img src = '".$fullPath."inc/images/db.png'><BR>";
?>

Related

Get image from PHP displaying using an img src

The code I have should output a jpg from a list of files in a directory however it is not. I have trawled this site and tried different methods but not helped. I am a relative beginner at php so looking for any help at all.
I have tried using img src in the php code but I am trying to get the image to display within a Wordpress post so I cannot echo the img src within the script. I have tried file_get_contents and read file as well but it may be my lack of knowledge holding me back.
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);
define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );
If(LOCALHOST){
define('PATH_IMAGES', 'this_path');
}else{
define('PATH_IMAGES', '../../../Images/');
}
$arrnum = $GLOBALS[imagenum] - 1;
$dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
$images = scandir($dirname);
rsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
header('Content-type: image/jpeg');
file_get_contents('$dirname$images[$arrnum]');
}
}
?>
Have you tried readfile(...); should read and output the file. In your example you are not outputting the image data
http://php.net/manual/en/function.readfile.php

Calling external php function in <img>

I've created an external php file (sort.php) that sorts the files in a folder on the server by time modified, and returns the most recent file.
<?php
function scanDir ($dir){
$fileTimeArray = array();
// Scan directory and get each file date
foreach (scandir($dir) as $fileTime){
$fileTimeArray[$fileTime] = filemtime($dir . '/' . $fileTime);
}
//Sort file times
var $latestFile = arsort($fileTimeArray);
return($latestFile[0]);
}
?>
I'm attempting to call this function inside of , in another php file, and set the src:
<img <?php echo 'src="'.scanDir("issues/preview").'"';?>/>
I've included sort.php at the top of the page in question.
The image src reads "(unknown)". What am I missing or doing wrong or both?
Thank you!
I would write
<?php $x = scanDir("issues/preview"); ?>
<img src="<?php echo $x; ?>"/>

Variables not propagating to PHP include file

I have a file called index.php and in this file there is a variable called $mainDir, I would like this variable to be used in the file that is included,
Example:
<?php // index.php
$mainDir = dirname(__FILE__);
if ($isTest){ // presume this is true
include $mainDir . 'test.php';
}
?>
// Different File:
<?php // test.php
echo $mainDir;
?>
I have looked at the other solutions and I have placed the variable I want before the include statement and the include statement is being called properly, it just gives me a warning that the variable that I want to use in the included file is not set.
dirname(__FILE__); doesn't include a "/" at the end I believe. To fix this, simply use this as your include:
include $mainDir.'/test.php';
Maybe you can try this :
<?php // index.php
$mainDir = dirname(__FILE__);
if ($isTest){ // presume this is true
include $mainDir . 'test.php';
}
$_GET["mainDir"] = $mainDir;
?>
// Different File:
<?php // test.php
echo $_GET["mainDir"];
?>
it's horrible but it should works.

CodeIgniter doesn't see images (using file_exists)

I'm learning CodeIgniter. I have a directory img with images (path /img/). I am trying to access it through CI view and check if exists with this code:
$av = '../../../img/content/users/'.$userID.'.jpg';
if(file_exists($av)) {
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works. What should I do?
CI always runs on index.php, so paths are always relative from there.
Assuming index.php and /img are at the same level in the root, try this:
$av = 'img/content/users/'.$userID.'.jpg';
if(is_file($av)) { // or better yet, make sure it's really an image
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works
It's because the browser is looking in a different place than the server. I'd recommend not using ../../relative/paths but using functions like base_url() and img(). When there are additional segments in the URL, relative paths break.
URLs and file paths are not the same. From the current URL ../../../img/content/users may and likely is something completely different than the file path on the hard disk where the view file is located.
Use following steps
1) Create a custom config file name site_config.php in config file (/application/config/) and paste following code
<?php
$config['base_url'] = "http://".$_SERVER['SERVER_NAME'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
if(!defined('DOCUMENT_ROOT')) define('DOCUMENT_ROOT',str_replace('system/application/config','',substr(__FILE__, 0, strrpos(__FILE__, '/'))));
$config['base_path'] = constant("DOCUMENT_ROOT");
?>
2) Edit autoload.php to autoload site_config.php (/application/config/autoload.php)
$autoload['config'] = array('site_config');
3) Then using following code to view image
$image_path = $this->config->item('base_path').'folder_name/'.$userID.'.jpg';
if(file_exists($image_path)) {
$avatar = $this->config->item('base_url').'folder_name/'.$userID.'.jpg';
} else {
$avatar = $this->config->item('base_url').'default_folder_name/profile.jpg';
}
echo '<img src="'.$avatar.'" />';
I think it will help you
Try this:
$av = './img/content/users/'.$userID.'.jpg';

printing a UL from an array of images

I am trying to print a UL list of images ending with _th.jpg returned from a specific folder. All i get back is array()
<?php
require '../../config.php';
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);
$id = (int)$_GET['id'];
$q = $conn->query("SELECT * FROM cms_page WHERE id=$id");
$project = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
$imagesDir = 'public/images/portfolio/'.$project['slug'].'/';
$images = glob($imagesDir . '*_th.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo $imagesDir ;
print_r($images);
?>
<h1><?=htmlspecialchars($project['title'])?></h1>
<?php
if ($images < 1) {
echo '<div id="slider">';
echo '<ul>';
foreach($images as $key => $value) {
echo '<li><img src="public/images/portfolio/'.$project['title'].'/'.$value.'.jpg" width="160" height="96" /></li>';
}
echo '</ul>';
echo '</div>';
} else {
echo 'There are currently no images to display for tihis project.';
}
?>
Anyone got any ideas?
First of all : are you sure you are reading from the right directory ?
What I mean, is : does 'public/images/portfolio/'.$project['slug'].'/' really exist, and is accessible from your script, using this relative path, in this PHP script ?
(You can test that with is_dir, for instance)
As a precaution, when working with files and directories, I like using absolute paths, so I always know to which directory exactly I'm accessing.
For instance, something like this :
$imagesDir = '/var/www/public/images/portfolio/'.$project['slug'].'/';
If you do not know the absolute path to your directories, you can use dirname(__FILE__), to get the absolute path to the current PHP file -- and then, starting from that file, use a relative path ; for instance :
$imagesDir = dirname(__FILE__) . '/public/images/portfolio/'.$project['slug'].'/';
This way, you don't have to care about the current working directory : your path will always be the same, as it's not relative.
If that doesn't work, then first of all, make sure you are accessing the right directory.
<h1><?=htmlspecialchars($project['title'])?></h1>
Is <? a valid PHP opening tag?
Since your last block of PHP code isn't apparently executed (since it would either print an empty ul or the text from the else block) I suspect the PHP doesn't get parsed correctly.

Categories