Pastebin.ca PHP API

In my boredom, I find I do a lot of things. Some of those things range from very silly to intense coding sessions. So, out of boredom tonight, I have built a script to use the Pastebin.ca API to make pastes remotely.

Below you will find the code and an example. Let me know if you have any issues 🙂

UPDATES:

  • November 20, 2017: Small changes to code, a little cleanup.

<br />
&lt;?php</p>
<p>/**<br />
 * Object oriented wrapper for the cURL library.<br />
 *<br />
 * @author  Eric Sizemore &lt;admin@secondversion.com&gt;<br />
 * @author  David Hopkins &lt;semlabs.co.uk&gt;<br />
 * @package OO cURL Class<br />
 *<br />
 * Based on the cURL class by David Hopkins (semlabs.co.uk).<br />
 */<br />
class cURL<br />
{<br />
    private static $instance;</p>
<p>    public $sessions = [];<br />
    public $retries  = 0;</p>
<p>    /**<br />
     * Constructor.<br />
     */<br />
    private function __construct() {}</p>
<p>    /**<br />
     * Creates an instance of the class.<br />
     * @return	cURL<br />
     */<br />
    public static function getInstance(): cURL<br />
    {<br />
        if (!self::$instance) {<br />
            self::$instance = new self();<br />
        }<br />
        return self::$instance;<br />
    }</p>
<p>    /**<br />
     * Adds a cURL session.<br />
     *<br />
     * @param	$url		string	URL<br />
     * @param	$options	array	Optional array of cURL options/values<br />
     */<br />
    public function addSession(string $url, array $options = [])<br />
    {<br />
        $this-&gt;sessions[] = curl_init($url);</p>
<p>        if (!empty($options)) {<br />
            $this-&gt;setOptions($options, (count($this-&gt;sessions) - 1));<br />
        }<br />
    }</p>
<p>    /**<br />
     * Sets an option to a cURL session.<br />
     *<br />
     * @param	$option		constant	cURL option<br />
     * @param	$value		mixed		value of option<br />
     * @param	$key		integer		session key to set option for<br />
     */<br />
    public function setOption($option, $value, int $key = 0)<br />
    {<br />
        curl_setopt($this-&gt;sessions[$key], $option, $value);<br />
    }</p>
<p>    /**<br />
     * Sets an array of options to a cURL session.<br />
     *<br />
     * @param	$options	array		array of cURL options/values<br />
     * @param	$key		integer		session key to set option for<br />
     */<br />
    public function setOptions(array $options, int $key = 0)<br />
    {<br />
        curl_setopt_array($this-&gt;sessions[$key], $options);<br />
    }</p>
<p>    /**<br />
     * Executes as cURL session.<br />
     *<br />
     * @param	$key	integer		Optional argument if you want to execute only one session<br />
     */<br />
    public function exec($key = false)<br />
    {<br />
        $session_count = count($this-&gt;sessions);</p>
<p>        if ($session_count == 1) {<br />
            $result = $this-&gt;execSingle();<br />
        } elseif ($session_count &gt; 1) {<br />
            if ($key === false) {<br />
                $result = $this-&gt;execMultiple();<br />
            } else {<br />
                $result = $this-&gt;execSingle($key);<br />
            }<br />
        }</p>
<p>        if ($result) {<br />
            return $result;<br />
        }<br />
    }</p>
<p>    /**<br />
     * Executes a single cURL session.<br />
     *<br />
     * @param	$key	integer		id of session to execute<br />
     * @return			array		content if CURLOPT_RETURNTRANSFER is set<br />
     */<br />
    public function execSingle(int $key = 0): array<br />
    {<br />
        if ($this-&gt;retries &gt; 0) {<br />
            $retries = $this-&gt;retries;<br />
            $http_code = 0;</p>
<p>            while ($retries &gt;= 0 AND ($http_code[0] == 0 OR $http_code[0] &gt;= 400)) {<br />
                $result = curl_exec($this-&gt;sessions[$key]);</p>
<p>                $http_code = $this-&gt;info($key, CURLINFO_HTTP_CODE);</p>
<p>                $retries--;<br />
            }<br />
        } else {<br />
            $result = curl_exec($this-&gt;sessions[$key]);<br />
        }<br />
        return $result;<br />
    }</p>
<p>    /**<br />
     * Executes multiple sessions.<br />
     *<br />
     * @return	array	content if CURLOPT_RETURNTRANSFER is set<br />
     */<br />
    public function execMultiple(): array<br />
    {<br />
        $mh = curl_multi_init();</p>
<p>        foreach ($this-&gt;sessions AS $i =&gt; $url) {<br />
            curl_multi_add_handle($mh, $this-&gt;sessions[$i]);<br />
        }</p>
<p>        do {<br />
            $mrc = curl_multi_exec($mh, $active);<br />
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);</p>
<p>        while ($active AND $mrc == CURLM_OK) {<br />
            if (curl_multi_select($mh) != -1) {<br />
                do {<br />
                    $mrc = curl_multi_exec($mh, $active);<br />
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);<br />
            }<br />
        }</p>
<p>        if ($mrc != CURLM_OK) {<br />
            echo &quot;Curl multi read error $mrc\n&quot;;<br />
        }</p>
<p>        foreach ($this-&gt;sessions AS $i =&gt; $url) {<br />
            $http_code = $this-&gt;info($i, CURLINFO_HTTP_CODE);</p>
<p>            if ($http_code[0] &gt; 0 AND $http_code[0] &lt; 400) {<br />
                $result[] = curl_multi_getcontent($this-&gt;sessions[$i]);<br />
            } else {<br />
                if ($this-&gt;retries &gt; 0) {<br />
                    $retries = $this-&gt;retries;<br />
                    $this-&gt;retries -= 1;</p>
<p>                    $exec = $this-&gt;execSingle($i);</p>
<p>                    if ($exec) {<br />
                        $result[] = $exec;<br />
                    } else {<br />
                        $result[] = false;<br />
                    }</p>
<p>                    $this-&gt;retries = $retries;<br />
                }<br />
                else<br />
                {<br />
                    $result[] = false;<br />
                }<br />
            }<br />
            curl_multi_remove_handle($mh, $this-&gt;sessions[$i]);<br />
        }<br />
        curl_multi_close($mh);</p>
<p>        return $result;<br />
    }</p>
<p>    /**<br />
     * Closes cURL sessions.<br />
     *<br />
     * @param	$key	integer		Optional, session close<br />
     */<br />
    public function close($key = false)<br />
    {<br />
        if ($key === false) {<br />
            foreach ($this-&gt;sessions AS $session) {<br />
                curl_close($session);<br />
            }<br />
        } else {<br />
            curl_close($this-&gt;sessions[$key]);<br />
        }<br />
    }</p>
<p>    /**<br />
     * Remove all cURL sessions.<br />
     */<br />
    public function clear()<br />
    {<br />
        foreach ($this-&gt;sessions AS $session) {<br />
            curl_close($session);<br />
        }<br />
        $this-&gt;sessions = [];<br />
    }</p>
<p>    /**<br />
     * Returns an array of session information.<br />
     *<br />
     * @param	$key		integer		Optional session key to return info on<br />
     * @param	$option		constant	Optional option to return<br />
     * @return				array<br />
     */<br />
    public function info($key = false, $option = false): array<br />
    {<br />
        if ($key === false) {<br />
            foreach ($this-&gt;sessions AS $key =&gt; $session) {<br />
                if ($option) {<br />
                    $info[] = curl_getinfo($this-&gt;sessions[$key], $option);<br />
                } else {<br />
                    $info[] = curl_getinfo($this-&gt;sessions[$key]);<br />
                }<br />
            }<br />
        } else {<br />
            if ($option) {<br />
                $info[] = curl_getinfo($this-&gt;sessions[$key], $option);<br />
            } else {<br />
                $info[] = curl_getinfo($this-&gt;sessions[$key]);<br />
            }<br />
        }<br />
        return $info;<br />
    }</p>
<p>    /**<br />
     * Returns an array of errors.<br />
     *<br />
     * @param	$key	integer		Optional session key to retun error on<br />
     * @return			array		error messages<br />
     */<br />
    public function error($key = false): array<br />
    {<br />
        if ($key === false) {<br />
            foreach ($this-&gt;sessions AS $session) {<br />
                $errors[] = curl_error($session);<br />
            }<br />
        }<br />
        else<br />
        {<br />
            $errors[] = curl_error($this-&gt;sessions[$key]);<br />
        }<br />
        return $errors;<br />
    }</p>
<p>    /**<br />
     * Returns an array of session error numbers.<br />
     *<br />
     * @param	$key	integer		Optional session key to retun error on<br />
     * @return			array		error codes<br />
     */<br />
    public function errorNumber($key = false)<br />
    {<br />
        if ($key === false) {<br />
            foreach ($this-&gt;sessions AS $session) {<br />
                $errors[] = curl_errno($session);<br />
            }<br />
        } else {<br />
            $errors[] = curl_errno($this-&gt;sessions[$key]);<br />
        }<br />
        return $errors;<br />
    }<br />
}</p>
<p>class Pastebin<br />
{<br />
    /**<br />
     * Used for spam protection methods. You will need to get an API Key at:<br />
     * http://pastebin.ca/apikey.php<br />
     */<br />
    const API_KEY = '';<br />
    const API_URL = 'http://pastebin.ca/quiet-paste.php?api=%s';<br />
    const API_ROOT = 'http://pastebin.ca';<br />
    const API_POST = '&amp;content=%s&amp;description=%s&amp;type=%d&amp;expiry=%s&amp;name=%s';</p>
<p>    /**<br />
     * Class instance.<br />
     *<br />
     * @var	object<br />
     */<br />
    private static $instance;</p>
<p>    /**<br />
     * Types of text, and their option number<br />
     *<br />
     * @var	array<br />
     */<br />
    private $languages = [<br />
        22 =&gt; 'ASP',<br />
        18 =&gt; 'Action Script',<br />
        19 =&gt; 'Ada Source',<br />
        20 =&gt; 'Apache Configuration',<br />
        21 =&gt; 'Assembly (NASM)',<br />
        2  =&gt; 'Asterisk Configuration',<br />
        23 =&gt; 'BASH Script',<br />
        3  =&gt; 'C Source',<br />
        9  =&gt; 'C# Source',<br />
        4  =&gt; 'C++ Source',<br />
        24 =&gt; 'CSS',<br />
        25 =&gt; 'Delphi Source',<br />
        26 =&gt; 'HTML 4.0 Strict',<br />
        7  =&gt; 'Java Source',<br />
        27 =&gt; 'JavaScript',<br />
        28 =&gt; 'LISP Source',<br />
        29 =&gt; 'Lua Source',<br />
        30 =&gt; 'Microprocessor ASM',<br />
        31 =&gt; 'Objective C',<br />
        5  =&gt; 'PHP Source',<br />
        14 =&gt; 'PL',<br />
        12 =&gt; 'Pascal Source',<br />
        6  =&gt; 'Perl Source',<br />
        11 =&gt; 'Python Source',<br />
        1  =&gt; 'Raw',<br />
        10 =&gt; 'Ruby Source',<br />
        33 =&gt; 'Script Log',<br />
        16 =&gt; 'SQL Statement',<br />
        17 =&gt; 'Scheme Source',<br />
        32 =&gt; 'Visual Basic .NET',<br />
        8  =&gt; 'Visual Basic Source',<br />
        15 =&gt; 'XML Document',<br />
        13 =&gt; 'mIRC Script'<br />
    ];</p>
<p>    /**<br />
     * Expiry options<br />
     *<br />
     * @var	array<br />
     */<br />
    private $expiration = [<br />
        'Never',<br />
        '5 minutes',<br />
        '10 minutes',<br />
        '15 minutes',<br />
        '30 minutes',<br />
        '45 minutes',<br />
        '1 hour',<br />
        '2 hours',<br />
        '4 hours',<br />
        '8 hours',<br />
        '12 hours',<br />
        '1 day',<br />
        '2 days',<br />
        '3 days',<br />
        '1 week',<br />
        '2 weeks',<br />
        '3 weeks',<br />
        '1 month',<br />
        '2 months',<br />
        '3 months',<br />
        '4 months',<br />
        '5 months',<br />
        '6 months',<br />
        '1 year'<br />
    ];</p>
<p>    /**<br />
     * Constructor.<br />
     */<br />
    private function __construct()<br />
    {<br />
        if (self::API_KEY == '') {<br />
            throw new Exception('You have not specified a Pastebin.ca API Key for Pastebin::API_KEY');<br />
        }<br />
    }</p>
<p>    /**<br />
     * Creates an instance of the class.<br />
     *<br />
     * @return	Pastebin<br />
     */<br />
    public static function getInstance(): Pastebin<br />
    {<br />
        if (!self::$instance) {<br />
            self::$instance = new self();<br />
        }<br />
        return self::$instance;<br />
    }</p>
<p>    /**<br />
     * Submit paste request to pastebin.ca<br />
     *<br />
     * @param	string		$content		Paste content<br />
     * @param	string		$description	Paste description (optional)<br />
     * @param	integer		$type			Paste format/language, 1=Raw, 5=PHP, etc {@see self::$languages}<br />
     * @param	string		$expiry			Paste expiration time {@see self::$expiration}<br />
     * @param	string		$name			Paste name/from<br />
     * @return	mixed						Pastebin URL on success, false or error string on failure.<br />
     */<br />
    public function post(string $content, string $description = '', int $type = 1, string $expiry = '', string $name = 'clueless')<br />
    {<br />
        if (empty($content)) {<br />
            throw new Exception('$content cannot be empty');<br />
        }</p>
<p>        if (!isset($this-&gt;languages[$type])) {<br />
            $type = 1; // Raw<br />
        }</p>
<p>        if ($expiry == 'Never' OR !in_array($expiry, $this-&gt;expiration)) {<br />
            $expiry = ''; // Never is empty.<br />
        }</p>
<p>        if (empty($name)) {<br />
            $name = 'clueless';<br />
        }</p>
<p>        $curl = cURL::getInstance();<br />
        $curl-&gt;addSession(sprintf(self::API_URL, self::API_KEY), [<br />
            CURLOPT_HEADER         =&gt; false,<br />
            CURLOPT_POST           =&gt; true,<br />
            CURLOPT_POSTFIELDS     =&gt; sprintf(self::API_POST, $content, $description, $type, $expiry, $name),<br />
            CURLOPT_REFERER        =&gt; self::API_ROOT,<br />
            CURLOPT_RETURNTRANSFER =&gt; true<br />
        ]);</p>
<p>        $result = $curl-&gt;exec();</p>
<p>        $curl-&gt;clear();</p>
<p>        if ($result) {<br />
            $result = explode(':', $result);<br />
            return self::API_ROOT . &quot;/$result[1]&quot;;<br />
        } else {<br />
            if ($curl-&gt;error()) {<br />
                return implode(&quot;&lt;br /&gt;\n&quot;, $curl-&gt;error());<br />
            }<br />
        }<br />
        return false;<br />
    }<br />
}</p>
<p>?&gt;<br />

And an example:

<br />
&lt;?php</p>
<p>$pb = Pastebin::getInstance();<br />
$paste = $pb-&gt;post('&lt;?php</p>
<p>echo &quot;This is a test again&quot;;</p>
<p>?&gt;', 'test', 5, '', 'anonymous');</p>
<p>if ($paste !== false) {<br />
	echo $paste;<br />
}</p>
<p>?&gt;<br />

Enjoy. 🙂

Eric Sizemore

I’m a 30 year old Web Developer, Programmer, and Domainer. I specialize in PHP and MySQL, and have used both extensively since early 2005.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.