gentle gentle - 2 months ago 7
PHP Question

How to Upload a file MVC php

I have this code:

// assign params by methods
switch($method){
case "GET": // view
// we need to remove _route in the $_GET params
unset($_GET['_route']);
// merege the params
$this->params_ = array_merge($this->params_, $_GET);
break;
case "POST": // create
case "PUT": // update
case "DELETE": // delete
{
// ignore the file upload
if(!array_key_exists('HTTP_X_FILE_NAME',$_SERVER))
{
if($method == "POST"){
$this->params_ = array_merge($this->params_, $_POST);
}else{
// temp params
$p = array();
// the request payload
$content = file_get_contents("php://input");
// parse the content string to check we have [data] field or not
parse_str($content, $p);
// if we have data field
$p = json_decode($content, true);
// merge the data to existing params
$this->params_ = array_merge($this->params_, $p);
}
}
}
break;
}


from http://www.elvishsu.com/2014/01/start-your-own-mvc-framework-with-php.html#.V7lBVnUrLxs

Please can anyone tell me how to deal with file uploads in this situation
I mean how should I deal with:

if(array_key_exists('HTTP_X_FILE_NAME',$_SERVER))


Thanks

Answer

This is what I resolve into:

// assign params by methods  
    switch($method){
        case "GET": // view
            // we need to remove _route in the $_GET params
            unset($_GET['_route']);
            // merege the params
            $this->params_ = array_merge($this->params_, $_GET);               
        break;
        case "POST": // create
        case "PUT":  // update
        case "DELETE": // delete
        {

                if($method == "POST" && isset($_FILES)){
                    if (!empty($_FILES))
                    {
                        $this->params_ = array_merge($this->params_, $_POST);
                        $this->params_ = array_merge($this->params_, $_FILES);                            
                    }else{
                        $this->params_ = array_merge($this->params_, $_POST); 
                    }
                }else{           
                    // temp params 
                    $p = array();
                    // the request payload
                    $content = file_get_contents("php://input");
                    // parse the content string to check we have [data] field or not
                    parse_str($content, $p);
                    // if we have data field
                    $p = json_decode($content, true);
                    // merge the data to existing params
                    $this->params_ = array_merge($this->params_, $p);
                }   

        }
        break;                
    }

I put it here in case anyone is also trying to build MVC from that tutorial and find it difficult to upload Thanks everyone

Comments