str_replace in file names - php

I have a PHP code that displays the file contents of a directory in a list. Each file is linked so that if clicked, it will download or open. The files inside the directory will be files uploaded by customers. If the file name contains spaces, the link is broken and will not open, so I would like to have the spaces replaced with underscores.
I know that str_replace does what I'm looking for, but I'm not sure how to apply it to this code (which I did not write).
// Define the full path to your folder from root
$path = "uploads/artwork";
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
echo "<a href=uploads/artwork/$file>$file</a><br />";
}
// Close
closedir($dir_handle);
All help is greatly appreciated. Thank you!

You'd have to replace the filenames with underscores when you save them to the server, also.
Since you don't have the code on where you save the files, you can urlencode() the link URL so it will not be broken by hazardous characters. Note that originally it was broken by spaces because you didn't have the href value enclosed in quotes, which I'm doing here:
echo "<a href='" . urlencode("uploads/artwork/$file") . "'>$file</a><br />";
Otherwise, to replace spaces with underscores, you'd do:
echo "$file<br />";
But again, that would likely require you changing the file names on upload.
Note that you'll also want to call htmlentities() on the $file portion of that link, to prevent characters such as < from breaking the HTML page. So, the final result would be:
echo "<a href='" . urlencode("uploads/artwork/$file") . "'>" . htmlentities( $file) . "</a><br />";

Related

Issue with passing variables in url for php

I feel a bit stupid having to ask this, but for the life of me it won't work and I know I must be missing something small. I have the following PHP code for a gallery of model's photos. I have 2 pages. guests1.php and guests2.php. Guests1 shows the thumbnails and lists all the models. guests2 will show a particular model's individual portfolio. I am trying to pass the model name in the url, as I need it for the title on the second page and also for the directory name, so that the page knows where to find the pictures.
Simple enough, I thought, just add it into the url as a variable. No problem... however no matter how I write it, it will not put it in the url. The name of the model is always missing... however if I echo the variable it does it no problem?! The pages are working wonderfully apart from this one little thing and it's driving me bonkers. Any help most appreciated.
Here is the code :
<?php
echo "<div class=\"guests-gallery\">";
echo "<ul class=\"guests-gallery-list\">";
$dirs = glob("guests/*", GLOB_ONLYDIR);
foreach($dirs as $model) {
$files = glob($model. "/*.{jpg,png,gif,JPG}", GLOB_BRACE);
foreach($files as $file) {
$m = basename($model);
echo "<li><a href=\"index.php?page=guests2&model=\"" .$m. "\">";
echo "<img src=\"" . $file . "\" alt=\"" .basename($model). "\"></a><br />
<h3>" .basename($model). "</h3></li>";
}
}
echo "</ul></div>";
?>
You're making your code harder to read by double quoting and escaping your HTML quotes so you're not spotting your mistake with the quotes, make it easier to read and write by using single quotes on your echos leaving the double quotes for the html then you won't need to escape them and it'll be easier to spot the extra unnecessary " you included.
Try this:
<?php
echo '<div class="guests-gallery">';
echo '<ul class="guests-gallery-list">';
$dirs = glob("guests/*", GLOB_ONLYDIR);
foreach($dirs as $model) {
$files = glob($model. "/*.{jpg,png,gif,JPG}", GLOB_BRACE);
foreach($files as $file) {
$m = basename($model);
echo '<li><a href="index.php?page=guests2&model=' .$m. '">';
echo '<img src="' . $file . '" alt="' .basename($model). '"></a><br>
<h3>' .basename($model). '</h3></li>';
}
}
echo '</ul></div>';
?>
try removing the quote s from the model and maybe try using the & character without using it encoded:
echo "<li><a href=\"index.php?page=guests2&model=" .$m. "\”>something</a></li>";
Tell me if this works.

php echo filenames in a directory?

I am using the following php code to echo out the names (and extensions) of all the files in a folder.
This works fine and I am producing the results in a table like so:
code:
<?php
$dir = new DirectoryIterator("data/uploads/");
foreach ($dir as $fileinfo) {
echo '<table><tr><td><p>' . $fileinfo->getFilename() . "\n" . '</p></td><td><p>Existing File</p></td><td><p>Delete</p></td></tr><tr></tr></table>';
}?>
result:
. Existing File Delete
.. Existing File Delete
Filename1.jp Existing File Delete
Filename2.jp Existing File Delete
Filename3.jp Existing File Delete
The problem is in my results I am also getting those weird dots at the top. I do not know why these are being shown as I only have 3 files in the directory and don't know where the dots have come from?
Can anyone please help with this? thanks
Add Condition to check that is it file or not.. try this code
if ($fileinfo->isFile()) { // add this condition
echo '<table><tr><td><p>' . $fileinfo->getFilename() . "\n" . '</p></td><td><p>Existing File</p></td><td><p>Delete</p></td></tr><tr></tr></table>';
}
Add condition and check if it is . or .. if it satisfies the condition continue your looop

exif_imagetype() returning error on moving .gif (but still posts link to picture)

