dsbruqxgt820011351 2012-03-14 08:30
浏览 41
已采纳

将变量从一个函数扩展到另一个函数

I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file.

I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content.

If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified.

What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function.

is there a way to do this? in a smart way? :D

Here is my code:

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

    }
}

?>

Thank you a lot guys!

  • 写回答

2条回答 默认 最新

  • doutan8506 2012-03-14 08:36
    关注

    Have the imageupload() function return the $newname variable, and then set it like so on the EditFrontPage() function:

    $newName = imageUpload(10000, 100, 100, '', 5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?