php truncate file path to display file name - php

Trying to display filename but code is resulting in full file url displaying
if (trim($s) == "") continue;
$arrfilename = explode("\/", $s);
$shortfilename = $arrfilename[count($arrfilename)-1];
$path_parts = pathinfo($s);
$dir = $path_parts['dirname'];
$basename = $path_parts['basename'];
$ext = $path_parts['extension'];
$fn = $path_parts['filename'];
$sliderimage = $dir . '/' . $fn . '.' . $ext;
if (!file_exists($sliderimage) && !file_exists('../' . $sliderimage)) $sliderimage = $s;
$output .= '[setslideshowlinkattributes ssrs="' . $s . '"]<img src="/' . $sliderimage . '" alt="' .$shortfilename . '" /></a>';
}
$output .= '</div>';
$output .= ' <div id="htmlcaption" style="display: inline;">' . $this->options->slideshowcaption . '</div>';
$output .= '</div>';

Related

Search for pdf files

I have one little question, this is my code to list all files from a folder and subfolders;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry)){
$allFiles[] = "D: " . $dir . "/" . $entry;
}else{
$extension = strtoupper(pathinfo($entry, PATHINFO_EXTENSION));
$fileNoExten = pathinfo($entry, PATHINFO_FILENAME);
$directory = substr(str_replace('/', ' > ', $dir), $rootLenOnce + 3);
$listagem .= '<tr>';
$listagem .= "<td><a href='../" . $dir . "/" . $entry . "' ' target='_blank'>" . $entry . "</a></td>";
//$listagem .= "<td><small>" . $directory . "</small></td>";
$listagem .= "<td>" . $extension . "</td>";
$listagem .= "<td><a class='download-cell' href='../".$dir ."/". $entry."' ' download> <i class='fa fa-download' ></i></a></td>";
$listagem .= "<td class='display-none'>" . $fileNoExten . "</td>";
$allFiles[] = "F: " . $dir . "/" . $entry;
$listagem .= '</tr>';
echo "<pre>"; print_r(glob("*.pdf")); echo "</pre>";
}
}
}
closedir($handle);
foreach($allFiles as $value){
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", "%20", substr($value, $pathLen + 3));
if (is_dir($fileName)) {
myScanDirPdf($fileName, $level + 1, strlen($fileName),$rootLenOnce);
}
}
}
return $listagem;
}
what i need is to filtrate the search, to search only .pdf files.
Someone can help me plz!
Thks!
i try with the glob function, but not with great results.
Thks!
When you are looping through each file, you can use
if(stripos($fileName, ".pdf"))
Hope this will help
I have one more suggestion in listing all the files and subfolders.
You can use Recursive Iterator
$folderName = $_POST['folderName'];
$dir = new RecursiveDirectoryIterator($folderName);
$it = new RecursiveIteratorIterator($dir);
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
}elseif ($fileinfo->isFile()) {
$fileName = $fileinfo->getFileName();
if(stripos($fileName, ".pdf")) {
//do what you need to do
}
}
}

How do I write a ternary operator for this line?

I can't figure out how to write a ternary operator for the ending of this line (i.e. "location" and "description"). I've defined the $location and $description variables but I'm getting an error that says unexpected $location variable.
Basically, for both location and description, I'm trying to say: If the field has been filled out, display the field. If not, don't print anything.
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
Here is the full context:
if( have_rows('slides', $frontpage_id) ):
while ( have_rows('slides', $frontpage_id) ) :
the_row();
$group = get_sub_field('group');
$count = 1;
$i = 0;
$nav .= '<ul id="nav_'.$group.'" style="display: none;">';
$content .= '<div class="image-data-container image-container-'. $group .'">';
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
$location = get_sub_field('location');
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
$content .= '</div>';
$nav .= '</ul>';
endwhile;
endif;
?>
Other the fact that your $content variable is a formatting nightmare. The ternary operator syntax returns result based on the condition and it should be separated from your $content attribute
$someVariable = (get_sub_field('location')) ? '<em>'.$location.'</em>' : '';
Now use that some variable inside your $content variable instead
Here is your code with comments:
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
// you have already defined the location variable here
// It also means and I am assuming they your get_sub_field is returning a string
// If you are receiving a boolean or null value than and than only than you can do your ternary condition call of
// get_sub_field('location') ? '<em>'$location'</em>' : ''
// and if you are receiving a string field then you will have to explicitly check the condition
// something like this (get_sub_field('location') === '') ? '<em>'$location'</em>' : ''
// I am not that familiar with wordpress framework or the ACF plugin but it looks like get_sub_field will return something so you actually wont need the ternary condition
$location = get_sub_field('location');
// Similar case with description
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
// After removing the ternary condition your content variable will look like this
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . '<em>' . $location . '</em>' . '<hr><span class="details">Details [+]</span><div class="details-display">' . $description . '</div>' . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
You know you can always make it more readable
// You know instead of all the concatenation you can do this instead
$templateDirURI = get_template_directory_uri();
$groupLower = strtolower($group);
$title = get_sub_field('title');
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong><hr><em>{$location}</em><hr><span class='details'>Details [+]</span><div class='details-display'>{$description}</div></div></div></div>";
Updated Code
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong>";
// Assuming the user did not submit location information
if($location !== "")
$content .= "<hr><em>{$location}</em><hr>";
if($description !== "")
$content .= "<span class='details'>Details [+]</span><div class='details-display'>{$description}</div>";
$content .= "</div></div></div>";