I've got a simple uploading script that works well for all file types (including non-moving .gif) that aren't moving .gifs. It uses exif_imagtype() to figure out whether or not a file is an image, then post a thumbnail or a text-link. The error I'm getting is:
Attachments: Warning: exif_imagetype(uploads/waterbaloons.gif): failed to open stream: No such file or directory in /var/www/oversized_shirt/logbook/daily_log/whichposts.php on line 57 Warning: exif_imagetype(uploads/waterbaloons.gif): failed to open stream: No such file or directory in /var/www/oversized_shirt/logbook/daily_log/whichposts.php on line 60 waterbaloons.gif
I bolded the last part; after all those errors, it still posts a (working) link to the .gif file. Every other type of image does not return an error (again, including non-moving .gif). Here is the relevant code. $filenames is just an array of filename strings.
#Displays a text-link or a thumbnail
foreach ($filenames as $filename){
$fileloc = "uploads/" . $filename;
if (exif_imagetype($fileloc) != False){
echo "<a href = '" .$fileloc. "'> <img src='" .$fileloc. "' height='150' width='150'></a>";
}
elseif (exif_imagetype($fileloc) == False){
echo "<a href='" .$fileloc. "'>" .$filename. "</a> &nbsp";
}
}
}
}
I could put '#' behind exif_imagetype(), but I'd like to know if there's anything I can do code-wise to stop this error. Is there, for example, a way of determining whether or not a .gif is a moving one? Or is there something just wrong w/ my code? Or is this just a job for a try-catch?

unable to show image from external hd php

I'm new with programming and learning now php. I have installed xamp and have write a little bit code. I have some images on my external hd and I want to show some pictures.
The problem is I can get a list of path of my images with this code:
echo "<html><body>";
$outerDir = "x:\map\maps\more\\";
$total = count (array_diff (scandir ($outerDir), Array (".", "..")));
$dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
foreach ($dirs as $d) {
if (!is_dir($outerDir . $d)) {
echo $d . "<br>";
}
}
but if I want to show it as an image, i can't show the image. I tried this in the foreach:
if (!is_dir($outerDir . $d)) {
$file = $outerhDir . $d;
echo 'img src="' . $outerDir . $d . '> <br>';
echo "<img src='" . $outerDir . '\\' . $d . "'alt='" . $d . "'> <br>";
}
But none of them work. I also tried the header and file_get_content like this:
if (!is_dir($outerDir . $d)) {
$file = $outerDir . $d;
header('Content-type: image/jpeg');
header('Content-Length:' . filesize($file));
$image = file_get_contents('$file');
echo $image . "<br>";
}
Even a simple html code wont work! Like this:
echo '<img src="x:\map\maps\more\needwonder.jpg"> <br>';
BUTTTT!! When I store one of the image in the same folder as my php file it will work! Like this:
echo '<img src="needwonder.jpg"> <br>';
But I dont want to put all my files in the same folder as the php file, because of security, technicaly, comfortable reasons AND I want to learn programming not to avoid issues or problems with my code.
So I hope I defined my problem good and hope that one of you guys and/or girls know the solution to help me out
If your image files aren't in a folder that's set up to be accessible by the web server, you can't display them on a web page. Simple as that. Put them in a web directory to use them.
It is possible to write a PHP script that proxies image files (kind of like what you're trying with file_get_contents()), but doing that requires a separate PHP file for the images, and it's best avoided unless absolutely necessary, as it can easily introduce security vulnerabilities, and performs poorly. If you do want to do that, though:
Link to the PHP script in place of an image, and pass it an identifier for the image as a parameter (e.g, <img src="img.php?image=blah">).
In that script, use that identifier to send the appropriate Content-Type, then use readfile() to output the image. (It's equivalent to echo file_get_contents(...), but more concise and performs better in some situations.)
MAKE ABSOLUTELY SURE that the parameter to that script cannot be manipulated to load a file that you didn't intend to make available. This includes trickery like ?image=../../wrong/file.

PHP fsize - possible reasons for failure?

I've got a question I can see being asked all around the internet but I haven't seen an answer that would help me.
Long story short; I've got a PHP script that lists files in a directory (file name, ctime). Both file name & creation date work fine, but I'm struggling with file-size.
This is the code that lists the files in a specific folder:
//show only files with 'xml' extension
if ($files[$b] != "." && $files[$b] != ".." && $ext == 'xml') {
echo "<tr style=\"border: 1px solid gray; background-color:";
if ($even) {
echo "#fff5cc;\">";
} else {
echo "white;\">";
}
echo "<td>$files[$b]";
echo "(" . filesize($files[$b]) . ")";
//echo filesize($files[$b]);
echo "</td>";
echo "<td>" . date("F d Y H:i:s.", filectime(UPLOAD_FOLDER . "/" . $files[$b])) . "</td>";
}
$even = !$even;
}
?>
Key stuff happens in the line code that shows the filesize; PHP error is 'Stat Failed...'. I have to admit I have no idea why because I'm able to open the file (one of the functions actually opens the XML file and places its contents to a text-area).
As most answers are about permissions, I actually tried adding 777 permissions to a test file and 777 to the folder where the file is saved, but to no avail. Thanks in advance!
I believe you have forgotten to link full path to the file. Have a look what do you few lines below:
filectime(UPLOAD_FOLDER . "/" . $files[$b])
So, the same should go everywhere:
filesize(UPLOAD_FOLDER . "/" . $files[$b])
Commentts below:
Also, I suppose $b is an iterator. If it is, you don't need $even variable, because you can use modulo operator:
if($b%2==0)
//event
Using other variable is not problem here, however it's good to be aware of other possible solutions.
I'd also let you know that there's a glob function. You could use it to get the XML file list:
$list = glob(UPLOAD_FOLDER . "/*.xml");

Categories