I have been trying to debug this code for a while now, and it looks like the build method is not being called. I put echo's, var_dumps, and all other kinds of signs in it, but never get anything.
Full php code
class Auto_slideshow {
private $_img_dir;
//constructor sets directory containing the images
function __construct($dir) {
//Directory source from webroot
$_img_dir = $dir;
}
//Iterates through directory and constructs HTML img list
public function build() {
//use SPL for directory iteration
$iterator = new DirectoryIterator($_img_dir);
$html = '';
$i = 1;
//Iterate through directory
foreach ($iterator as $file) {
//set a variable to add class of "show" on first element
$showClass = $i === 1 ? ' class="show"' : null;
//exclude '.' and '..' files
if(!$iterator->isDot()) {
//set src attribute for img tag
$src = $_img_dir . $iterator->getFilename();
//Grab sizes of images
$size = getimagesize($_img_dir . $iterator->getFilename());
var_dump($src);
//create img tags
$html .= '<img src="' . $src . '" ' . $size[3] . $displayNone . ' />' . "\r\n";
$i++;
}
}
return $html;
}
}
html call
<center>
<div class="imagecontainer" id="auto-slideshow">
<?php
$show = new Auto_slideshow("../CMSC/images/master/slidestock/");
$show->build();
?>
</div>
</center>
I also tried print $show->build();, as the tutorial showed, which also did not work.
Update
I changed $_img_dir to $this->$_img_dir' and called the method byecho show->build();` and the method still isn't being called.
This is a matter of the method not even running, not even to the point of find the images yet.
Update 2
If I remove the entire php code within the html, the rest of the page loads just fine. As it is now, the html loads only to the div that contains the php then stop everything after it.
Have you used a var_dump() outside of the loop as well?
The problem is that your variable will remain NULL:
//constructor sets directory containing the images
function __construct($dir) {
//Directory source from webroot
// This is a local variable that will be gone when the constructor finishes:
$_img_dir = $dir;
}
You need:
//constructor sets directory containing the images
function __construct($dir) {
//Directory source from webroot
$this->_img_dir = $dir;
^^^^^^ here
}
You return the text you want to display but you don't display it:
echo $show->build();
Fix and update the code bellow:
Constructor:
$this->_img_dir = $dir;
build Function:
$iterator = new DirectoryIterator($this->_img_dir);
$src = $this->_img_dir . $iterator->getFilename();
$size = getimagesize($this->_img_dir . $iterator->getFilename());
You can call it:
echo $show->build();
Related
I have written a function to get a file from S3 and get the number of pages from it. (It's a PDF.) Everything works fine until I try and do the same for multiple files. Now it is just returning the number of pages of the last file. I think that the problem is that local.pdf needs to be deleted or overwritten, but I'm not sure how. I thought it would automatically overwrite it.
I tried using $pdf->cleanUp(); but that doesn't seem to do anything. It is still returning the page count of the last file.
This is the function that gets called for each child job:
public function getPageCountPDF($jobid) {
$this->load->library('Awss3', null, 'S3');
$PdfTranscriptInfo = $this->MJob->getDOCCSPdfTranscript($jobid);
$filename = $PdfTranscriptInfo['origfilename'];
$PdfFilename = 'uploads/' . $jobid . '/' . $filename;
$localfilename = FCPATH . 'tmp\local.pdf';
$this->S3->readfile($PdfFilename, false, 'bucket');
require_once 'application/libraries/fpdi/fpdf.php';
require_once 'application/libraries/fpdi/fpdi.php';
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile($localfilename);
$pdf->cleanUp();
return $pageCount;
}
I am not getting any error messages, but the $pageCount should be 8 and then 6. The return I am getting from the function is 6 and 6.
I also tried adding
ob_clean();
flush();
But that clears the whole page, which I don't want.
I also tried using a generated name instead of local.pdf, but that doesn't work (I get a "cannot open file" message).
EDIT: This is the part that calls the function getPageCountPDF($jobid):
foreach ($copies as $copy) {
.
.
$CI = &get_instance();
$pageCount = $CI->getPageCountPDF($copy['jobid']);
.
.
}
What happens to $pageCount after
$pageCount = $CI->getPageCountPDF($copy['jobid']); ?
This gets overwritten after each iteration. Maybe you want something like $pageCount[$copy['jobid']] = $CI->getPageCountPDF($copy['jobid']); so you actually keep an array of $pageCounts to be processed further down the line.
function get_all_directory_files($directory_path) {
$scanned_directory = array_diff(scandir($directory_path), array(
'..',
'.'
));
return custom_shuffle($scanned_directory);
}
function custom_shuffle($my_array = array()) {
$copy = array();
while (count($my_array)) {
// takes a rand array elements by its key
$element = array_rand($my_array);
// assign the array and its value to an another array
$copy [$element] = $my_array [$element];
// delete the element from source array
unset($my_array [$element]);
}
return $copy;
}
So you can call get_all_directory_files which calls custom_shuffle
Then you can loop through while reading them. In case you want to delete the files
You can proceed with :
$arrayfiles = get_all_directory_files('mypath');
foreach ($arrayfiles as $filename) {
echo 'mypath/'.$filename; //You can do as you please with each file here
// unlink($filename); if you want to delete
}
I am trying to figure out a way of searching through all of the *.php files inside the parent directory, parent directory example:
/content/themes/default/
I am not wanting to search through all of the files in the sub-directories. I am wanting to search for a string embedded in the PHP comment syntax, such as:
/* Name: default */
If the variable is found, then get the file name and/or path. I have tried googling this, and thinking of custom ways to do it, this is what I have attempted so far:
public function build_active_theme() {
$dir = CONTENT_DIR . 'themes/' . $this->get_active_theme() . '/';
$theme_files = array();
foreach(glob($dir . '*.php') as $file) {
$theme_files[] = $file;
}
$count = null;
foreach($theme_files as $file) {
$file_contents = file_get_contents($file);
$count++;
if(strpos($file_contents, 'Main')) {
$array_pos = $count;
$main_file = $theme_files[$array_pos];
echo $main_file;
}
}
}
So as you can see I added all the found files into an array, then got the content of each file, and search through it looking for the variable 'Main', if the variable was found, get the current auto-incremented number, and get the path from the array, however it was always telling me the wrong file, which had nothing close to 'Main'.
I believe CMS's such as Wordpress use a similar feature for plugin development, where it searches through all the files for the correct plugin details (which is what I want to make, but for themes).
Thanks,
Kieron
Like David said in his comment arrays are zero indexed in php. $count is being incremented ($count++) before being used as the index for $theme_files. Move $count++ to the end of the loop, And it will be incremented after the index look up.
public function build_active_theme() {
$dir = CONTENT_DIR . 'themes/' . $this->get_active_theme() . '/';
$theme_files = array();
foreach(glob($dir . '*.php') as $file) {
$theme_files[] = $file;
}
$count = null;
foreach($theme_files as $file) {
$file_contents = file_get_contents($file);
if(strpos($file_contents, 'Main')) {
$array_pos = $count;
$main_file = $theme_files[$array_pos];
echo $main_file;
}
$count++;
}
}
My script is pointing to a folder that stores images.
I would like to retrieve the file name and path name of the images so that my images get loaded when called (see html/php code below).
I have tried the following but i am getting an error:
Failed to open stream: Permission denied
On this line of code $page = file_get_contents($fileinfo->getPathname());
PHP
public function action_mybook($page = '') {
FB::log($this->request->param('id1'));
$this->template->content = View :: factory('mybook/default');
// give me a list of all files in folder images/mybook_images
$dir = new DirectoryIterator('images/mybook/');
$this->template->content->pages = array('.$dir.');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$pages[] = $fileinfo->getFilename();
$page = file_get_contents($fileinfo->getPathname());
}
}
}
HTML/PHP
<div id="book">
<!-- Next button -->
<div ignore="1" class="next-button"></div>
<!-- Previous button -->
<div ignore="1" class="previous-button"></div>
<?php
foreach ($pages as $page) {
echo '<div><img src="'.$page.'" /></div>';
}
?>
</div>
If I comment out the line $page = file_get_contents($fileinfo->getPathname()); and get no errors and the div for the image is created, but it says 'failed to load given url'
Loading the image manually using echo '<img src="myimage.png">' it displays the image
Possible problem
Your directory separator.
I try executate your code and get the same code. Whhy? Because the /. In windows is \. The return URL is invalid:
images/mybook\arrows.png
The correctly is:
images\mybook\arrows.png
or images/mybook/arrows.png (linux... in windows works too)
So, you need to use DIRECTORY_SEPARATOR constant of PHP, this solve your problem. See below:
UPDATE
I just add the $page to end of the URL in DirectoryIterator.
public function action_mybook($page = '') {
FB::log($this->request->param('id1'));
$this->template->content = View :: factory('mybook/default');
$dir = new DirectoryIterator('images' . DIRECTORY_SEPARATOR . 'mybook' . DIRECTORY_SEPARATOR . $page);
$this->template->content->pages = array('.$dir.');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$pages[] = $fileinfo->getPathname();
}
}
}
I hope this help.
And sorry for my english.
Change permissions on files in directory on 777, and try again
Try to comment this line:
$page = file_get_contents($fileinfo->getPathname());
i have no any idea, that you need to read image file to variable.
Check your full image path, try this:
$pages[] = 'images/mybook/'.$fileinfo->getFilename();
or
$pages[] = '/images/mybook/'.$fileinfo->getFilename();
relate to your project path.
Try to give the permission to your image, you can give the permission using chmod :
chmod($fileinfo->getPathname(),0777);//add this line in your code
$page = file_get_contents($fileinfo->getPathname());
Note: $fileinfo->getPathname() should return the image path.
I'm trying to get a webpage to show images but it doesn't seem to be working.
here's the code:
<?php
$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" alt="random image">'." ";
}
?>
If the code should work, where do i put it?
If not, is there a better way to do this?
You'd need to put this code in a directory that contains a directory named "images". The directory named "images" also needs to have files in a *.* name format. There are definitely better ways to do what you're trying to do. Such would be using a database that contains all the images that you want to display.
If that doesn't suit what you want to do, you'd have to be much more descriptive. I have no idea what you want to do and all I'm getting from the code you showed us is to render every file in a directory called "images" as an image.
However, if this point of this post was to simply ask "How do I execute PHP?", please do some searching and never bother us with a question like that.
Another thing #zerkms noticed was that your for .. loop starts at iteration 1 ($i = 1). This means that a result in the array will be skipped over.
for ($i = 0; $i < count($files); $i++) {
This code snippet iterates over the files in the directory images/ and echos their filenames wrapped in <img> tags. Wouldn't you put it where you want the images?
This would go into a PHP file (images.php for example) in the parent directory of the images folder you are listing the images from. You can also simplify your loop (and correct it, since array indexes should start at 0, not 1) by using the following syntax:
<?php
foreach (glob("images/*.*") as $file){
echo '<img src="'.$file.'" alt="random image"> ';
}
?>
/**
* Lists images in any folder as long as it's inside your $_SERVER["DOCUMENT_ROOT"].
* If it's outside, it's not accessible.
* Returns false and warning or array() like this:
*
* <code>
* array('/relative/image/path' => '/absolute/image/path');
* </code>
*
* #param string $Path
* #return array/bool
*/
function ListImageAnywhere($Path){
// $Path must be a string.
if(!is_string($Path) or !strlen($Path = trim($Path))){
trigger_error('$Path must be a non-empty trimmed string.', E_USER_WARNING);
return false;
}
// If $Path is file but not folder, get the dirname().
if(is_file($Path) and !is_dir($Path)){
$Path = dirname($Path);
}
// $Path must be a folder.
if(!is_dir($Path)){
trigger_error('$Path folder does not exist.', E_USER_WARNING);
return false;
}
// Get the Real path to make sure they are Parent and Child.
$Path = realpath($Path);
$DocumentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// $Path must be inside $DocumentRoot to make your images accessible.
if(strpos($Path, $DocumentRoot) !== 0){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// Get the Relative URI of the $Path base like: /image
$RelativePath = substr($Path, strlen($DocumentRoot));
if(empty($RelativePath)){
// If empty $DocumentRoot === $Path so / will suffice
$RelativePath = DIRECTORY_SEPARATOR;
}
// Make sure path starts with / to avoid partial comparison of non-suffixed folder names
if($RelativePath{0} != DIRECTORY_SEPARATOR){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// replace \ with / in relative URI (Windows)
$RelativePath = str_replace('\\', '/', $RelativePath);
// List files in folder
$Files = glob($Path . DIRECTORY_SEPARATOR . '*.*');
// Keep images (change as you wish)
$Files = preg_grep('~\\.(jpe?g|png|gif)$~i', $Files);
// Make sure these are files and not folders named like images
$Files = array_filter($Files, 'is_file');
// No images found?!
if(empty($Files)){
return array(); // Empty array() is still a success
}
// Prepare images container
$Images = array();
// Loop paths and build Relative URIs
foreach($Files as $File){
$Images[$RelativePath.'/'.basename($File)] = $File;
}
// Done :)
return $Images; // Easy-peasy, general solution!
}
// SAMPLE CODE COMES HERE
// If we have images...
if($Images = ListImageAnywhere(__FILE__)){ // <- works with __DIR__ or __FILE__
// ... loop them...
foreach($Images as $Relative => $Absolute){
// ... and print IMG tags.
echo '<img src="', $Relative, '" >', PHP_EOL;
}
}elseif($Images === false){
// Error
}else{
// No error but no images
}
Try this on for size. Comments are self explanatory.
I have a Drupal site that needs to display a unique header image based on the path. I have found some helpful code. It gets me close to where I need to be, but not all the way. I have pasted it at the end of this post.
The issue I am having is that it bases the banner image off of the characters after the first "/" after example.com in the URL. For example, example.com/forum returns a banner of header-FORUM.png.
I need it to work a little differently. I would like it to base the banner returned off the characters after the second "/" after example.com in the URL. For example, example.com/category/term should return a banner of header-TERM.png.
Any help that you can offer with this is much appreciated.
Here's the code I mentioned earlier via AdaptiveThemes (FYI, there is a comment on that page that attempts to solve a similar issue to mine but I can't get it to work).
<?php
// Return a file based on the URL alias, else return a default file
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
list($sections, ) = explode('/', $path, 2);
$section = safe_string($sections);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.png';
}
return $output;
}
//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
?>
Thanks!
Not exactly sure what the output of drupal_get_path_alias is, but try this:
<?php
// Return a file based on the URL alias, else return a default file
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
$pathSegments = explode('/', $path, 3);
$section = safe_string($pathSegments[2]);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.png';
}
return $filepath;//$output;
}
//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
The only changes made were to the usage of explode. explode will separate the path based on the /, so you just need to access a different element in that array. The last parameter of explode is the maximum number of elements to be returned and may also need to be tweaked
I'm adding an answer so I can include code. This is based on Gilean's response.
/** Return a file based on the URL alias, else return a default file
*/
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
$pathSegments = explode('/', $path, 3);
$section = safe_string($pathSegments[1]);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.jpg';
}
return $output;
}
/** Make a string safe
*/
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
This is what I would do:
In your theme's template.php, create the function THEMENAME_preprocess_page (replace THEMENAME with the name of your theme) as follows. If it already exists, add the following code to that function. (disclamer: untested code)
function THEMENAME_preprocess_page(&$variables) {
$path = drupal_get_path_alias($_GET['q']);
$path_segments = explode('/', $path, 3);
if ($path_segments[0] == 'category' && !empty($path_segments[1])) {
$safe_term = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $path_segments[1]));
$filepath = path_to_theme() . '/images/sections/header-' . $safe_term .'.png';
if (!file_exists($filepath)) {
$filepath = path_to_theme() . '/images/sections/header-default.png';
}
$variables['header_image'] = theme('image', $filepath);
}
}
Using a preprocess function (like the one above) is the Drupal way to make extra variables available for a template file. You only have to add a new element to the $variables array. Once you have done the above, you can simply put the following line in your page.tpl.php:
<?php print $header_image; ?>
This will print the complete <img> element.
PS. Usually, I advice not to base code like this on path aliases. It's a method that breaks easily because path aliases can change.