Adding functions into an Array in php

As it stands I am having real trouble figuring out just how to get the functions delete, move/copy, rename into an array via click of an image or text, and then making the function correspond to the correct row in the table and the correct file on the row in the array.
This is a very hard question to word to be honest but the array currently populates a table with files in a folder, file name, size and date modified, I'm trying to add in small images on each row for delete file, rename file ect. so that these images are linked with functions so when pressed it will delete the corresponding file or rename it if that makes sense. anyway the array code is below, and I understand if its difficult to answer just figured I would ask.
Also $cellOptions is the cell im trying to populate it currently just gives me back the logged in user
http://pastebin.com/dkeUAk50
function listFiles($dir)
{
$output = ''; $outRows = ''; $files = array();
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
$totalSize = (int) 0;
foreach($files as $file) {
$fileTime = #date("d-M-Y", filectime($dir . '/' . $file)) . ' ' . #date("h:i", filemtime($dir . '/' . $file));
$totalSize += filesize($dir . '/' . $file);
$fileSize = #byte_convert(filesize($dir . '/' . $file));
$cellLink = '<td class="list_files_table_file_link">' . $file . '</td>';
$cellTime = '<td>' . $fileTime . '</td>';
$cellOptions = '<td>'. $_SESSION['Username'] .'<td>';
$cellSize = '<td>' . $fileSize . '</td>';
$outRows .= '<tr>' . "\n " . $cellLink . "\n " . $cellTime . "\n " . $cellSize . "\n" . $cellOptions . '</tr>' . "\n";
}
closedir($dirHandle);
}
}
$output = '<table class="list_files_table" width="100%" align="center" cellpadding="3" cellspacing="1" border="0">' . "\n";
$output .= '<thead><tr><td><b>Name</b></td><td><b>Date Modified</b></td><td><b>Size</b></td></tr></thead>' . "\n";
$output .= '<tfoot><tr><td colspan="2">' . count($files) . ' files.</td><td>' . #byte_convert($totalSize) . '</td></tr></tfoot>' . "\n";
$output .= '<tbody>' . "\n";
$output .= $outRows;
$output .= '</body>' . "\n";
$output .= '</table>';
return $output;
}
function byte_convert($bytes)
{
$symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$exp = (int) 0;
$converted_value = (int) 0;
if ($bytes > 0) {
$exp = floor(log($bytes)/log(1024));
$converted_value = ($bytes/pow(1024,floor($exp)));
}
return sprintf('%.2f ' . $symbol[$exp], $converted_value);
}
session_start();
echo listFiles($_SESSION['UserFolder']);
Add an element that contains the following in your loop:
A form that submits to the same page with a method of POST
An hidden input element that contains the filename
A submit button to submit the form.
This is what it would look like:
$cellSize = '<td>' . $fileSize . '</td>';
$deleteCell = '<td><form action="/" method="POST"><input type="hidden" value="'.$file.'" ame="fileToDelete"/><input type="submit" value="Delete" name="deleteButton"/></form></td>';
Create a function to delete:
function deleteFile($dir, $fileToDelete){
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
if($files){
foreach($files as $file){
if($file === $fileToDelete) {
unlink($fileToDelete);
$output = 'Successfully deleted file: '.$fileToDelete;
}
}
}
}
}
return $output;
}
Check if a form was submitted, and if so, delete the file in question:
if(isset($_POST)){
echo deleteFile($_SESSION['UserFolder'], $_POST['fileToDelete']);
}

Creating XML code using image source from SlideshowPro Album using PHP

