How to get uploaded image url using the Discourse API?

function _curl($url,$poststr='',$httpheader=array(),$usecookie=false){
        $ch = curl_init();
        $SSL = substr($url, 0, 8) == "https://" ? true : false;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        if ( $SSL ) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        }
        if( $poststr!='' ){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $poststr);
        }
        if( $httpheader ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        }
        if( $usecookie ){
        	$cookie_jar = APPPATH.'cache/logs/curl_cookie_'.md5($url).'.log';
        	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
        }
        
        $data = curl_exec($ch);
        curl_close($ch);
        return  $data;
    }

Curl is a tool and libcurl is a library for transferring data with URL syntax. It not just gets a URL and some query parameters
Before, I can use this curl function to submit data to discourse server when I create a new topic.

Look down a successful example to create a new topic using the api.

public function create_topic($params) {
        $url = 'http://hostname/posts?api_key=api_key&api_username=api_username';
        $poststr = http_build_query(array('raw' => $params['raw'], 'title' => $params['title'], 'category' => $params['category']));
        $result = array('success' => false, 'msg' => 'failed');
        if(($data=_curl($url, $poststr)) && ($json = json_decode($data, true))) {
            if( !empty($json)) {
                if(isset($json['errors'])) {
                    $result['msg'] = $json['errors'][0];
                }
                else {
                    $result['success'] = true;
                }
            }
        }
        return $result;
    }

Thank you.:stuck_out_tongue:

1 Like