You are not logged in.

Dear visitor, welcome to Coder Forum. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

This articles has been requested to be deleted.

Sunday, October 23rd 2011, 10:13am

Tags

formular, fsockopen, Upload

Abstract

In diesem Tutorial erfahrt ihr, wie ihr File Uploads mit PHP an ein Formular schickt.

Article

Wenn ihr von eurem Webserver eine Datei an ein Upload Script schicken wollt, bietet euch PHP keine Standardfunktionen.\\
Eine Funktion dazu reiche ich euch hiermit nach.

Das passende Formular auf Empfängerseite würde grob gesehen folgendermaßen aussehen:

HTML Code

1
2
3
4
5
6
<form>
	<input type="text" name="var1" />
	<input type="text" name="var2" />
	<input type="file" name="inputname" />
	<input type="submit" />
</form>


Hier nun das Script auf Senderseite:

PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
function postToHost($host, $port, $path, $postdata = array(), $filedata = array()) {
	$data = "";
	$boundary = "---------------------".substr(md5(rand(0,32000)),0,10);
	$fp = fsockopen($host, $port);
 
	fputs($fp, "POST $path HTTP/1.0\n");
	fputs($fp, "Host: $host\n");
	fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n");
 
	// Ab dieser Stelle sammeln wir erstmal alle Daten in einem String
	// Sammeln der POST Daten
	foreach($postdata as $key => $val){
	    $data .= "--$boundary\n";
	    $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
	}
 
	// Sammeln der FILE Daten
	if($filedata) {
		$data .= "--$boundary\n";
		$data .= "Content-Disposition: form-data; name=\"".$filedata['name']."\"; filename=\"".$filedata['name']."\"\n";
		$data .= "Content-Type: ".$filedata['type']."\n";
		$data .= "Content-Transfer-Encoding: binary\n\n";
		$data .= $filedata['data']."\n";
		$data .= "--$boundary--\n";
	}
 
	// Senden aller Informationen
	fputs($fp, "Content-length: ".strlen($data)."\n\n");
	fputs($fp, $data);
 
	// Auslesen der Antwort
	while(!feof($fp)) {
		$res .= fread($fp, 1);
	}
	fclose($fp);
 
	return $res;
}
 
$postdata = array('var1'=>'test', 'var2'=>'test');
$filedata = array(
	'name' => 'inputname',
	'filename' => 'image2.jpg',
	'type' => 'image/jpeg',
	'data' => file_get_contents('/home/easycoding/image2.jpg')
);
 
echo '<pre>'.postToHost ("localhost", 80, "/test3.php", $postdata, $filedata).'</pre>';

Lexikon 4.1.3, developed by www.viecode.com