I have a method in a class I would like to use in order to show an image in a page that could be placed in any directory.
Basically, the class file would be at the root directory and the class would look like this:
class A{
function showImage(){
echo '<img src="img/file.jpg">';
}
}
Problems occur when I call the method in a page which is in a subdirectory.
For example, if I use showImage() in 'subdir/mypage.php', then the image link is broken.
I have looked into $_SERVER['HTTP_HOST'] and dirname(__FILE__) but I coud not find the right mix to get the right image path that could be used in order to show the image from any directory.
What function should I used in the class to get the file path dynamically that would depending on the directory where I am calling showImage()?
Many thanks
class A{
function showImage($link){
$link = str_replace('/home/public', '', $link);
echo '<img src="' . $link . '">';
}
}
and use it like this:
$a->showImage(getcwd().'/img/file.jpg');
The getcwd() will get the directory, then remove the first absolute path to your public folder in the function.
Example case:
test.php is placed in /home/public/images/{test.php}
class.php is placed in /home/public/{class.php}
test.php does:
$a->showImage(getcwd().'/img/file.jpg');
What it'll send to class.php is:
$a->showImage('/home/public/images/img/file.jpg');
Then in your function it'll remove /home/public and show this link:
<img src="/images/img/file.jpg">
MY BAD
I didn't read the answer right. Here's the solution you're looking for:
class A{
function showImage(){
$root = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
echo '<img src="' . $root . 'img/file.jpg">';
}
}
Related
<script src='<?php base_url();?>assets/js/jquery.min.js'></script>
the script above is code that my friend use, that works just for him, but if i change it to <?php echo base_url();?> and it's work for me, not for him. It's become a problem when we transfer files each other, What i am supposed to do ?
thank you.
I've solution script for my case, change this from config.php :
$http = 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://';
$urlbaru = str_replace("index.php","", $_SERVER['SCRIPT_NAME']);
$config['base_url'] = "$http" . $_SERVER['SERVER_NAME'] . "" . $urlbaru;
Please show more about your problem detail like paste your error code in here that we could use those information to help you.
Btw, base_url() isn't a php embedded function, one of the potential problem is that your friend custom a function named base_url() that supposed to return it's root path.
So, you have to either include or build the same function with the same name to your script.
Ex.
function base_url()
{
return dirname($_SERVER['SCRIPT_FILENAME']);
}
And the 'src' inside your tag should point to your jQuery source file.
Looks like you are using codeigniter framwork, and you have not autoloaded URL helper, that's why you getting error. if I am not wrong you have to load URL helper.
I am trying to delete pdf files from a folder. I have written the delete_files function as follows
public function delete_files($company_id)
{
$this->load->model('search_model');
$company = $this->search_model->get_company($company_id);
$username = $company[0]['username'];
$path=$this->config->base_url('/uploads/'.$username . '/' . 'uploaded');
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
}
when i did echo $path; it shows the right path where i want the files deleted but when i run the entire function nothing happens and i just get a white screen.
You need to use path to file and not resource locator.
$path = FCPATH . "uploads/$username/uploaded";
try this code
Use
$path = FCPATH . "uploads/$username/uploaded";
unset($path);
Sometime I have to use include_once and include it depend how the page are accessed. For example:
sales.php
include("class/pdoDatabase.php");
include("class/ClassExample.php");
$obj = new ClassExample();
$obj->getNewItem(1);
ClassExample.php
include_once("class/pdoDatabase.php");
class ClassExample {
public function getNewItem($id) { .. }
public function addNew($id) { .. }
}
// Accessing this file directly via Ajax request
if (isset($_POST['AddNew'])) {
$obj = new ClassExample ();
$obj->addNew($_POST['id']);
}
}
If you access to sales.php which will then load include("class/ClassExample.php");, however I have to use include_once in the ClassExample.php because pdoDatabase.php might be already loaded in sales.php.
If you access the file directly to ClassExample.php with POST query, it mean it will have to load the file and create an object.
Problem:
Problem is when you access to ClassExample.php directly - it could not find class/pdoDatabase.php . It work fine when sales.php load class/pdoDatabase.php file
This is not a problem with include_once and include difference. This is a problem with relative paths. Include always uses paths relative to called php file. You have this file structure:
sales.php
[class]
- pdoDatabase.php
- ClassExample.php
when you call sales.php everything is ok, but when you call ClassExample.php it's trying to find class/class/pdoDatabase.php which don't exist.
Change include line in your ClassExample.php
include_once(dirname(__FILE__)."/pdoDatabase.php");
and use the same pattern everywhere.
You are doing it wrong.
Instead of manually loading each class file, you should be using autoloader, that you initialize in bootstrap stage of your application. Something along the lines of:
$root = __DIR__;
spl_autoload_register(function( $className ) use ( $root ){
$className = str_replace( '\\', '/', $className );
$filepath = $root . '/' . strtolower( $className ) . '.php';
if ( !file_exists($filepath) )
{
return false;
}
require $filepath;
return true;
});
To learn more about this, please read about spl_autoload_register() in the manual.
I'm building a script that got a static class used to load few things including files and views.
class load
{
public static function view($file_path, $area)
{
debug::log('getting view <b>' . $area . $file_path . '</b>.');
ob_start();
self::file($file_path, 'areas/' . $area . '/views');
debug::log('flushing view <b>' . $area . $file_path . '</b>.');
eturn ob_get_clean();
}
public static function file($file, $folder)
{
if(is_file($file_path = ROOT . '/' . $folder . '/' . $file))
{
if(require_once $file_path)
{
debug::log('file <b>' . $file_path . '</b> included.');
return true;
}
}
else
debug::kill('requested file <b>' . $file_path . '</b> does not exist.');
}
}
In the controller Im calling the view method to get a view:
$html = load::view('public', 'path/to/view/file.php');
Obviously, Im not able to access the variables from the controller at the view file using this practice, so I did a small modification on the view class to capture the vars:
public static function view($file_path, $area, $vars = array())
And added the following lines of codes to get the keys into vars:
while(list($n_list_var,$v_list_var)=each($vars))
$$n_list_var = $v_list_var;
But again I can't access the vars since Im using a method to load a file.
I have a method to load the files because I wanna test and log each file include attempt and not repeat the code every time I need include a file. And I have the loader view inside the loader class so I have all the methods of this kind together. Should I give up on using a class to load files? Should I use the loader view method on a extendable class from my controller?
Instead of going ahead and modify my entire script I would like to hear some opinions ... what would be the best practice to go? Or is there a way to solve my problem? Maybe using __set and __get magic methods?
Thanks,
Why not just pass a $vars argument to load::file() and extract( $vars ) (possibly moving the vars you use inside file() into class variables to prevent them from being overwritten)?
I'm suggesting using extract() instead of:
while(list($n_list_var,$v_list_var)=each($vars))
$$n_list_var = $v_list_var;
By the way, it would be a good idea to name your class Load.
In my Product Class, there is a function called pictures() which returns the file address of the picture of a product. It's something like this:
public function picture()
{
$file = "images/pictures/products/" . $this->id . ".png";
if(file_exists($file))
return $file;
else
return false;
}
It works fine when running the code on the administration area of the website (which is located on /admin/ directory)
But when I call this function from the index.php which is not on the /admin/ directory it always returns false. What should I do? The only way I figured to solve this is by creating a parameter on the picture() function, like: picture($directory_prefix) then that way I'll call the function with picture("/admin/"). But there's gotta be a better way than this...
Place your resources in a directory under the web root. Then the path would be:
$file = $_SERVER['HTTP_HOST']."/images/pictures/products/" . $this->id . ".png";