I was trying to populate my dropdown menu with file names from a directory, I have searched for articles here at SO regarding this inquiry I found several answers and tried them but none of them seems to work which I find weird because they were chosen as answers and some of them have High votes
take this article for example this is one of the reference that I have tried but it seems like it does not work for me
Here is my code based on the reference link that I Have provided
<select name="templ" class="form-control input-sm">
<?php
foreach(glob(dirname(__FILE__) . '/els-content/*') as $filename){
$filename = basename($filename);
echo "<option value='" . $filename . "'>".$filename. </option>";
}
?>
</select>
this does not return any values at all. What could be the problem ?
Hi Ok so I was able to answer my own question because of what #bobdye had pointed out, okayyy I'll cut to the chase here is how it was solved
dirname(FILE) . '/els-content/*'
returns the current directory plus the string '/els-content/*' which my problem is the files from els-content does not show on my dropdown so I used echo to check what does that return so I find out that it returns something like this
Users/WhosPC/Desktop/cms_form/myPadmin/els-content/*
in which els-content is FOUND OUTSIDE the myPadmin meaning els-content is on the same level as my myPadmin so what I did was I used chdir() then used getcwd() inside a variable
so what it look like was
<?php
chdir('../');
$s = getcwd();
?>
<select name="templ" class="form-control input-sm">
<?php
foreach(glob($s . '/els-content/*') as $filename){
$filename = basename($filename);
echo "<option value='" . $filename . "'>".$filename."</option>";
}
?>
</select>
although I'm not sure if chdir('../') and getcwd() is reliable enough for this kind of task.. when this cms baby is on the real world up and runnning
feel free to critize this script so I can improve this further
UPDATED CODE
$s = realpath(getcwd()."/..");
foreach(glob($s . '/els-content/*') as $filename){
$filename = basename($filename);
echo "<option value='" . $filename . "'>". $filename."</option>";
}
Ok I didnt delete the 1st version of my code so that users who stumble on this post could see the difference of the 1st one and the 2nd code that
#prodigitalson had pointed out on my 1st code snippet
Related
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.
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.
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");
I have a piece of php that if a specified folder has a file in, it will display the filename, date created and present a download button, if the folder is empty it will show nothing. This works very well but if I have more than one file in the folder it bunches all the filenames together - what I want is the separate information displayed for every file.
To help you understand the problem here is an image showing the problem and the code. I got very far on my own but its way above my head, I just cant see a simple way to correct the problem. The code may look very awkward and odd as I'm totally new at this but it looks visually right on the browser. I would really appreciate any help thank you.
Here is an image of the problem: http://i46.tinypic.com/m79cvs.png
<?php if (!empty($thelist)) { ?>
<p class="style12"><u>Fix</u></p>
<p class="style12"><?=$thelist?><?php echo " - " ?> <?php $filename = '../../customers/client1/client1.fix.exe';
if (file_exists($filename)) {
echo "" . date ("m/d/Y", filemtime($filename));
}
?> <?php echo " - <a href='download.php?f=client1/client1.fix.exe'><b>Download</b></a> <a href='download.php?f=client1/client1.fix.exe'>
<img src='../css/images/dlico.png' alt='download' width='35' height='32' align='absmiddle' /></a>" ?>
</p>
<?php } ?>
The list ($thelist) contains your files, yes?
You are not working on the $thelist, but on the $filename which is a hardcoded string.
Why? Currently you are outputting <?=$thelist?> and it looks like concatenated string from filenames. I would suggest that $thelist should be something like an array of your files. Then you could iterate over the files and output html dynamically for each entry.
<?php
// define your directory here
$directory = xy;
// fetches all executable files in that directory and loop over each
foreach(glob($directory.'/*.exe') as $file) {
// output each name and mtime
echo $file . '-' . date ("m/d/Y", filemtime($file));
// or you might also build links dynamically
// $directory needs to be added here
echo ''.$file.' - Size: '.filesize($file).'';
}
?>
I am printing an image using an ID which is generated. however i wanted to do a check to see if this image exists and if it doesnt print no-image.jpg instead...
<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" />
It would be great if this could be kept on one line is possible. Any help would be appreciated.
What Kristopher Ives says, and file_exists:
echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")
btw, your snippet is unlikely to work, as you seem to be combining plain HTML output and PHP without putting the PHP into <? ?>
My recommendation would actually be to abstract the decision making from the html tag itself, in a separate block of php logic that is not outputting html...here is an abbreviated example that assumes you are not using a template engine, or MVC framework.
<?php
$filename = 'th.jpg';
$filePath = '/public/images/' . $row['id'] '/';
$webPath = '/images/' . $row['id'] . '/';
//Logic to get the row id etc
if (!file_exists($filePath . $filename)) {
$filename ='no-image.jpg';
$webPath = '/images/';
}
?>
<img src="<?php echo $webpath . $filename;?>" />
Wow, this question gets asked and answered a lot:
http://en.wikipedia.org/wiki/Ternary_operation
You could do it by:
<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >