Showing Images in PHP - php

I want to show images residing inside a directory in PHP
The code which I wrote was
<?php
$dir = opendir("upload");
while (($file = readdir($dir)) !== false)
{
echo "filename: " . $file . "<br />";
echo "<a href='shoe.php?image_name=".$file."'> <img src='upload/".$file[0]."' width='150' height='150' /></a></td>";
}
closedir($dir);
?>
Here the images are not displayed. Only a frame comes for that image and the actual image is not displayed inside that.
Where I have went wrong? Can any one please help...

PHP Glob makes it much easier to list directories. You can do something like
$image = glob("*.jpg")
foreach ($image as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}

Replace $file[0] with $file, as $file is not an array and that will only return the first character of the string.

why $file[0]??? $file is correct:
<?php
$dir = opendir("upload");
while (($file = readdir($dir)) !== false)
{
echo "filename: " . $file . "<br />";
echo "<a href='shoe.php?image_name=".$file."'> <img src='upload/".$file."' width='150' height='150' /></a>";
}
closedir($dir);
?>

Related

Download link over random php image

I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link display on top of the image?
Display random image from folder using PHP:
function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);
if($leading == '/')
{
$directory = substr($directory, 1);
}
if($trailing != '/')
{
$directory = $directory . '/';
}
if(empty($directory) or !is_dir($directory))
{
die('Directory: ' . $directory . ' not found.');
}
$files = scandir($directory, 1);
$make_array = array();
foreach($files AS $id => $file)
{
$info = pathinfo($dir . $file);
$image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
if(!in_array($info['extension'], $image_extensions))
{
unset($file);
}
else
{
$file = str_replace(' ', '%20', $file);
$temp = array($id => $file);
array_push($make_array, $temp);
}
}
if(sizeof($make_array) == 0)
{
die('No images in ' . $directory . ' Directory');
}
$total = count($make_array) - 1;
$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];
}
Markup:
echo "<img src=" . random_image('css/images/avatars') . " />";
I've tried looking around google for an answer but I can't find anything, any help would be appreciated
You should save the image location in a variable then use it to create a link, plus display it.
$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">";
echo "<img src=" . $imageUrl . " />";
echo "</a>";
or if you want to show the text link above, seperately then
$imageUrl = random_image('css/images/avatars');
echo "Click Here<br />";
echo "<img src=" . $imageUrl . " />";
you could use simple javascript to do so, like onclick event for example :
just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'
echo "<img onclick='window.open('". random_image('css/images/avatars') ."')' src='" . random_image('css/images/avatars') . "' />";

How can I get the contents of a file one line at a time?

I have a project where a user uploads a photo with a name and caption, and I am having trouble with displaying the name and caption.
Right now, it's displaying the entire text file with each image, and I am having trouble fixing this.
My code so far:
<?php
$Dir = "files";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry)
{
if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
{
echo "<p>Name: " . file_get_contents("imagelist.txt") . "</p>";
echo "<a href=\"files/" . $Entry . "\" target=\"_blank\" >" . $Entry . "</a><br />\n";
}
}
closedir($DirOpen);
?>
Any help would be greatly appreciated.
You can use fgets():
$inputFile = fopen("file.txt", "r");
if ($inputFile) {
while (($line = fgets($inputFile)) !== false) {
echo $line."<br>";
// The process read the file line by line
}
} else {
echo "There was an error in the opening file";
}
fclose($inputFile);

Editing text files in a directory with PHP

I've got a script which lists all the txt files that I have in a directory. I've put a hyperlink each of the results that comes up and I want to the redirect to a simple editor which I have the code for.
This is the code for listing the files in the directory;
<?php
//Open directory
$dir = dir("content");
//List files in directory
while (($file = $dir->read()) !== false){
//Make sure it's a .txt file
if(strlen($file) < 5 || substr($file, -4) != '.txt')
continue;
echo "Page: <a href='content/" .$file. "'>" . $file . "</a><br />";
}
$dir->close();
?>
And the code to edit the file:
<?
if($_POST['Submit']){
$open = fopen("content/body.txt","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("content/body.txt");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("content/body.txt");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
What's the best way to try and do this?
Thanks in advance.
I think you mean this:
in directory list use this:
echo "Page: <a href='editor_script.php?filename=".$file."'>".$file."</a><br/>";
in your editor script use this:
$open = fopen("content/".$_GET['filename'].".txt","w+");
$file = file("content/".$_GET['filename'].".txt");
I' not sure but maybe you have to remove action from form
echo '<form method="post">';
or use url with $_GET['filename']
echo '<form action="editor_script.php?filename='.$_GET['filename'].'" method="post">';
maybe this works too but I'm not sure
echo '<form action="?filename='.$_GET['filename'].'" method="post">';

Do a php function code on a link

I'm looking for a way to do a function with php when clicking on a link.
I mean to delete an item when clicking on this link. I got my code set up like this:
$files = glob("upload/*.*");
if(count($files) == 0){
echo "No files present";
} else {
foreach ( $files as $file ) {
$array = explode("/", $file);
//echo $array[1] . "<br>";
echo "<tr>";
echo "<td>" . $array[1] . "</td>";
echo '<td><img height="70" width="auto" src=" ' . $file . '" ></td>';
echo '<td>Delete item</td>';
echo "</tr>";
}
}
In your main script:
$files = glob("upload/*.*");
if(!count($files)){
echo "No files present";
} else {
foreach ($files as $file) {
$array = explode("/", $file);
echo "<tr>";
echo "<td>" . $array[1] . "</td>";
echo '<td><img height="70" width="auto" src=" ' . $file . '" ></td>';
echo '<td>Delete item</td>';
echo "</tr>";
}
}
In your delete script:
if (isset($_GET['file']) && $file = rawurldecode($_GET['file'])) {
if (file_exists('upload/' . $file))
unlink($file);
}
You might want to pass in another $_GET parameter (secret token) for added security - otherwise it'll open up your uploads directory to permanent threat. You can send a random sha1() hash or system-defined configuration value, and have your delete script expect a 40-char string.

php - get full image path from server

how can i get image path on server using "browse" button in a html form, select the file (double clicking the file returning its full path), and put the result image path into variable $img_path?
let's say the image dir in my server is /images, i'd like to get path of "foo.jpg", the full image path should be "/images/foo.jpg"
so, all i have to do is :
1. create form which contain "browse" button or something like that - that allow me to explore "images" directory at my server
2. exploring "images" dir, all files listed and clickable, locate "foo.jpg", select it, and voila, i get the image path "/images/foo.jpg"
any lil' help would be appreciated..
Thanks
#CodeCaster thanks for your respond.. but this is all i want (at least closer) :
<?php
$dir = '/images';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
echo $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
?>
using "dir" you can achieve your goal.
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
You could use dir:
echo "<ul>";
$d = dir("images");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo "<li>" . $entry . "</li>";
}
$d->close();
echo "</ul>";

Categories