slim php framework image upload put database

前端 未结 2 1193
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 22:48

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.

2条回答
  •  名媛妹妹
    2021-01-31 23:50

    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!!  

    Try again'; return; } $plural = ($imageCount == 1) ? '' : 's'; foreach($imgs as $img) { printf('%s
    ', $img['name'], $img['url']); } }

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

提交回复
热议问题