Home > Blog

Curl en gebruik

Geschreven op 16 April 2009 door Han. Categorie: PHP. Reacties: 0

Zoals jullie in deze post kunnen lezen, ben ik aardig met een cURL class bezig geweest. Waarvoor dan eigenlijk? Nou. Voor een uitgebreide proxy over ssl! Maar niet zomaar een proxy maar eentje die automatisch voor je inlogt en de sessie onthoudt. Een soort van single-sign-on. Alleen de html's worden over de ssl gehaald, de rest gaat gewoon via de host zelf. (Want die is gewoon beschikbaar voor jou).

Alleen het probleem is dat ik niet weet of het wel mag. Het idee is leuk! En het werkt zelfs fantastisch, maar ik zit in het randgebied. Wat zou jij doen?

Lees verder ...

tags: curl php useage

Curl cookie class - v2

Geschreven op 05 April 2009 door Han. Categorie: PHP. Reacties: 991

Deze week ging ik me bezig houden met cURL. Het probleem ontstond dat de cookies niet werden onthouden. Officieel zou het moeten werken met CURLOPT_COOKIEJAR en CURLOPT_COOKIEFILE. de jar slaat de cookies op in een bestand en cookiefile leest dat bestand weer uit en zo draag je de cookies over, maar dat werkt in veel gevallen niet. Dus vandaar dat ik mijn eigen class heb gemaakt die cookies automatisch opslaat.

Voor op en aanmerkingen kan je onderaan de pagina reageren.

Nieuw in versie 2.0

  1. Bestanden upload afhandel script! (is temp map voor nodig zie const)
  2. Onthoudt nu ook referer
  3. Verbeterde splitcontent! Ook met http codes afhandeling. (zie de class onderaan)
  4. Minor Bug Fixes

php:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165166
167
168
169
170171
172
173
174
175176
177
178
179
180181
182
183
184
185186
187
188
189
190191
192
193
194
195196
197
198
199
200201
202
203
204
205206
207
208
209
210211
212
213
214
215216
217
218
219
220221
222
223
224
225226
227
228
229
230231
232
233
234
235236
237
238
239
240241
242
243
244
245246
247
248
249
250251
252
253
254
255256
257
258
259
260261
262
263
264
265266
267
268
269
270271
272
273
274
275276
277
278
279
280281
282
283
284
285286
287
288
289
290291
292
293
294
295296
297
298
299
300301
302
303
304
305306
307
308
309
310311
312
313
314
315316
317
318
319
320321
322
323
324
325326
327
328
329
330331
332
333
334
335336
337
338
339
340341
342
343
344
345346
347
348
349
350351
352
353
354
355356
357
358
359
360361
362
363
364
365366
367
368
369
370371
372
373
374
375376
377
378
379
380381
382
383
384
385386
<?PHP
/**
 * Basis curl class met cookie ondersteuning
 * 
 * @author Han */
 
class CurlIt {
	
		/**
	 * Contstante waar een temp bestand naar geschreven moet worden
	 * @var str
	 */
	const TEMP_UPLOAD_DIR = 'tempfiles';	/**
	 * User Agent String, eventueel aangepast
	 * @var str
	 */
	private $user_agent;	
	/**
	 * Disable ssl check, valideer certificaat of niet
	 * @var boolean
	 */	private $disable_ssl;
	
	
	/**
	 * Private storage of cookie	 * @var array|str
	 */
	private $cookie;
	
		/**
	 * Huidige CurlChannel, er kan in PHP maar 1 ding tegelijk dus dan kan dit. In Java kan dit niet
	 * @var resource
	 */
	protected $ch;	
	
	/**
	 * Referer
	 * @var str	 */
	protected $referer;
	
	/**
	 * Initialiseer de Class	 * @param $user_agent   mix 	    NULL geeft huidige user_agent anders je eigen
	 * @param $disable_ssl  boolean 	Disable ssl check
	 * @return void
	 */
	public function __construct($user_agent = null,$disable_ssl = true) {	
	// Browser
	if($user_agent != null) {
		$this->user_agent = $user_agent;
	} else {		$this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'WebmailProxy 1.0 (Mozilla Compatible)';
	}
	
	$this->disable_ssl = $disable_ssl;
		// Check voor upload dir
	if(!is_writable(self::TEMP_UPLOAD_DIR)) {
		throw new Exception('Map voor uploaden van bestanden bestaat niet of is niet schrijfbaar');
	}
	}	
	/**
	 * Init A connection
	 * @param $url  URL of page
	 * @return resource	 */
	private function init($url) {
	
	$this->ch = curl_init();
		// Set referer tot de laatste
	if(!empty($this->referer)) {
		curl_setopt($this->ch,CURLOPT_REFERER,$this->referer);
	}
	// Nieuwe ref	$this->referer = $url;
	
	// set URL
	curl_setopt($this->ch,CURLOPT_URL,$url);
	// Disable ssl	if($this->disable_ssl) {
		curl_setopt ($this->ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt ($this->ch, CURLOPT_SSL_VERIFYPEER, false);
	} 
		// Set options
	curl_setopt($this->ch,CURLOPT_USERAGENT,$this->user_agent);
	curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($this->ch,CURLOPT_HEADER,true);
	curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,true);	curl_setopt($this->ch,CURLOPT_AUTOREFERER,true);
		
