I have this code to list the images in a directory into a dropdown so that I can then select an image and save the image name selected into a flat file for later use in other programs/scripts. When I come back to make changes I have to re-select the image and I would like to be able to have it remember the image as selected via the variable.
It's been a while since I've been fluent in php as I've been undergoing medical treatments and the medicine has affected my memory and I've tried to work out an elseif statement but it wasn't successful, I think the while loop is overriding it. The functions file sorts the directory files and the info file is the flat file. It works, except it doesn't allow me to show the selected image in the dropdown menu when the page is reloaded.
Thanks in advance for any help.
<?php
include ("functions.php");
include ("info_file1.php");
// Settings section ------------------------------
$filedir = "files/"; // The file folder
$columns = 1; // Number of columns of files listed per row
global $filename;
global $filename_sorted;
$i=0;
$j=0;
$k=0;
$m=0;
// Table Title row -------------------------------
echo "<select name=Image id=Image>";
if (file_exists($filedir)) {
$handle = opendir($filedir);
while (false !==($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$filename[$i][1] = $file;
$filename[$i][2] = date ("m/d/y", filemtime($filedir.$file));
$filename[$i][3] = round(filesize($filedir.$file)/1024);
++$i;
}
}
closedir($handle);
// Sorting --------------------------------------------
$filename_sorted = ($filename);
// End of Sorting -------------------------------------
while($m<(count($filename)))
{
echo "<option value=".$filename_sorted[$m][1].">".$filename_sorted[$m][1]."</option>";
$m++;
}
} elseif ( $image=$filename_sorted[$m][1] )
echo "<option value=".$image." selected>".$image."</option>";
else {
echo "<option value=Upload Image First>Upload Image First</option>";
}
echo "</select>";
?>
Related
Am a php novice and in need of some help. Basically I have a script that populates a drop down select bar using php. I want to retain the value the user selects in this drop down after submission, so the user does not have to select it again, here is the snippet of the script that I am trying to work with.
<?php
// Start the session
session_start();
$_SESSION["dir"] = $_POST['hiddenVal'];
//echo "hi at last" .$_SESSION["dir"];
?>
<script>
function loadValues()
{
var $x=obj.options[obj.selectedIndex].value;
document.getElementById("hiddenVal").value = $x;
//alert(document.getElementById("hiddenVal").value);
}
</script>
<script>
function country(obj){
//alert(obj.options[obj.selectedIndex].value); //if you want to show in alart
//or put in a variable
var $x=obj.options[obj.selectedIndex].value;
document.getElementById("hiddenVal").value = $x;
alert($x);
}
</script>
<body onload="loadValues();">
<form action="dir20.php" method="post">
<input type="hidden" id="hiddenVal" name = "hiddenVal"/>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
<?php
$path = '/docdownloads';
//echo 'php_'.$abc;
$dirs = array();
// directory handle
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
if ($entry != '.' && $entry != '..') {
if (is_dir($path . '/' .$entry)) {
$dirs[] = $entry;
//echo "$entry</br>";
}
}
}
?>
<select name="country" id="country" onChange="country(this)" required>
<!--<option value="">-----------------</option>-->
<?php
asort($dirs);
reset($dirs);
foreach($dirs as $p => $w):
echo '<option value="'.$w.'">'.$w.'</option>'; //close your tags!!
endforeach;
?>
</select>
<?php
$tex = $_SESSION["dir"];
//$def = "docdownloads";
//$dir = "c:/".$tex;
$dir = "c:/docdownloads/".$tex;
//echo "tex is". "$dir";
echo "</br>";
//if ($handle = opendir('.')) {
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry</br>";
}
}
closedir($handle);
}
?>
You're going to want to check the $_GET var against the selected option. If the current option exists and it has been selected, then give the option the selected attribute.
-----------------
<?php
asort($dirs);
reset($dirs);
foreach($dirs as $p => $w):
$selected = isset($_GET['country']) && $_GET['country'] === $w ? "selected" : "";
echo '<option value="'.$w.'"'.$selected.'>'.$w.'</option>';
endforeach;
?>
</select>
You will need to assign a ID for user if you havent already, then save the submitted option in your database with corresponding ID. Then when you load you'r dropdown box insert a IF clause in your script to check if user has already saved a option.
To achieve that you should save the value the user chose into session
and always when displaying the form, you should check if the value exists in the session and if it exists - display it as selected option.
get the submitted value of country by GET or POST(depend on your form method) and compare it in foreach loop
$countryId = isset($_POST['country']) ? $_POST['country'] : ''; //or $_GET['country'];
foreach($dirs as $p => $w):
$selected = $countryId==$w ? 'selected' : '';
echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
endforeach;
Assuming your form action is on same page, if different, store country value in session and retrieve it from session in this page
Blockquote You need to put your select element inside your form. Otherwise it won't submit
problem solved, script now works, many thanks!
I have a drop down list that generates all files in a folder, which is working. But i would like to only see .jpg files and also i would like to exclude one file from the list as it is a place holder image lets call it "0001_Place_Holder.jpg".
The second part to this is that i want to pick a file from the dropdown list and copy it to a New folder then delete the original image.
this is "move_files_general.php" // which generates my dropdown list
<?php
$dirname = "general_2";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality" class="submit" />';
echo '</form>';
?>
This is "move_general.php" // which should copy the file then delete the original
<?php
$dirpath = "general_2";
$dirpath_2 = "quality_2";
$file_to_move = $_GET['file2'];
copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move") or die("Unable to copy");
if (copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move")) {
unlink("$dirpath.'/'.$file_to_move");
if ( unlink ($dirpath.'/'.$file_to_move) ) {
echo $file_to_move . " deleted.";
echo '<script>parent.window.location.reload(true);</script>';
} else {
echo "Error.";
}
}
?>
You would test the filename if its extension is jpg and if it is not equal to your placeholder name.
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
For the second issue: try to set the folder permissions to 777 for testing purpose. Also echo the strings that you pass to copy(string1,string2) in order to check if something is wrong in there.
First off, Thanks for your answers, and help. Alex Odenthal, that worked for the 1st part. i tried everything to get the 2nd part to work. I finally rewrote it a different way and it's working now, I must have had something wrong , somewhere.
Here is my fixed "move_files_general.php"
<?php
$dirname = "general";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder_DO_NOT_DELETE.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality1" class="submit" />';
echo '</form>';
?>
Here is my fixed "move_general.php"
<?php
$file_to_move = $_GET['file2'];
$source = "general/$file_to_move";
$dest = "quality/$file_to_move";
copy($source, $dest);
if (copy($source, $dest)) {
unlink($source);
if(file_exists($source)) {
unlink($source); }
else {
echo "Deleted.";
}
}
?>
I have done a program using PHPExcel and TCPDF on PHP. where I can select companies listed in excel file according to column that they are located.
I am tracking companies between already defined columns and between rows that I can scan till "next company's name". So that I can print them out in the screen.
I upload a screenshot how my excel file looks like...
after I retrieve the data from excel file it looks like
However, when I select last company since there is no "next company", it doesn't return result; on the contrary it gives an error.
my question: how can I control "last company" and print it out like the others. I couldn't put an exceptional condition for last one.
related part of my code looks like this:
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//echo "selected row value :".$only_row[1]. "<br />"; this shows selected company's row number
for($i=0; $i< $count; $i++)
{
if ($comp[$i][2]== $only_row[1])
{
$info_end=($comp[$i+1][2]-1);// here table ends before the next company's name begins
}
}
}
else{error_reporting(E_ALL ^ E_NOTICE);}
$rowCompanyInfoStart = $only_row[1]+2;
$rowCompanyInfoEnd = $info_end;
$colCompanyInfoStart = 'C';
$colCompanyInfoEnd = 'M';
PS: it would be appreciated if you can give a clear answer.
If something is unclear on the question, please let me know.
All you got to do is a test on $i, because you can't access $comp[$i+1][2]-1 when $i = $count-1.
So to do something different if this is the last line :
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
} else {
// what to do normally
$info_end=($comp[$i+1][2]-1);
}
}
}
thanks to #Random
here is my full solution with exception for the last company
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//var_dump($only_row);
//echo "selected row value :".$only_row[1]. "<br />";
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
$info_end=($objPHPExcel->setActiveSheetIndex(0)->getHighestRow());
}
else {
$info_end=($comp[$i+1][2]-1);
}
}
}
}
I'm currently making a droplist but in the droplist let's say I only want to include only .txt extension files so any other extensions like .php .jpg or any other extensions will not be in in the droplist. How can I do that as simple as possible?
Another question is I want to make a warning IF the folder does not have any .txt extension files an error message will show. So even if there are other .jpg .php or any other files inside as long as there's no .txt file in the folder a warning will show.
Anyone able to give me a hand?
This is what I have done but it only shows a drop-list with no .txt at the end but it will still show other random files in the drop-list though.
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if(($list == ".") || ($list == ".."))
{
continue;
}
echo "<option value=\"";
echo basename($list,".txt");
echo "\">";
echo basename($list,".txt");
echo "</option>";
}
echo "</select>";
echo "</form>";
editted added the substr with $hasTxt
<?php
if(!(is_dir("./aaa")))
{
die("Must create a <strong>aaa</strong> folder first, sorry");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select name=\"aaa\">";
$aaa_files = scandir("./aaa");
$hastxt = false;
foreach($aaa_files as $file_list)
{
if(($file_list == ".") || ($file_list == ".."))
{
continue;
}
if(strlen($file_list)>4 && strtolower(substr($file_list, -4))!='.txt')
{
continue;
}
else
{
$hastxt = true;
echo "<option value=\"";
echo basename($file_list,".txt");
echo "\">";
echo basename($file_list,".txt");
echo "</option>";
}
}
echo "</select>";
echo "<br/><input type=\"submit\">";
echo "</form>";
if($hastxt == false)
{
echo "Must create text files first, sorry";
die();
}
?>
This is what happens for the script that I have now if the folder does not have any txt files.
This is what I actually want if there's no txt file but of course without the arrow
For the first part, just like you continue on directories . and .., you can continue on non-text files:
if(strlen($list)>4 && strtolower(substr($list, -4))!='.txt') continue;
For the warning part, put a flag before the foreach
$hasTxt = false;
And set it to true whenever you get input you don't ignore (ie. after the if(unwanted) continue;)
$hasTxt = true;
Finally, after the foreach check the value of $hasTxt and use it as you prefer.
You could use PHP's substr() function to test the filenames:
if(substr($filename, -3) == 'txt') {
// show file
}
See here: http://php.net/manual/en/function.substr.php
Try this , Hope it will work you
<?php
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
$i =0;
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
$i++;
}
}
if($i == 0){
die("the folder does not have any .txt extension files");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
echo "<option value=\"".substr($list,0, -4)."\">".substr($list, 0,-4)." </option>";
}
}
echo "</select>";
echo "</form>";
?>
I have this drupal slideshow which pulls images from a folder sequentially by image title (01_title.jpg, 02_title.jpg, etc..)
I was wondering if there is an easy way to randomize the images, so it starts with a different image every time you refresh the page?
you can view the slideshow here http://www.rubensteinpr.com/
Thanks!
<div id ="index">
<?php
// Note that !== did not exist until 4.0.0-RC2
$desired_extension = 'jpg'; //extension we're looking for
$banner_imgs_array = array(); // array of banner images
$banner_imgs = ''; // sting of banner images names comma dileneated
if ($handle = opendir(file_directory_path().'/banner_imgs')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(($file != ".") and ($file != "..")) {
$fileChunks = explode(".", $file);
if($fileChunks[1] == $desired_extension) //interested in second chunk only
{
$banner_imgs_array[] = $file;
}
}
}
closedir($handle);
$banner_imgs = implode(',', $banner_imgs_array);
}
?>
<div id="banner"><img src="<?php print file_directory_path(); ?>/temp_banner.jpg" width="702" height="310" border="0"></div>
<div id="bannerText">media relations • strategic planning • digital communications • crisis management</div>
<script type="text/javascript">
// <![CDATA[
var so = new SWFObject("<?php print file_directory_path(); ?>/banner.swf", "ban", "702", "310", "8", "#ffffff");
so.addParam('menu', 'false');
so.addParam("wmode", "transparent");
so.addParam("base", "<?php print file_directory_path(); ?>");
so.addVariable("banner_imgs", "<?php print $banner_imgs; ?>");
so.write("banner");
// ]]>
</script>
</div>
adding
shuffle($banner_imgs_array);
line just before
$banner_imgs = implode(',', $banner_imgs_array);
should do the trick.
array_rand will return one or more random array keys. If you want to shuffle the array itself, use shuffle.