php 纤薄的php框架图片上传把数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25016307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:36:07  来源:igfitidea点击:

slim php framework image upload put database

phpfile-uploadslim

提问by Jasonsti

I am new to slim php framework, I want to upload an image and put the file name in the database via POST, can some one kindly give me some example code.

我是瘦 php 框架的新手,我想通过 上传图像并将文件名放入数据库中POST,有人可以给我一些示例代码。

回答by Muhaimin

Here's the router:

这是路由器:

$app->post('/', 'uploadFile');

this will point to the function below:

这将指向下面的函数:

function uploadFile () {
    if (!isset($_FILES['uploads'])) {
        echo "No files uploaded!!";
        return;
    }
    $imgs = array();

    $files = $_FILES['uploads'];
    $cnt = count($files['name']);

    for($i = 0 ; $i < $cnt ; $i++) {
        if ($files['error'][$i] === 0) {
            $name = uniqid('img-'.date('Ymd').'-');
            if (move_uploaded_file($files['tmp_name'][$i], 'uploads/' . $name) === true) {
                $imgs[] = array('url' => '/uploads/' . $name, 'name' => $files['name'][$i]);
            }

        }
    }

    $imageCount = count($imgs);

    if ($imageCount == 0) {
       echo 'No files uploaded!!  <p><a href="/">Try again</a>';
       return;
    }

    $plural = ($imageCount == 1) ? '' : 's';

    foreach($imgs as $img) {
        printf('%s <img src="%s" width="50" height="50" /><br/>', $img['name'], $img['url']);
    }
}

If anyone have better answer, please be welcome to alter mine.

如果有人有更好的答案,欢迎修改我的。

回答by flawyte

The creator of Slim has made a library to handle file uploading through Slim: https://github.com/brandonsavage/Upload

Slim 的创建者制作了一个库来处理通过 Slim 上传文件:https: //github.com/brandonsavage/Upload