CodeIgniter doesn't see images (using file_exists) - php

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';

Related

Summernote and absolute path in the img-upload.php file

I'm using summernote as the text editor in a backend. The text and images stored must then be displayed in the pages of the frontend.
The editor and the upload images works, but the problem is to recover the images in the frontend because of the path.
I need to use the absolute path in the img-upload.php file but it doesn't seem to accept it.
img-upload.php
if(empty($_FILES['file']))
{
exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
echo $errorImgFile;
}
else{
echo $destinationFilePath;
}
with the relative path works:
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
but in this way not:
$path = 'http://localhost/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
I don't see any error.
Thanks
You have probably figured it out by now...
It seems Summernote does not render images from absolute paths, but the closest you can get is to specify the file from the root path, like:
$path = '/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
Results in something like: '/sites/my-site/images/img-uploads/filename.jpg'
If you save this to your database, you can render your images anywhere on your site using this rooth path address for the files.
I suggest you to use Ckfinder or Fileman with Ckeditor. I made a repository for that. Go check it out.
https://github.com/senocak/Laravel-CKEDITOR-CKFINDER-usage

PHP Search for image file in two specific directories

I need to look for and echo an image file name that's located in either of these two directories named 'photoA' or 'photoB'.
This is the code I started with that tries to crawl through these directories, looking for the specified file:
$file = 'image.jpg';
$dir = array(
"http://www.mydomain.com/images/photosA/",
"http://www.mydomain.com/images/photosB/"
);
foreach( $dir as $d ){
if( file_exists( $d . $file )) {
echo $d . $file;
} else {
echo "File not in either directories.";
}
}
I feel like I'm way off with it.
You cannot use a url in file_exists, you need to use an absolute or relative path (relative to the runnings script) in the file-system of the server, so for example:
$dir = array(
"images/photosA/",
"../images/photosB/",
"/home/user/www/images/photosB/"
);
You can also use paths relative to the root of the web-server if you don't know the exact path and add the document root before that:
$dir = array(
$_SERVER['DOCUMENT_ROOT'] . "/images/photosA/",
$_SERVER['DOCUMENT_ROOT'] . "/images/photosB/"
);
(or you use it once, where you use file_exists())
Since you are running this script from within the root directory of your website, you won't need to define 'http://www.mydomain.com/' as this will cause Access Denied issues as it is not an absolute/relative file path. Instead, if the images/ folder is at the same directory level as your PHP script, all you will need to do is
$dir = array(
"images/photosA/",
"images/photosB/"
);
Otherwise, just add the absolute path as needed to make it work, but you can not put the. The rest seems as if it should work fine.
As the others said, file_exists() is for local files.
If you REALLY need to look for files over http, you can use :
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
NOTE: This relies on the server returning a 404 if the image does not exist. If the server instead redirects to an index page or a pporly-coded error page, you could get a false success.

Check if file exists before displaying in Magento PHP?