	return $this->ch;
	}
		/**
	 * 
	 * @param $url  URL to get
	 * @param $cookie       Set stored cookie for this session
	 * @return str  Content of website	 */
	public function get($url,$cookie = false) {
	
	$this->init($url);
		// Als cookie wel moet, store hem dan
	if($cookie) {
		curl_setopt($this->ch,CURLOPT_COOKIE,$this->getStoredCookie());
	}
		// Uitvoeren
	$parse = $this->exec($this->ch);
	
	
		// Cookie store?
	if($cookie === false) {
		$this->parseCookies($parse['header']);
	}
	$this->parseHeader($parse['header']);	
	curl_close($this->ch);
	
	
	return $parse['content'];	}
	
	
	/**
	 * Post A form, with or withoud cookie	 * @param $url
	 * @param $postdata
	 * @param $cookie
	 * @return str
	 */	public function post($url,$postdata,$cookie = false) {
	
	// Preparepost
	foreach($postdata as $key => $v) {
		$nkey = str_replace('_','.',$key);		$postdata[$nkey] = $v;
		
		// Niet een bestaande checken
		if($nkey != $key) {
		unset($postdata[$key]);		}
	}
	
	// Initaliseer
	$this->init($url);	
	// _FILES gebeuren
	$uploaded_files = array();
	if(isset($_FILES)) {
		// Groote en bestanden		foreach($_FILES as $key => $val) {
		$nkey = str_replace('_','.',$key);
		$f = '@'.$this->handleUpload($val);
		$uploaded_files[] = ltrim($f,'@');
		$postdata[$nkey] = $f;		}
	}
	
	
		// Als cookie wel moet, store hem dan
	if($cookie) {
		curl_setopt($this->ch,CURLOPT_COOKIE,$this->getStoredCookie());
	}
		curl_setopt($this->ch,CURLOPT_POST,1);
	curl_setopt($this->ch,CURLOPT_POSTFIELDS,$postdata);
	
	$parse = $this->exec($this->ch);
		
	// Cookie store?
	if($cookie === false) {
		$this->parseCookies($parse['header']);
	}	$this->parseHeader($parse['header']);
	
	curl_close($this->ch);
	
	// Verwijder de bestanden weer	foreach($uploaded_files as $v) {
		unlink($v);
	}
	
		
	return $parse['content'];
	}
	
	/**	 * Uitvoeren van operatie
	 * @return unknown_type
	 */
	public function exec() {
		$out = curl_exec($this->ch);
	
	$error = curl_error($this->ch);
	if(!empty($error)) {
		throw new Exception('cURL ERROR: '.$error.' ('.curl_errno($this->ch).')');	}
	
	$parse = $this->splitContent($out);
	
	// Foute code? Gooi fout!	if(httpCodes::exists($parse['code'])) {
		throw new Exception($parse['code'].' '.httpCodes::getCode($parse['code']),$parse['code']);
	}
	
	return $parse;	}
	
	/**
	 * handleTheUpload
	 * @param $file	 * @return str
	 */
	private function handleUpload($file) {
	if(is_uploaded_file($file['tmp_name'])) {
		$dest = getDir($_SERVER['SCRIPT_FILENAME']).'/'.self::TEMP_UPLOAD_DIR.'/'.$file['name'];		if(move_uploaded_file($file['tmp_name'],$dest)) {
		return $dest;
		} else {
		throw new Exception('Dest niet schrijven, dest: '.$dest);
		}	} 
	}
	
	/**
	 * Get cookie array	 * @return array
	 */
	public function getCookies() {
	return $this->cookie;
	}	
	/**
	 * Voeg cookie toe aan array
	 * @param $key  str
	 * @param $data str	 * @return void
	 */
	public function addCookie($key,$data) {
	$explode = explode(';',$data);
	$this->cookie[$key] = trim($explode[0]);		}
	
	/**
	 * Verwijder cookie
	 * @param $key	 * @return void
	 */
	public function removeCookie($key) {
	unset($this->cookie[$key]);     
	}	
	/**
	 * Reset en Set de class met array data
	 * @param $data array
	 * @return void	 */
	public function setCookies(array $data) {
	$this->cookie = $data;
	}
		/**
	 * Set referer
	 * @param $ref
	 * @return str
	 */	public function setReferer($ref) {
	if($ref != null) {
		$this->referer = $ref;
	}
	}	
	/**
	 * Parse the header string en zet het in de cookie array voor later
	 * @param $header
	 * @return void	 */
	private function parseCookies($header) {
	$patt = '#Set-Cookie: ([a-z0-9]+)=(.*)#i';
	preg_match_all($patt,$header,$return);
		foreach($return[1] as $key => $id) {
		$this->addCookie($id,$return[2][$key]);
	}
	}
		/**
	 * Parse the whole header
	 * @param $header
	 * @return str
	 */	public function parseHeader($h) {
	$ex = explode("\n",$h);
	
	foreach($ex as $v) {    
		if(strstr($v,'Content-') !== false) {		
		if(strstr($v,'Content-Type')) continue; 
		header($v);
		}
	}	}
	
	/**
	 * Get stored cookie in CURL format
	 * @return str	 */
	private function getStoredCookie() {
	
	$ret = '';
	foreach($this->cookie as $key => $val) {		$ret .= $key.'='.$val.';';
	}
	
	return rtrim($ret,';');
	}	
	/**
	 * Split content in header en content deel
	 * @param $content
	 * @return array (header,content)	 */
	private function splitContent($data) {
	
	$patt = "#HTTP/1.1 ([0-9]+) (.*)\n#i";
	$match = preg_split($patt,$data);	
	// Match error code
	preg_match_all($patt,$data,$codes);
	
	// Laatste	$data = end($match);
	$ex = explode("\n",$data);
	
	$header 	= '';
	$content        = '';	$headersplit    = true;
	
	foreach($ex as $v) {
		
		// Lege regel, dus dan is de rest content		$x = trim($v);
		if(empty($x)) {
		$headersplit = false;   
		}
				if($headersplit === true) {
		$header .= $v."\n";
		} else {
		$content .= $v."\n";
		}		
	}
	
	
	$ret = array();	$ret['header']  = $header;
	$ret['content'] 	= $content;
	$ret['code']    = end($codes[1]);
	
	return $ret;	}
	
}
 
 ?>

