CURL Wrapper-Klasse in PHP – WebBrowser.class.php

Dieser Beitrag ist Teil meiner Sourecode a Day-Aktion.

Eine simple nützliche Wrapper-Klasse, die den einfachen Umgang mit CURL ermöglicht. Cookies und Referer werden automatisch gespeichert.

<?php
/**
 * Simple CURL Wrapper
 *
 * @author Alexander Thiemann 
 */
class WebBrowser {
	/**
	 * saves curl session
	 *
	 * @var cURL
	 */
	private $ch = null;
	
	/**
	 * saves referer
	 *
	 * @var string
	 */
	private $ref = "";
	
	/**
	 * saves results
	 */
	public $result = "";
	
	/**
	 * init curl
	 *
	 */
	public function __construct() {
		$this->ch = curl_init();
	}
	
	/**
	 * destruct
	 *
	 */
	public function __destruct() {
		curl_close($this->ch);
	}
	
	/**
	 * post
	 *
	 * @param string $url
	 * @param string $data
	 */
	public function post($url, $data) {
		$this->result = "";
		curl_setopt($this->ch, CURLOPT_URL, $url);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
		$this->refer($url);
		$this->setopts();
		ob_start();  
		$this->result = curl_exec($this->ch);
		ob_end_clean();
	}
	
	/**
	 * get
	 *
	 * @param string $url
	 */
	public function get($url) {
		$this->result = "";
		curl_setopt($this->ch, CURLOPT_URL, $url);
		$this->refer($url);
		$this->setopts();
		ob_start();  
		$this->result = curl_exec($this->ch);
		ob_end_clean();
	}
	
	/**
	 * update referer
	 *
	 * @param string $url
	 */
	private function refer($url) {
		curl_setopt ($this->ch, CURLOPT_REFERER, $this->ref);
		$this->ref = $url;
	}
	
	/**
	 * set global opts
	 *
	 */
	private function setopts() {
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
		// you may want to change this
		curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9 (.NET CLR 3.5.30729)");
		curl_setopt($this->ch, CURLOPT_COOKIEJAR, "cookie");
		curl_setopt($this->ch, CURLOPT_COOKIEFILE, "cookie");
	}
}
?>

Die Verwendung:

$browser = new WebBrowser();
// einfaches get request; Resultat in Datei speichern
$browser->get("http://google.de");
$fp = fopen("tmp.txt", "w+");
fwrite($fp, $browser->result);
fclose($fp);

// post request
$browser->post("http://localhost/post.php", "test_data=" . urlencode("asdfg"));
// response is in $browser->result
 

at

 

5 Gedanken zu „CURL Wrapper-Klasse in PHP – WebBrowser.class.php

    1. Wenn du zB einen Login durchführen willst, verlangen manche Seiten, dass der Referer richtig gesetzt ist. Damit kannst du dir dann also zB das unnötige Request der Startseite sparen.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert