从php下拉菜单中显示所选图像

时间:2015-12-07 02:54:31

标签: php html

所以我有这个工作代码:

<?php 
                $folder = './images/'; 

                echo '<form action="" method="post">'."\n".'<select name="image">'."\n". 
                     dropdown(image_filenames($folder), @$_POST['image']). 
                     '</select>'."\n".'</form>'; 
                function image_filenames($dir) 
                { 
                    $handle = @opendir($dir) 
                        or die("I cannot open the directory '<b>$dir</b>' for reading."); 
                    $images = array(); 
                    while (false !== ($file = readdir($handle))) 
                    { 
                        if (eregi('\.(jpg|gif|png)$', $file)) 
                        { 
                            $images[] = $file; 
                        } 
                    } 
                    closedir($handle); 
                    return $images; 
                }   
                function dropdown($options_array, $selected = null) 
                { 
                    $return = null; 
                    foreach($options_array as $option) 
                    { 
                        $return .= '<option value="'.$option.'"'. 
                                   (($option == $selected) ? ' selected="selected"' : null ). 
                                   '>'.$option.'</option>'."\n"; 
                    } 
                    return $return; 
                } 
                ?>

这是创建一个下拉菜单,其中包含my / images文件夹中列出的内容。如何发布所选图像?

1 个答案:

答案 0 :(得分:0)

如果您向表单添加提交按钮,则可以发布所选图像。在下面的代码中,它检查post变量(如果表单已提交),然后您可以使用$_POST['image']执行某些操作,这是在表单中选择的值。

// if the form is submitted
if (isset($_POST['submit'])) {
    // the selected image will be $_POST['image']
        // do something with the posted image name
    var_dump($_POST);
}

$folder = './images/'; 

echo '<form action="" method="post">'."\n".'<select name="image">'."\n". 
     dropdown(image_filenames($folder), @$_POST['image']). 
     '</select>'."\n".'<input type="submit" name="submit">'."\n".'
     </form>'; 
function image_filenames($dir) 
{ 
    $handle = @opendir($dir) 
        or die("I cannot open the directory '<b>$dir</b>' for reading."); 
    $images = array(); 
    while (false !== ($file = readdir($handle))) 
    { 
        if (preg_match('/^.*\.(jpg|jpeg|png|gif|svg)$/', $file)) 
        { 
            $images[] = $file; 
        } 
    } 
    closedir($handle); 
    return $images; 
}   
function dropdown($options_array, $selected = null) 
{ 
    $return = null; 
    foreach($options_array as $option) 
    { 
        $return .= '<option value="'.$option.'"'. 
                   (($option == $selected) ? ' selected="selected"' : null ). 
                   '>'.$option.'</option>'."\n"; 
    } 
    return $return; 
}