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.
Related
I have upload images in rooturl + uploads/slider
and image name store in database slider_image.
I want to delete slider_image from databse and also delete from folder.
my folder location :
http://localhost/game/uploads/slider/soccer.jpg
image_name:
soccer.jpg
I got an warning error :
Severity: WarningMessage: unlink(): http does not allow unlinking
my model code:
public function deleteSlider($sliderID)
{
$this->db->delete('slider_tbl',array('slider_id' => $sliderID));
$path = base_url("uploads/slider/".$result[0]->slider_image);
if($this->db->affected_rows() >= 1){
if(unlink($path))
return TRUE;
} else {
return FALSE;
}
}
Try Changing your $path.
$path = base_url("uploads/slider/".$result[0]->slider_image);
to
$path = "./uploads/slider/" . $result[0]->slider_image;
Change
$path = base_url("uploads/slider/".$result[0]->slider_image);
to
$path = FCPATH . "uploads/slider/" . $result[0]->slider_image;
You need to use the path to the file on the server, not the URL, so you need something like:
$path = "/uploads/slider/".$result[0]->slider_image;
without the base_url.
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();
I'm very basic when it comes to PHP.
With my website, I have a directory called "uploads"
Within "uploads" I have 3 folders "Example1" "Example2" and "Example3"
Within each of the folders, they contain images.
I need to know how to use php to create a navigation for every sub directory.
So that if I add a new folder "Example4" it will give a navigation like:
Select what section you're looking for:
Example1 | Example2 | Example3
and if I later add new folders add them to the navigation.
EX:
Example1 | Example2 | Example3 | Example4 | Example5
Then once they click the link to go into the folder, have a code that displays all the images in that folder.
So far I have:
<?php
$files = glob("uploads/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="/'.$num.'">'."<p>";
}
?>
but it will only display the images in the upload directory, not the images in Example1 and so on.
How on earth would I go about doing this? I'm doing it for a school project and have two weeks to complete it, but I am so lost. I only have knowledge with CSS, HTML, and the only PHP I know is php includes, so any help would be appreciated.
Since it seems that you are familiar with globs a bit, here is an example using the "glob" function. You can see a basic working example of what you are looking for here:
http://newwebinnovations.com/glob-images/
Here is how I have the example set up:
There are two PHP files, one is index.php and the other is list-images.php.
There is also a folder for images two subfolders that have images inside of them.
index.php is the file that finds the folders in the images folder and places them in a list with links list-images.php which will display the images inside of the folder:
$path = 'images';
$folders = glob($path.'/*');
echo '<ul>';
foreach ($folders as $folder) {
echo '<li>'.$folder.'</li>';
}
echo '</ul>';
The links created above have a dynamic variable created that will pass in the link to the list-images.php page.
Here is the list-images.php code:
if (isset($_GET['folder'])) {
$folder = $_GET['folder'];
}
$singleImages = array();
foreach (glob($folder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $image) {
$imageElements = array();
$imageElements['source'] = $image;
$singleImages[$image] = $imageElements;
}
echo '<ul>';
foreach ($singleImages as $image) {
echo '<li><img src="'.$image['source'].'" width="400" height="auto"></li>';
}
echo '</ul>';
The links created here will link you to the individual images.
To get files of every specific folder ,pass it throw a get variable that contains folder's name,an then scan this folder an show images ,url should be like this :
listImages.php?folderName=example1
To have menu like what you want :
<?php
$path = 'uploads/' ;
$results = scandir($path);
for ($i=0;$i<count($results);$i++ ) {
$result=$results[$i];
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
echo "<a href='imgs.php?folderName=$result'>$result</a> ";
}
if($i!=count($results)-1) echo '|'; //to avoid showing | in the last element
}
?>
And here is PHP page listImages that scan images of a specific folder :
<?php
if (isset($_GET['folderName'])) $folder=$_GET['folderName'];
$path = 'uploads/'.$folder.'/' ;
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
echo "<img src='$image' />";
}
?>
First of all, do read more PHP manual, for directory related: opendir, for files related: fopen
The following code is basically re-arranging the example code provided in opendir. What it does:
A scan_directory function to simply check if directory path is valid and is a directory, then proceed to do a recursive call if there's a child directory else just print out the file name.
The first if/else condition is just to ensure the base directory is valid.
I'll added ul and li to make it slightly more presentable.
$base_dir = 'upload';
if (is_dir($base_dir))
scan_directory($base_dir);
else
echo 'Invalid base directory. Please check your setting.';
// recursive function to check all dir
function scan_directory($path) {
if (is_dir($path)) {
if ($dir_handle = opendir($path)) {
echo '<ul>';
while (($file = readdir($dir_handle)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($path . '/' . $file)) {
echo '<li>';
echo $file;
scan_directory($path . '/' . $file);
echo '</li>';
}
else
echo "<li>{$file}</li>";
}
}
echo '</ul>';
}
}
}
create image as subdirectory name with image name and save it in database
example:
subdirectory name: example2
image name: image.jpg
store image name in db as "example2/image.jpg"
I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content.
I'd like to randomly grab a file from this folder and echo it into a div. Here is what I have:
<?php
function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
<div class="my-div">
<?php echo random_update(); ?>
</div><!--end my-div-->
I am getting 500 errors? Also, my intention is to only echo 1 file at a time. Will the provided code accomplish that?
Php does not recognize the syntax you used. You have to bypass it like this:
<?php
function random_update($dir = NULL)
{
if ($dir === NULL) {
$dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
}
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Also, you might want to enable error dumping in your development environment so you know what went wrong next time.
Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code:
<?php echo random_update(); ?>
for this one:
<?php echo file_get_contents (random_update()); ?>
because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div.
You can't use any expression as "default" function's argument value.
The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>