I used the code from this website http://wiki.slideshowpro.net/PlayerWithoutDirector/PWDSCRIPTS-PHPXMLBuilderScript with a copy of the code below called images.php with audio but I don't really need audio. This PHP script just retrieves the image source of photos in a directory of a folder to an XML file. Instead, I'd like to write an XML file that would get the image source directly from a SlideshowPro Album. The first code below lists the images from an album directly from SlideShowPro. How do I combine the two scripts?
// gallery.php
<?php
include('classes/DirectorPHP.php');
$director = new Director('api', 'key');
$album = $director->album->get(440);
echo $album->name . '<br /><br />';
// Loop through album content
$contents = $album->contents[0];
foreach($contents as $content) {
echo $content->src . '<br />';
}
?>
// images.php
<?php
/**************************************************************************
XML Generator for SlideShowPro
Brad Daily - slideshowpro.net
For instructions, see the wiki:
http://wiki.slideshowpro.net/SSPExtras/PhpXmlBuilder
This script is governed by the following license:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
**************************************************************************/
/*
CONFIGURATION
*/
// Name of the folder in each album's folder that contains the full size imagery
$large_folder = 'lg';
// Name of the folder in each album's folder that contains the thumbnails
$thumb_folder = 'tn';
// Name of your album preview image. placed at the root of each album's folder (optional)
$album_preview_name = 'albumPreview.jpg';
/* Audio addition
$audio_folder = 'audio';
*/
/*
END CONFIGURATION
(DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING)
*/
// Set up paths
define('DS', DIRECTORY_SEPARATOR);
$dir = dirname(__FILE__);
$server = 'http://' . $_SERVER['HTTP_HOST'];
$rel_path = str_replace('images.php', '', $_SERVER['PHP_SELF']);
$path = $server . $rel_path;
$iptc = is_callable('iptcparse');
/*$width = "thumbnailWidth=auto thumbnailHeight=78"; */
// Find all folders in this directory
$albums = array();
$d = dir($dir);
while (false !== ($folder = $d->read())) {
if ($folder != '.' && $folder != '..' && is_dir($dir . DS . $folder . DS . $large_folder))
{
$albums[] = $folder;
}
}
$d->close();
// Start writing XML
$o = '<?xml version="1.0" encoding="utf-8"?>' . "\n<galleries>\n";
// Cycle through albums
foreach($albums as $album) {
// Path variables
$loc_path = $path . $album . '/';
$full_path = $dir . DS . $album;
// Find images in the large folder
$images = array();
$d2 = dir($full_path . DS . $large_folder);
while (false !== ($image = $d2->read())) {
if (eregi('.jpg|.gif|.png|.swf|.flv|.mov', $image)) {
$images[] = $image;
}
}
$d2->close();
/* Audio addition
// Find audios in the audio folder
$audios = array();
$d2 = dir($full_path . DS . $audio_folder);
while (false !== ($audio = $d2->read())) {
if (eregi('.mp3|.ra|.wav', $audio)) {
$audios[] = $audio;
}
}
$d2->close();
Audio addition */
// Only write the album to XML if there are images
if (!empty($images)) {
natcasesort($images);
// Pretty up the title
$title = ucwords(preg_replace('/_|-/', ' ', $album));
// See if there is an album thumb present, if so add it in
if (file_exists($full_path . DS . $album_preview_name)) {
$atn = ' tn="' . $loc_path . $album_preview_name . '"';
} else {
$atn = '';
}
// Only write tnPath if that folder exists
if (is_dir($full_path . DS . $thumb_folder)) {
$tn = ' tnPath="' . $loc_path . $thumb_folder . '/"';
}
/* Audio addition
$audio = '';
if (0 < count($audios)) {
$audio = sprintf(' audio="%s" audioCaption="%s"',
$loc_path . $audio_folder . '/' . $audios[0],
substr(ucwords(preg_replace('/_|-/', ' ', $audios[0])), 0, -4));
}
Audio addition */
// Album tag
$o .= "\t" . '<imagegroup title="' . $title . '" thumbnailPath="' . $loc_path .
$large_folder . '/"' . $width . $atn . $audio . '>' . "\n";
// Cycle through images, adding tag for each to XML
foreach($images as $i) {
$link = $caption = '';
$title = '';
if ($iptc) {
$file = $full_path . DS . $large_folder . DS . $i;
$path_info = pathinfo($file);
$extensions = array('jpg', 'jpeg', 'gif', 'png');
if (in_array(strtolower($path_info['extension']), $extensions)) {
getimagesize($file, $info);
if (!empty($info['APP13'])) {
$iptc = iptcparse($info['APP13']);
if (isset($iptc['2#005'])) {
$title = $iptc['2#005'];
if (is_array($title)) {
$title = htmlentities($title[0], ENT_COMPAT);
}
}
if (isset($iptc['2#120'])) {
$caption = $iptc['2#120'];
if (is_array($caption)) {
$caption = htmlentities($caption[0], ENT_COMPAT);
}
}
}
}
}
if (isset($_GET['link'])) { $link = $loc_path . $large_folder . '/' . $i; }
$o .= "\t\t" . '<img src="' . $i . '" title="' . $title . '" />' . "\n";
}
// Close the album tag
$o .= "\t</imagegroup>\n";
}
}
// Close gallery tag, set header and output XML
$o .= "</galleries>";
header('Content-type: text/xml');
die($o);
I'd like my result to appear like this:
<galleries>
<imagegroup title="2013 In Review" thumbnailPath="2013Review/thumb.jpg" thumbnailWidth="auto" thumbnailHeight="78">
<img src="2013Review/JLP09509_01_026.jpg" title="Paul Walker by Jeff Lipsky"/>
<img src="2013Review/NAB10003_01_001.jpg" title="Nelson Mandela by Nabil"/>
<img src="2013Review/MMU13110_41_001.jpg" title="Lindsey Vonn by Michael Muller"/>
</imagegroup>
<imagegroup title="Awards Season" thumbnailPath="AwardSeason/thumb.jpg" thumbnailWidth="56" thumbnailHeight="78">
<img src="AwardSeason/GBE07090_04_007.jpg" title="Tom Hanks by Giuliano Bekor - "Captain Phillips""/>
<img src="AwardSeason/DTI12009_02_001.jpg" title="Amy Adams by Darren Tieste - "American Hustle" "/>
<img src="AwardSeason/NPA11013_01_005.jpg" title="Idris Elba by Nigel Parry - "Mandela-Long Walk to Freedom" "/>
</imagegroup>
</galleries>