I am able to get the web path to the file like so:
$filename = 'elephant.jpg';
$path_to_file = $this->getSkinUrl('manufacturertab');
$full_path = $path_to_file . '/' . $filename;
But if the file doesn't exist, then I end up with a broken image link.
I tried this:
if(!file_exists($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_path ?>" /><?php
}
Of course that didn't work because file_exists does not work on urls.
How do I solve this?
1.)
Can I translate between system paths and web urls in Magento?
e.g. something like (pseudocode):
$system_path = $this->getSystemPath('manufacturertab');
That looks symmetrical and portable.
or
2.)
Is there some PHP or Magento function for checking remote resource existence? But that seems a waste, since the resource is really local. It would be stupid for PHP to use an http method to check a local file, wouldn't it be?
Solution I am currently using:
$system_path = Mage::getBaseDir('skin') . '/frontend/default/mytheme/manufacturertab'; // portable, but not pretty
$file_path = $system_path . '/' . $filename;
I then check if file_exists and if it does, I display the img. But I don't like the asymmetry between having to hard-code part of the path for the system path, and using a method for the url path. It would be nice to have a method for both.
Function
$localPath = Mage::getSingleton( 'core/design_package' )->getFilename( 'manufacturertab/' . $filename, array( '_type' => 'skin', '_default' => false ) );
will return the same path as
$urlPath = $this->getSkinUrl( 'manufacturertab/' . $filename );
but on your local file system. You can omit the '_default' => false parameter and it will stil work (I left it there just because getSkinUrl also sets it internaly).
Note that the parameter for getSkinUrl and getFilename can be either a file or a directory but you should always use the entire path (with file name) so that the fallback mechanism will work correctly.
Consider the situation
skin/default/default/manufacturertab/a.jpg
skin/yourtheme/default/manufacturertab/b.jpg
In this case the call to getSkinUrl or getFilename would return the path to a.jpg and b.jpg in both cases if file name is provided as a parameter but for your case where you only set the folder name it would return skin/yourtheme/default/manufacturertab/ for both cases and when you would attach the file name and check for a.jpg the check would fail. That's why you shold always provide the entire path as the parameter.
You will still have to use your own function to check if the file exists as getFilename function returns default path if file doesn't exist (returns skin/default/default/manufacturertab/foo.jpg if manufacturertab/foo.jpg doesn't exist).
it help me:
$url = getimagesize($imagepath); //print_r($url); returns an array
if (!is_array($url))
{
//if file does not exists
$imagepath=Mage::getDesign()->getSkinUrl('default path to image');
}
$fileUrl = $this->getSkinUrl('images/elephant.jpg');
$filePath = str_replace( Mage::getBaseUrl(), Mage::getBaseDir() . '/', $fileUrl);
if (file_exists($filePath)) {
// display image ($fileUrl)
}
you can use
$thumb_image = file_get_contents($full_path) //if full path is url
//then check for empty
if (#$http_response_header == NULL) {
// run check
}
you can also use curl or try this link http://junal.wordpress.com/2008/07/22/checking-if-an-image-url-exist/
Mage::getBaseDir() is what you're asking for. For your scenario, getSkinBaseDir() will perform a better job.
$filename = 'elephant.jpg';
$full_path = Mage::getDesign()->getSkinBaseDir().'/manufacturertab/'.$filename;
$full_URL=$this->getSkinUrl('manufacturertab/').$filename;
if(!is_file($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_URL ?>" /><?php
}
Note that for the <img src> you'll need the URL, not the system path. ...
is_file(), rather than file_exists(), in this case, might be a good option if you're sure you're checking a file, not a dir.
You could use the following:
$file = 'http://mysite.co.za/files/image.jpg';
$file_exists = (#fopen($file, "r")) ? true : false;
Worked for me when trying to check if an image exists on the URL

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.

PHP's file_exists() will not work for me?

For some reason this PHP code below will not work, I can not figure it out.
It is very strange,
file_exists does not seem to see that the image does exist, I have checked to make sure a good file path is being inserted into the file_exists function and it is still acting up
If I change file_exists to !file_exists it will return an images that exist and ones that do not exist
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($thumb_name)) {
$img_name = $thumb_name;
}else{
$img_name = $noimg;
}
echo $img_name;
file_exists() needs to use a file path on the hard drive, not a URL. So you should have something more like:
$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($thumb_name)) {
some_code
}
http://us2.php.net/file_exists
docs say:
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.
file_exists does only work on the local file system.
So try this if you’re using localhost:
$thumb_name = 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($_SERVER['DOCUMENT_ROOT'].$thumb_name)) {
$img_name = SITE_PATH2.$thumb_name;
} else {
$img_name = $noimg;
}
Have you enabled the option which allows you to use external URLs? You can set it in php.ini:
allow_url_fopen = 1
You have to write the file path like "file:///C:/Documents%20and%20Settings/xyz/Desktop/clip_image001.jpg".
http://php.net/manual/en/function.file-exists.php
did you check the comments below?
Just reading parts of it, but there seem to be several issues.
Caching may be a problem.
When opening FTP urls it always returns true (they say in the comments)
...
Try Below one. Its working for me
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if ($fileopen = #fopen($thumb_name)) {
$img_name = $thumb_name;
fclose($fileopen);
}else{
$img_name = $noimg;
}
echo $img_name;

Categories