HTTP code class

php:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
50
<?php
/**
 * http status codes
 * 
 * @author Han *
 */
class httpCodes {
	
	/**	 * Array of http status codes
	 * @var Array of codes
	 */
	public static $codes = array(   
	404 => 'File not Found',	403 => 'Forbidden',
	500 => 'Server Error',
	504 => 'Gateway Timeout',
	503 => 'Service niet beschikbaar',
	502 => 'Bad gateway',	415 => 'Unsupported media type',
	414 => 'Request uri too long',
	410 => 'Gone, weggelopen',
	401 => 'Unauthorized',
	400 => 'Bad Request'	);
 
	
	/**
	 * Bestaat code?	 * @param $code
	 * @return bool
	 */
	public static function exists($code) {
	return isset(self::$codes[$code]);	}
	
	/**
	 * Get omschrijving
	 * @param $code	 * @return str
	 */
	public static function getCode($code) {
	if(self::exists($code)) {
		return self::$codes[$code];	}
	throw new Exception('Error code not supported');
	}
}
?>

Versie 2.0

TODO: Opslaan in bestand en uitlezen

Lees verder ...

tags: curl cookie class

PHP5.3 Op windows

Geschreven op 14 March 2009 door Han. Categorie: PHP. Reacties: 0

PHP5.3 komt er bijna aan! En natuurlijk moet je er wel wat van afweten. De nieuwe syntax weten is één, maar je moet het natuurlijk ook kunnen testen ;-). Dus hoe installeer je PHP5.3 op windows (want dat kon ik nergens vinden on the internet).

Als eerste moet je php5.3 beta downloaden. Uitpakken in de gewenste php map (in dit voorbeeld c:/server/php/5.3.0/)

Om PHP5.3 te kunnen draaien in Apache moet je het via CGI draaien. Op deze manier kan je dus meerdere php versies naast elkaar draaien.

Mijn config van Apache zag er dus zo uit:

apache:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
#Dit is voor php5.2.9
LoadModule php5_module C:/server/php5/5.2.9/php5apache2_2.dll
AddType application/x-httpd-php .php4 .php .php3 .inc .php5
AddType application/x-httpd-php-source .phps
 # dit is voor php5.3.0
 
  AllowOverride None
  Options None
  Order allow,deny  Allow from all
 
# .php53 is nu de extentie voor php5.3.0 scripts
ScriptAlias /php53/ "C:/server/php5/5.3.0/"
Action application/x-httpd-php5_3_0 "/php53/php-cgi.exe "AddType application/x-httpd-php5_3_0 .php53 .53

Als je dus een bestand test.php53 noemt zal het uitgevoerd worden als php5.3.0 en als je test.php noemt zal het uitgevoerd worden door php5.2.9. Zo kan je dus de nieuwe php versie proberen met backwards compatible.

Succes met proberen van php5.3.0!

 

Lees verder ...

tags: php5.3 windows


1

css xhtml