PHP function extension for wordpress plugin

I'm trying to extend a function of a WordPress plugin to accept another parameter but I'm having problems figuring out the output. The plugin I'm talking about is NextGen Gallery and I'm trying to make it to show a slideshow of images with descriptions.
The code I'm using to show the slideshow on my theme file is this:
<?php echo nggShow_JS_Slideshow(1,906,358,'caption'); ?>
Below is the complete function:
function nggShow_JS_Slideshow($galleryID, $width, $height, $template = '', $class = 'ngg-slideshow') {
global $slideCounter;
$ngg_options = nggGallery::get_option('ngg_options');
// we need to know the current page id
$current_page = (get_the_ID() == false) ? rand(5, 15) : get_the_ID();
// look for a other slideshow instance
if ( !isset($slideCounter) ) $slideCounter = 1;
// create unique anchor
$anchor = 'ngg-slideshow-' . $galleryID . '-' . $current_page . '-' . $slideCounter++;
if (empty($width) ) $width = (int) $ngg_options['irWidth'];
if (empty($height)) $height = (int) $ngg_options['irHeight'];
//filter to resize images for mobile browser
list($width, $height) = apply_filters('ngg_slideshow_size', array( $width, $height ) );
$width = (int) $width;
$height = (int) $height;
$out = '<div id="' . $anchor . '" class="' . $class . '" style="height:' . $height . 'px;width:' . $width . 'px;">';
$out .= "\n". '<div id="' . $anchor . '-loader" class="ngg-slideshow-loader" style="height:' . $height . 'px;width:' . $width . 'px;">';
$out .= "\n". '<img src="'. NGGALLERY_URLPATH . 'images/loader.gif" alt="" />';
$out .= "\n". '</div>';
$out .= '</div>'."\n";
$out .= "\n".'<script type="text/javascript" defer="defer">';
$out .= "\n" . 'jQuery(document).ready(function(){ ' . "\n" . 'jQuery("#' . $anchor . '").nggSlideshow( {' .
'id: ' . $galleryID . ',' .
'fx:"' . $ngg_options['slideFx'] . '",' .
'width:' . $width . ',' .
'height:' . $height . ',' .
'template:' . $template . ',' .
'domain: "' . trailingslashit ( home_url() ) . '",' .
'timeout:' . $ngg_options['irRotatetime'] * 1000 .
'});' . "\n" . '});';
$out .= "\n".'</script>';
return $out;
}
The problem is the 'template' parameter that I've added to the function. It doesn't work for some reason - the slideshow keeps loading forever. You can see the full nggfunctions.php file here. And the website were you can see this live is this. I also should mention that PHP is not one of my strong points.
Later edit: isn't there a way to add the description of each image directly in the function and not pass it through the 'template' parameter?

Categories