I am attempting to create code that checks if an image exists on my site and if not shows a default image. In one case I know the file exists and can get it to link to the file using the variable that I want file_exist to use!
$menuCategories = get_categories( array(
'child_of' => $whichGrade,));
foreach ( $menuCategories as $menuCategory ) { ?>
<?php
$linktoicon = get_bloginfo('template_directory') ."/images/menuicon_".$menuCategory->slug.".png";
if (file_exists($linktoicon)) {
$iconref = $menuCategory->slug;
}else {
$iconref = "default";
} ?>
<a href='<?php echo $linktoicon; ?>'> <?phpvar_dump($iconref); ?></a>
<?php }?>
$linktoicon` is "http://mybritishhelper.com/wp-content/themes/wpex-magtastico/images/menuicon_colours.png"
Thank you.
PHP's file_exists isn't used with URL's, it's used for paths to files on the server itself. Not a problem. First, we need to get the path to your theme's template directory:
$templateDirectory = get_template_directory();
Assuming that the link you provided is on your own server, the full path to your image is
$pathToImage = $templateDirectory . '/images/menuicon_colours.png';
We can now check if your image exists with the following
if (file_exists($pathToImage)) {
// Do stuff
}
Hope this helps. For reference, see the docs for file_exists and get_template_directory()
Related
I'm having a very strange issue. All I want to do is get the thumbnail url and assign it to a variable. Here is my code.
<?php /* Template for displaying content of MH Posts Large widget */ ?>
<article class="post-<?php the_ID(); ?> mh-posts-large-item">
<figure class="mh-posts-large-thumb">
<?php
$form_image = 'blank';
if (has_post_thumbnail()) {
$form_image = the_post_thumbnail_url('mh-magazine-lite-content');
?>
Basically, if the post has a thumbnail I want to store the actual URL of the thumbnail used in that variable for later use. However, instead of doing that it just prints the URL on screen and doesn't actually seem to put it in the variable.
I don't understand why and I would definitely appreciate any help! :)
Looking at the official documentation:
function the_post_thumbnail_url( $size = 'post-thumbnail' ) {
$url = get_the_post_thumbnail_url( null, $size );
if ( $url ) {
echo esc_url( $url );
}
}
So the_post_thumbnail_url only outputs the URL it gets from get_the_post_thumbnail_url and doesn't return anything. Thus the solution is to use get_the_post_thumbnail_url directly.
Hello I'm trying to send a value from my php file to tpl file.
when I print_r in php file I see my value is defined in array however when I print_r my tpl file I don't see this element.
<img src="{$product.manufacturer_name}" alt="" title="" itemprop="image" />
and my controller
$special = Product::getProducts((int)$this->langID , 0,6, 'name', 'DESC', 51);
foreach ($special as $specia)
{
$id_image = Product::getCover($specia['id_product']);
// get Image by id
if (sizeof($id_image) > 0)
{
$image = new Image($id_image['id_image']);
// get image full URL
$image_url = _PS_BASE_URL_._THEME_PROD_DIR_.$image->getExistingImgPath()."-home_default.jpg";
$specia['manufacturer_name']=$image_url;
}
}
$dir = _PS_MODULE_DIR_.'/ptspagebuilder/views/templates/front/widgets/sub/products.tpl';
$tdir = _PS_ALL_THEMES_DIR_ . _THEME_NAME_ . '/modules/ptspagebuilder/views/templates/front/widgets/sub/products.tpl';
if (file_exists($tdir)) {
$dir = $tdir;
}
// get Product cover image (all images is possible retrieve by
// Image::getImages($id_lang, $id_product) or
// $productInstance->getImages($id_lang))
$setting['product_tpl'] = $dir;
$setting['products'] = $special;
$output = array('type' => 'flashsale','data' => $setting);
return $output;
}
if $special contain arrays, than you have mistake in script, change copies of vars in foreach loop. Try to change
foreach ($special as $specia) to foreach ($special as $k=>$specia)
$specia['manufacturer_name']=$image_url; to $special[$k]['manufacturer_name']=$image_url;
Actually i didn't get your problem. You said that you assigned value in your php file but i can't see any value which is assigned. For assigning value in php file you have to assign value in smarty variable so that you can access it in your tpl file. For that you have to write code something like that:
In your controller first You have to assigned value like:
$this->smarty->assign(array(
'product' => $containing_product,
));
The $product contain the value which you want to access in your tpl file.
Now in your tpl file you can check it like:
{var_dump($product)}
And Now in your tpl file you can use that
<img src="{$product}" alt="" title="" itemprop="image" />
I have a script that echo's usernames an inserts that into img src. This works great as long as the image is in the directory. How can I create an if statement that only echos the below command if the file exist? If it doesn't exist show default.png
I tried using mod_rewrite and have had zero luck with it..
<div class="contactphoto"><img src="contactphoto/<? echo ($note['user_name'] == "Support")? $note['first_name'].''.$note['last_name'] : $note['user_name'];?>.png"/></div>
The name says it all: file_exists()
I think this is what you want.
<?php
$file = ($note['user_name'] == "Support") ? $note['first_name'].''.$note['last_name'] : $note['user_name'];
$file .= '.png';
if(!file_exists($_SERVER{'DOCUMENT_ROOT'} .'/'.$file)){
$file = 'placeholder.png';
}
?>
<div class="contactphoto">
<img src="contactphoto/<?php echo $file; ?>"/>
</div>
If that fails, try a test ( this should match the path of the image ) also watch out for case sensitivity:
echo $_SERVER{'DOCUMENT_ROOT'} .'/'.$file;
M getting this :
<img alt="" }}="" es_3.jpg="" wysiwyg="" src="{{media url=">
In my form i added this code
$wysiwygConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig(
array('tab_id' => 'form_section')
);
$wysiwygConfig["files_browser_window_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg_images/index');
$wysiwygConfig["directives_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg/directive');
$wysiwygConfig["directives_url_quoted"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg/directive');
$wysiwygConfig["widget_window_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/widget/index');
$wysiwygConfig["files_browser_window_width"] = (int) Mage::getConfig()->getNode('adminhtml/cms/browser/window_width');
$wysiwygConfig["files_browser_window_height"] = (int) Mage::getConfig()->getNode('adminhtml/cms/browser/window_height');
$plugins = $wysiwygConfig->getData("plugins");
$plugins[0]["options"]["url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/system_variable/wysiwygPlugin');
$plugins[0]["options"]["onclick"]["subject"] = "MagentovariablePlugin.loadChooser('".Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/system_variable/wysiwygPlugin')."', '{{html_id}}');";
$plugins = $wysiwygConfig->setData("plugins",$plugins);
$fieldset->addField('longdescription', 'editor', array(
'name' => 'longdescription',
'label' => Mage::helper('press')->__('Description'),
'title' => Mage::helper('press')->__('Description'),
'style' => 'width:500px; height:300px;',
'config' => $wysiwygConfig,
));
I m still not clear about the above code but i copied it from somewhere,But i do know that it enables to browse for images files instead of writing custom url.
After that i just call it in frontend like this:
<?php echo $item["longdescription"]; ?>
I am getting the text , but not the image and for image i am getting the broken link mentioned at top.
Am i missing something ?? if yes then what ?
add this code :
<?php $_cmsHelper = Mage::helper('cms');?>
<?php $_process = $_cmsHelper->getBlockTemplateProcessor();?>
<?php echo $_process->filter($item["longdescription"]); ?>
It looks like you might be breaking on quotes somewhere, how are you passing in the image/url of the image? If you look right here: alt="" }}="" es_3.jpg="" you can see that you are passing in closing brackets somewhere, and are skipping the SRC entirely. Try VAR_EXPORTing the $item and show me what you have.
I had the same problem today. It turns out that Mage_Adminhtml_Cms_WysiwygController::directiveAction() tries to create an image according to a url. This function calls Varien_Image_Adapter_Gd2::open() which in turn tries to open the file. This is where it goes wrong:
The image adaptor tries to get information about the image, like image size and mime type. But... when your site is on a localhost or a vagrant box or something like that, the sever tries to getimagesize('http://www.domain.com/image.jpg') instead of getimagesize('/Users/john/sites/domain.com/image.jpg') (for example).
The fix for this is to override the directiveAction() in your own module to add another catch before throwing an exception:
public function directiveAction()
{
$directive = $this->getRequest()->getParam('___directive');
$directive = Mage::helper('core')->urlDecode($directive);
$url = Mage::getModel('core/email_template_filter')->filter($directive);
try {
$image = Varien_Image_Adapter::factory('GD2');
$image->open($url);
$image->display();
} catch (Exception $e) {
// Try to get an absolute path:
$path = Mage::getBaseDir().'/'.preg_replace('/http:\/\/(.*)\//Ui', '', $url);
$image = Varien_Image_Adapter::factory('GD2');
$image->open($path);
$image->display();
} catch (Exception $e) {
$image = Varien_Image_Adapter::factory('GD2');
$image->open(Mage::getSingleton('cms/wysiwyg_config')->getSkinImagePlaceholderUrl());
$image->display();
}
}
A nice little bonus: the broken links in your admin are now gone too! ;-)
Please advise me, what wrong with my following code:
<a href="<?php echo $_url; ?>" title="<?php echo $_name; ?>">
<?php
$logo2 = $_url.'/image/data/logo2.png';
$logo = $_url.'/image/data/logo.png';
if (file_exists($logo2)) {
echo "<img src=".$logo2." alt=\"Logo\" style=\"border: none;\" />";
} else {
echo "<img src=".$logo." alt=\"Logo\" style=\"border: none;\" />";
} ?>
</a>
both images of $logo2 and $logo exists in the same directory, but the code only shows $logo (logo.png)
I need pointers and thanks in advance
UPDATED:
the value of $_url is
$this->data['_url'] =
$this->config->get('config_url');
and when i <?php echo $_url;?> that will show e.g. http://www.mysite.com
by using code at above only show logo.png
file_exists can be used for URL wrapper.
In your case, if you really need to perform URL wrapper checking (will be very slow), make sure URL wrapper is enabled (default is enabled).
And also, your $_url = http://www.mysite.com///image/data/logo2.png, take note the extra slash may affecting web server rewrite.
If the file is located at the same server as your web server, you should replace the $_url to document_root (path to the folder).
For function wise, file_exists return true for directory too. You should replace that to is_file
You are applying file_exists() to a URL which doesn't work.
You need to apply it to a filesystem path.
file_exists expects a local path, not a url.
Contrary to some answers here, file_exists can take an URL as a parameter and it will check whether it exists or doesn't. However, you're still better off using a filesystem path for file_exists instead of the URL.
Anyway, two reasons immediately come to mind:
Do both files have the same permissions? (I.e., logo.png might have the necessary read permissions and logo2.png might not have them)
Are the file names really the same as in the script? For example, everything might work fine on your development platform - a Mac or Windows which ignores letter case for filenames but not on a Linux server where the filename must be in the same case.
Use getimagesize() as file_exists will return false.
<a href="<?php echo $_url; ?>" title="<?php echo $_name; ?>">
<?php
$logo2 = $_url.'/image/data/logo2.png';
$logo = $_url.'/image/data/logo.png';
if (getimagesize($logo2)) {
echo "<img src=".$logo2." alt=\"Logo\" style=\"border: none;\" />";
} else {
echo "<img src=".$logo." alt=\"Logo\" style=\"border: none;\" />";
} ?>
</a>