I'm having some difficulties echoing images to the browser. I'm quite new to PHP and I've been searching around the web for the past hour without finding a solution. I have tried adding header('Content-Type: image/jpeg');
to the document but it does nothing. I want my code to scan the directory and put all of its image files into the $thumbArray which I will echo to the browser. My ultimate goal is a photo gallery. Getting the images into the array works fine, but it will not display them on the page. Here is my my code:
<?php
//Directory that contains the photos
$dir = 'PhotoDir/';
//Check to make sure the directory path is valid
if(is_dir($dir))
{
//Scandir returns an array of all the files in the directory
$files = scandir($dir);
}
//Declare array
$thumbArray = Array();
foreach($files as $file)
{
if ($file != "." && $file != "..") //Check that the files are images
array_push($thumbArray, $file); //array_push will add the $file to thumbarray at index count - 1
}
print_r($thumbArray);
include 'gallery.html';
?>
Heres the Gallery.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gallery</title>
</head>
<body>
<?php
header('Content-Type: image/jpeg');
for($i = 0; $i < count($thumbArray); $i++)
echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />';
?>
</body>
</html>
For your current case, just remove header('Content-Type: image/jpeg'); from your code. Your output is HTML. All images are output inside IMG tags. No additional header modifications is required in this case.
Also, if you want use PHP, do not put this code in *.html file. It will not run inside *.html with default http-server's settings. Rename gallery.html to the gallery.php and change include 'gallery.html'; to the include 'gallery.php'; and it will works fine (of course if you have removed header('Content-Type: image/jpeg'); also).
Third bad thing is:
echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />';
You're trying to put $dir variable into single quote. Only double quote allows you to use PHP variables inside.
Change it:
echo '<img src="'.$dir.$thumbArray[$i].'" alt="Picture" />';
After changing, please, look in source code of the page and check if your image path is correct. If no, do something for correcting it. For example, maybe you forgot about directory separator and correct string will be:
echo '<img src="'.$dir.'/'.$thumbArray[$i].'" alt="Picture" />';
And so on.
Related
Hi I am using this code to output image from a file called images
<?php
//Path to folder which contains images
$dirname = $_POST['dir'];
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob($dirname."*");
//Display image using foreach loop
foreach($images as $image) {
//print the image to browser with anchor tag (Use if you want really :) )
echo '<p><img style="height:176px; width:221px; float:right;" src="'.$image.'" /></p>';
}
?>
I called it image.php and I used this form to make the user choose the directory
<form method="POST" action="image.php">
<input type="text" name="dir" placeholder="choose directory" />
<input type="submit" value="choose" />
</form>
when I run the code it output all files in the folder I have files like test.php and files as js and css and a file called images what happening is when I run it output the js and css and all .php file put it's not output the images what the error
That is extremely dangerous. Anyone can type whatever folder they want and immediately see (and in the case of PHP files, execute) all files in that directory.
Note the comment in your code about "only want JPEG or PNG", well you can do this:
$images = glob($dirname."*.{png,jpg,jpeg,gif}",GLOB_BRACE);
This will only allow image files of those types.
You should also be aware that glob is NOT recursive. You have to manually recurse through directories for that.
Or this, if you don't want to filter the extensions:
//Path to folder which contains images
$dirname = $_POST['dir'];
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob($dirname."/"."*");
//Display image using foreach loop
foreach($images as $image) {
//print the image to browser with anchor tag (Use if you want really :) )
echo '<p><img style="height:176px; width:221px; float:right;" src="'.$image.'" /></p>';
}
I am creating a slideshow editor. I have been able to parse a file and present it to the user in a form. Now I need to figure out how to write the saved information to the file. I want the user to be able to edit the information before and after the slideshow, so there is no specific set of information to be able to overwrite the whole file.
If there is a way to get all of the text before the div and copy it to the variable, add the new information, then get the rest of the information after the div and add that to the variable and then write all that information to the file, then that would work. Otherwise, here is what I have put together.
/* Set Variables */
$x = $_POST['x'];
$file = $_POST['file'];
$path = '../../yardworks/content_pages/' . $file;
$z=0;
while ($z<$x){
$title[$z] = $_POST['image-title'.$z];
$description[$z] = $_POST['image-desc'.$z];
$z++;
}
for ($y=0; $y<$x; $y++){
$contents .= '<li>
<a class="thumb" href="images/garages/'.$file[$y].'">
<img src="images/garages/'.$file[$y].'" alt="'.$title[$y].'" height="100px" width="130px" class="slideshow-img" />
</a>
<div class="caption">
<div class="image-title">'.$file[$y].'</div>
<div class="image-desc">'.$description[$y].'</div>
</div>
</li>';
}
/* Create string of contents */
$mydoc = new DOMDocument('1.0', 'UTF-8');
$mydoc->loadHTMLFile($path);
$mydoc->getElementById("replace")->nodeValue = $contents;
$mydoc->saveHTMLFile($path);
$file = file_get_contents($path);
$file = str_replace("<", "<", $file);
$file = str_replace(">", ">", $file);
file_put_contents($path, $file);
?>
Nothing throws out an error, but the file also remains unchanged. Is there anything I can change or fix to make it write to the file? This is all I have been able to find regarding this specific problem.
I would like to stick to one language, but if I find a way to write to the file using javascript, do the php variables pass on to the javascript section or do I have to stick with one language?
**Edit
Everything is working. ONE problem: is there a way to keep the special characters without converting them? I need the < and > to stay as they are and not convert to a string
I have decided to save the file as it is and use a separate code set to replace the string. I have edited my question above.
in php i want to ask how to get images one by one from folder directory and display in the jquery slider i have tried this php code by it's not working as i want?
<ul class="jcarousel-list">
<li class="jcarousel-item">
<?php
$directory = "data/uploads/topslider/";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
else
{
}
$files_index = glob("data/uploads/"."top"."slider/*.*");
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
?>
<img src="<?php echo $num2;?>" width="50" height="50" alt="" /> <?
}?></li>
</ul>
i want display like this:
Image1 Imag2 Image3......and So On from single folder or directory
There are four main things to check:
Is your $directory path correct relative to your current working directory in PHP? You can determine your current working directory by doing a temporary echo getcwd();. It needs to return the parent directory of your "data" folder for your code to work.
Is the data folder accessible from the current page on the web? e.g. if you manually remove the page from the URL (say, index.php) and add data/uploads/topslider/someimage.png where someimage.png is an image you know exists in your topslider folder, does the image load properly in the browser? If not, you'll need to update the way you build the src attribute in your img tag(s).
You're only adding one jcarousel-item for all your images, which doesn't seem right to me. I'm guessing you're expected to add a list item for each image.
You don't need to call glob twice just to ascertain how many files you have to work with. Just do a foreach statement once:
echo '<ul class="jcarousel-list">';
foreach(glob($directory . '*') as $filename) {
echo '<li class="jcarousel-item"><img src="'.$filename.'" width="50" height="50" alt="" /></li>';
}
echo '</ul>';
based on the original code in this question and Tims correction over there (answer 1) I'm trying to achieve the following:
I have a folder "img" containing images as follows:
image_123.jpg
image_123_alternate.jpg
image_456.jpg
image_456_alternate.jpg
image_789.jpg
image_789_alternate.jpg
and so on...
(Note: all images have the same size of 200px/200px)
When pulling from the "img" folder the simple HTML page should display images and filenames in the following fashion:
The actual images that contain the "_alternate" part in their filename (and only these) + the image filename not containing the "_alternate" part (without the file-extension) underneath the image in a textbox. All pairs should be pulled in an alphabetical order. In the example below bold capital letters indicate the actual image to be displayed:
IMAGE_123_ALTERNATE
textbox: "image_123"
IMAGE_456_ALTERNATE
textbox: "image_456"
IMAGE_789_ALTERNATE
textbox: "image_789"
This is what I have so far but this displays all images and filenames:
<?php
$dir = opendir("img");
while (($file = readdir($dir)) !== false)
{
echo "<a href='img/".$file."' target='_blank'> <img src='img/".$file."'width='200' height='200' /></a><br />";
echo "<textarea>$file</textarea><br /><br />";
}
closedir($dir);
?>
Any help would be much appreciated!
Thanks a lot!
This code should display a list of all images in alphabetical order (using PHP's GLOB function).
It then outputs a HTML image (leading to the "_alternate" image) and the image's filename (without the path, "_alternate" or "extension").
<?php
foreach (glob("img/*_alternate.jpg") as $file) {
$filename_parts = pathinfo($file);
$filename = $filename_parts['filename'];
$filename = str_replace("_alternate", "", $filename);
echo "<div>";
echo "<img src=\"/$file\" width=\"200\" height=\"200\" />";
echo "<p>$filename</p>";
}
?>
I have broken apart the functions that find the new filename and the parts that output the HTML code to make it easier to read and understand, you could merge these into one function if you wanted to.
Just through an if statement in your while loop. Check if the file name contains alternate or or not. If it doesn't contain alternate run your same code replacing the file extension with "_alternate.ext" while keeping the text area the same. If it does contain alternalte, do nothing. That way you are only processing half the files.
$files = new \DirectoryIterator('img'); // <- this should be the full absolute path!
$images = array();
// pick up jpg images that end in 'alternate'
foreach($files as $file){
$name = $file->getBasename('.jpg');
if(strripos($name, 'alternate') === (strlen($name) - 9))
$images[] = $name;
}
// sort them
sort($images, SORT_STRING);
// and do your thing here with $images...
var_dump($images);
I need to display an image which is in Base64 format. When I build the img tag in PHP it doesn't show the image (just the defualt 'broken image' icon). When I view the page source and click on the Base64 data is shows the picture as expected. Also, if I copy and paste the page source and save it as an HTML file it displays as expected. I also tried a random image and that worked however as my image works from a .html file I assume it is OK and should work?
The .php code:
header('content-type: text/html');
...
echo "<html><head></head><body>";
echo "Name = $name<br/>";
echo "<img src=\"data:image/jpg;base64,$photo\"/>";
echo "</body></html>";
The HTML from View Source:
<html>
<head></head>
<body>Name = Andrea Pilipczuk<br/>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAyADIAA...{too big to fit here].../9k="/>
</body>
</html>
EDIT:
This didn't come up in View Source but digging around Chrome, I inspected the image element and found at the end was "9k=�������". Is this some kind of padding? When I edited the element to remove these the image showed up as expected.
The following code removes the random characters and displays the image correctly but seems a bit hacky, would obviously prefer to solve the underlying issue.
$unpadded = explode("=", $photo);
$padding = strlen($unpadded[0]) % 3;
$padded = $unpadded[0];
while ($padding > 0) {
$padded .= "=";
$padding--;
}
echo "<img src=\"data:image/jpeg;base64,$padded\"/>";