2015-12-07 55 views
0

所以我有這樣的工作代碼:顯示從PHP所選圖像下拉菜單

<?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; 
       } 
       ?> 

這是創建一個下拉從我的/ images文件夾中列出的內容菜單。我如何發佈選定的圖片?

回答

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; 
}