2012-03-14 4 views
0

У меня есть функция загрузки изображений, которую я создал несколько недель назад - у нее есть переменная с именем $ newname, которая содержит путь и файл.Расширить переменную от одной функции до другой

Я использую функцию imageupload() в другой функции EditFrontPage(), которая используется для «обновления» некоторого содержимого.

Если я обновляю изображение, он запускает функцию imageupload, которая отличная, она изменяет размер и оптимизирует изображение и перемещает его в указанную папку.

То, что я тогда хочу, входит в мою функцию EditFrontPage(), состоит в том, чтобы вызывать переменную $ newname из функции imageUpload.

есть ли способ сделать это? умным способом? : D

Вот мой код:

<?php 
function EditFrontPage($db) 
{ 
    $stmt = $db->prepare("SELECT `id`, `heading`, `content`, `image` FROM `content` WHERE `page` = 'forside';"); 
    $stmt->execute(); 
    $row = $stmt->fetch(PDO::FETCH_ASSOC); 
    if(isset($_POST['EditFrontpageSubmit'])) 
    { 
     imageUpload(10000, 100, 100, '', 5); 
     global $newname; 
     echo $newname; 
    } 
?> 
    <form class="adminForm" enctype="multipart/form-data" action="" method="post"> 
     <h2>Overskrift</h2> 
     <input type="text" value="<?=$row['heading']?>" /> 
     <input type="file" name="image[]" /> 
     <h2>Tekst</h2> 
     <textarea><?=br2nl($row['content'])?></textarea> 
     <input type="submit" name="EditFrontpageSubmit" value="Opdater nyhed" /> 
    </form> 
<?php 
} 


function imageUpload($maxsize = 2000, $quality = 95, $imgwidth = 400, $imgheight = '', $numOfImages = 5, $path = '/lucas/images/') 
{ 
    // Turn on error reporting 
    error_reporting(-1); 

    //Set the max upload size in kilobytes 
    define("MAX_SIZE", "$maxsize"); 

    if(empty($imgheight) && empty($imgwidth)) 
    { 
     echo "<h1>Fejl: Definer bredde eller højde</h1>"; 
     die(); 
    } 

    //Makes a function that check the extension 
    function getExtension($str){ 
     $i = strrpos($str, "."); 
     if(!$i){return "";} 
     $l = strlen($str) - $i; 
     $ext = substr($str,$i+1,$l); 
     return $ext; 
    } 

    //Set errors to 0 from standard 
    $errors = 0; 

    //Define the size as a variable 
    $size = ''; 
     //foreach image selected 
     foreach($_FILES['image']['error'] as $key => $error) 
     { 
      //If no errors, return true 
      if($error == UPLOAD_ERR_OK) 
      { 
       //Gets the filename 
       $filename = stripslashes($_FILES['image']['name'][$key]); 

       //Gets the extension 
       $extension = getExtension($filename); 

       //convert the extension to lowercase 
       $extension = strtolower($extension); 

       //if the file extension doesn't match, return error 
       if(($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
       { 
        echo "<h1>Unknown Extension!</h1>"; 
        $errors = 1; 
       } 
       //This check if the amount of images is over 5. 
       elseif(count($_FILES['image']['name']) > $numOfImages) 
       { 
        //If it's over 5 images, return error and exit 
        echo "Too many images"; 
        exit(); 
       } 
       else 
       { 
        //Get the filesize of the image (total amount if multiple images). 
        $size += filesize($_FILES['image']['tmp_name'][$key]); 

        //if the filesize is over the defined amount 
        if($size > MAX_SIZE*1024) 
        { 
         echo "<h1>Du har overskredet maksimum fil-upload størrelse!</h1>"; 
         $errors = 1; 
        } 

        //This renames the image, to contain, the microtime, and a unique ID + extension 
        $image_name = microtime(true) . uniqid('',true) . '.' . $extension; 

        //This sets the path of the image. 
        $newname = $_SERVER['DOCUMENT_ROOT'] . $path . $image_name; 

        //It moves the file(s) to the path defined above! 
        $copied = move_uploaded_file($_FILES['image']['tmp_name'][$key], $newname); 

        //Check if the extension is png 
        //if($extension == "png") 
        //{ 
         //converts the quality from 'jpeg/gif' quality to png compression method 
         //$pngquality = round($quality/100 * 9); 

         //Executes a shell command optimizing the png 
         //shell_exec("gm mogrify -quality $pngquality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname"); 
        //} 
        //else 
         //Executes a shell command optimizing the jpeg/gif 
         //shell_exec("gm mogrify -quality $quality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname"); 


        //If the image isn't copied, return an error 
        if(!$copied) 
        { 
         echo "<h1>Der skete en fejl!</h1>"; 
         $errors = 1; 
        } 

        //Creates an array of the images 
        $array[] = $newname; 

       } 
      } 
     } 

    //If the submit is set, and errors = 0 return true 
    if(isset($_POST['Submit']) && $errors != 1) 
    { 
     echo "<h1>Fil blev uploaded som den skulle!</h1>"; 

     //Makes a for loop, that echo's out all uploaded images 
     for($i = 0; $i < count($array); $i++) 
     { 
      echo "<img src='{$array[$i]}' /><p>".preg_replace("/.*\//i", '', $array[$i])."</p>"; 
     } 

    } 
} 

?> 

Спасибо много парней!

+0

не может imageUpload() вернуть новое имя? –

ответ

2

ли функция imageupload() вернуть переменную $newname, а затем установить его как и на EditFrontPage() функции:

$newName = imageUpload(10000, 100, 100, '', 5); 
1

просто return $newname в конце imageUpload функции и изменять эту часть:

if(isset($_POST['EditFrontpageSubmit'])) 
{ 
    echo imageUpload(10000, 100, 100, '', 5); 
} 
Смежные вопросы