giobi
4/5/2018 - 6:16 PM

DCurl

Class for OOP curl interaction

<?php

class DCurl {
    private $ch;
    private $output;
    public $input;
    private $url;

    public function __construct($url, $method, $input = []) {
        $this->url = $url;
        $this->ch = curl_init($url);
        $this->input = json_encode($input);

        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->input);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: '.strlen($this->input)
        ]);

        return $this;
    }

    public function setHeader(array $header) {
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);
        return $this;
    }

    public function setPassword($password) {
        curl_setopt($this->ch, CURLOPT_USERPWD, 'user:'.$password);
        return $this;
    }

    public function run() {

        $this->output = curl_exec($this->ch);
//        print_r($this->url);
        $this->close();
        return $this;

    }

    public function getOutput() {
        return $this->output;
    }

    public function getError() {
        return curl_error($this->ch);
    }

    public function close() {
        curl_close($this->ch);
    }
}