symfony 4 create post request in proccess

Viewed 2078

I want to create function which will execute other url (this url generate file on server) and get responce and then send message to user, but I want not to use ajax, I try to user Reqeust object but it don't work.

public function testCreateFile() {

    $uri = 'http://someuri/somefuncition';
    $method = 'POST';
    $paramaters = array(
        'csv' => '20190102212655-product-test.csv',
        'type' => '5', 

    );
   $request = new Request();
   $request->create($uri,$method,$paramaters);


    return new Response("Message to user") ;
}

How I should do coreectly?

Thanks for help in advance.

1 Answers

What you need is curl. The best way is to use bellow code as Service, so I'll give the complete Class

The Service class

<?php
    App\Services;

    class PostRequest
    {
        static function get_data(String $url, Array $post_parameters)
        {
            //url-ify the data for the POST
            $parameters_string = "";

            foreach($post_parameters as $key=>$value) {
                 $parameters .= $key.'='.$value.'&'; 
            }

            rtrim($fields_string, '&');

            //open connection
            $ch = curl_init();

            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_POST, count($post_parameters));
            curl_setopt($ch,CURLOPT_POSTFIELDS, $parameters);

            //execute post
            $result = curl_exec($ch);

            curl_close($ch);

            return $result;
        }
    }
?>

So after including use App\Services\PostRequest; inside your Controller, you can do this

public function testCreateFile() {
    $uri = 'http://someuri/somefuncition';
    $paramaters = [
        'csv' => '20190102212655-product-test.csv',
        'type' => '5',
    ];
    $request = PostRequest::get_data($uri, $paramaters);
    return new Response("Message to user") ;
}
Related