Webdesign in Siegen

HTTP Klasse

Fragen zum Thema PHP können hier gestellt werden

Moderator: Basti

HTTP Klasse

Beitragvon Avedo am 21.04.2008, 21:16

Hallo!
Da ich für meine Repository Klasse eine Verbindung zu einem anderen Server mittels HTTP brauche, schreibe ich gerade eine HTTP-Klasse. Ich habe dazu einige Methoden meiner FTP-Klasse übernommen. Eigentlich alles schön und gut, aber es funktioniert nicht und ich weiß nicht wieso. Momentan mache ich nur Testausgaben um zu schauen, ob die Grundstrukturen funktionieren, auf denen die gesamte Klasse aufbauen soll, aber das funktioniert nicht. Ich versuche momentan folgenden Verbindungsablauf mit der Klasse auszuführen. (Mit dem nachfolgenden Code klappt es auch)
Code: Alles auswählen
<?php
   // run server connection
    $fp = fsockopen('www.avedo.net',  80, $errno, $error, 5)
          OR                     // if connection failed
      die($error."(". $errno.")");
         
    //send request
    fwrite($fp, "HEAD / HTTP/1.0\r\n");
    // end request
    fwrite($fp, "\r\n");
   
    // change Content-Type
    header('Content-Type: text/plain'); 
   
    while(!feof($fp))
    {
        $reply = fread($fp, 1025);
        $reply = str_replace("\r\n", '\r\n'."\n", $reply);
        echo $reply;
    }
   
    // close connection
    fclose($fp);
?>

Meine Klasse soll nun das gleiche machen. Jedoch klappt das nicht. Ich erhalte aber leider keine Fehlermeldung oder ähnliches. Ich sehe nur eine weiße Seite.
Code: Alles auswählen
<?php 
error_reporting(E_ALL);

/***
* HttpConnect class allows easy connecting to a foreign server.

* @package HttpConnect
* @version 0.1
* @author Andreas Wilhelm <Andreas2209@web.de>
* @copyright Andreas Wilhelm
**/ 
class HttpConnect
{
   // public class variables
   protected $entry;
   protected $host;
   
   protected $logStats;
   protected $log;

   /**
   * Constructor - Is called when the class is instanced
   *
   * @access: public
   * @param Str $host
   * @param Int $port
   * @param Bool $log   
   * @return NONE
   */
   public function __construct($host='localhost', $port=80, $log=false)
   {
      // set if the connection with the server should be logged
      $this->logStats = $log;
      
      // save host-name to $host
      $this->host = $host;
   
      // control-connection handle is save to $control
      $this->entry = @fsockopen($host, $port);
      if (!$this->entry)
         throw new Exception("Connection failed.\n");
      
      // switch to non-blocking mode - just return data no response
      set_socket_blocking($this->entry, true);
      
      // set timeout of the server connection
      stream_set_timeout($this->entry, 0, 200000);
   }
 
   /**
   * Destructor, is called if the entity is deleted (via unser() at the end of the script
   *
   * @access: public
   * @return NONE
   */     
   public function __destruct()
   {
      fclose($this->entry);
   }

   /**
   * sendCmd() - Sends a command to the server
   *
   * @access: public
   * @param Str $cmd
   * @return NONE
   */
   public function sendCmd($cmd)
   {
      // send the request
      fwrite($this->entry, $cmd);
      
      // log the request
      $this->log("&gt; $cmd");
   }
   
   /**
   * readSock() - Reads out the response from the server
   *
   * @access: public
   * @return String
   */
   public function readSock()
   {   
      $response = "";

      while(!feof($this->entry))
      {
         $response .= fread($this->entry, 1025);
      }
      
      $this->log($response);
      
      return $response;
   }
         
   /**
   * log() - Saves all request to the server and their responses into $this->log
   *
   * @access: private
   * @param Str $str
   * @return NONE
   */
   private function log($str)
   {
      if($this->logStats)
      {
         $this->log .= "$str<br>";
      }
   }
         
   /**
   * getLog() - Prints out all requests to the server and their responses
   *
   * @access: public
   * @return NONE
   */
   public function getLog()
   {
      return $this->log;
   }
}

try
{
   // change Content-Type
   header('Content-Type: text/plain');
   $http = new HttpConnect('www.avedo.net', 80, true);
   $http->sendCmd('HEAD / HTTP/1.0\r\n');
   $http->sendCmd('\r\n');
   echo $http->readSock();
   echo $http->getLog();
}

catch(Exception $e)
{
   echo $e->getMessage();
}
?>

Kann mir jemand sagen, wo mein Fehler liegt? Es wird wie gesagt nur eine weiße Seite angezeigt. Keine Fehler rein garnichts.
MfG, Andy

PS: Das erste Script gibt nachfolgenden Code aus, den das untere Script auch ausgeben sollte.

HTTP/1.1 302 Found\r\n
Date: Mon, 21 Apr 2008 18:04:27 GMT\r\n
Server: Apache\r\n
X-Powered-By: PHP/5.2.0-8+etch10\r\n
Location: ./user/index.php\r\n
Connection: close\r\n
Content-Type: text/html\r\n
\r\n
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon .wired am 21.04.2008, 23:44

Wie wendest du die Klasse denn an? Soweit ich das sehe kann sie ohnehin nur etwas ausgeben, wenn sie in die Fehlerbehandlung kommt. Wenn aber alles richtig abläuft und keine Exception geworfen wird, kann folglich auch nichts schief gehen... Moment, ich schau sie mir mal im normalen Editor an, hier ist mir zu wenig Platz :P

MfG .wired

<edit>'\r\n' in "\r\n" ändern, dann gehts....</edit>
Bild Bild
Benutzeravatar
.wired
Mitglied
 
Beiträge: 315
Registriert: 24.06.2007, 20:36
Wohnort: Diekholzen

Re: HTTP Klasse

Beitragvon Avedo am 22.04.2008, 00:50

Morgen!
Vielen Dank für deine Hilfe. Leider habe ich schon das nächste Problem. Kann es sein, dass ich für jeden HTTP-Request eine neue Verbindung zum Server aufbauen muss? Denn führe ich zwei Request hintereinander aus, wird immer nur eine Antwort auf den ersten gegeben. Kann mir da vielleicht einer helfen? Zudem hätte ich noch eine Allgemeine Frage zu den RFC Protokollen. Kann es sein, dass bei den gängigen RFCs (IMAP | SMTP | FTP | HTTP) das erst das Ende eines Befehls oder eines Responses, egal wie lang dieses ist, immer durch \r\n gekennzeichnet ist? Oder ist das richtige Ende immer durch \r\n\r\n gekennzeichnet? Ich würde auf das letztere Tippen, bin da aber noch nicht so ganz durchgestiegen. Wenn das so ist, müsste ich doch anstatt bis EOF immer bis \r\n\r\n den Stream auslesen können?
MfG, Andy
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Avedo am 28.04.2008, 17:59

Hallo!
Bräuchte mal eure Hilfe bei einem RegEx. Und zwar möchte ich den bei einem HTTP-Request zurückgegebenen Header in seine Einzelteile zerlegen und in einem Array $head speichern. Das ganze möchte ich mit preg-split() machen, da ich diese Funktion für sehr praktisch halte. Diese Funktion erwartet allerdings ein RegEx für patter. Schaut man sich so einen Header an, stellt man fest, dass man zuerst den Name des Header gefolgt von einem Doppelpunkt und den zugehörigen Informationen erhält und ein Infoblock mit \r\n beendet wird. Das sieht also so aus:

HTTP-Request-Header
HTTP/1.1 200 OK
Server: Apache/1.3.29 (Unix) PHP/4.3.4
Content-Length: (Größe von infotext.html in Byte)
Content-Language: de (nach ISO 639 und ISO 3166)
Content-Type: text/html
Connection: close

(Inhalt von infotext.html)


Diesen Header müsste ich ja dann eigentlich mit etwas Ähnlichem wie (*):(*)\r\n zerlegen können. Oder? Wie muss denn das RegEx nun genau aussehen? Und kann ich dann mit
Code: Alles auswählen
$head = preg_split($pattern, $head, -1, PREG_SPLIT_NO_EMPTY);

das irgendwie in der Form
Code: Alles auswählen
$head["server"] = Apache/1.3.29 (Unix) PHP/4.3.4

abspeichern?

Momentan trenne ich übrigens den Content vom Header mit
Code: Alles auswählen
list($head, $content) = split("\r\n\r\n", $reply);


Wäre sehr dankbar, wenn mir jemand helfen könnte.
MfG, Andy
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Ingo am 28.04.2008, 19:19

Hi.

RegEx testen kann man ganz praktisch mit Programmen wie Visual RegExp;
der Ausdruck müsste (.*):(.*)\r\n lauten, * ist nur ein Quantifizierer, der Punkt davor gibt
an, welches Zeichen beliebig oft kommen darf.

preg_split scheint mir nicht ganz das zu sein, was hier weiterhilft; das Muster beschreibt dann
nämlich nur, an welcher Stelle getrennt werden soll. Um aber key-value-Paare für einen Hash
zu erzeugen, finde ich das von dir oben genannte Muster (mit Punkten) zusammen mit der Funktion
preg_match_all einen Versuch wert; das Ergebnis ist ein Array $res mit den gewünschten Daten:

Code: Alles auswählen
$regexp = '/(.*):(.*)\r\n/';

preg_match_all($regexp, $txt, $res);

print_r($res);   


Gruß, Ingo :)
Die beste Browserweiche ... sitzt zwischen den Ohren ;o]
Benutzeravatar
Ingo
Moderator
 
Beiträge: 434
Registriert: 01.04.2007, 23:21
Wohnort: Neuss/NRW

Re: HTTP Klasse

Beitragvon Basti am 28.04.2008, 19:37

Hm... also dein Ansatz ist grundsätzlich schonmal richtig, allerdings würde dir preg_split() ersteinmal nur die einzelnen Zeilen zurückliefern, da sie den String einfach anhand des Regulären Ausdrucks in Teilstrings zerlegt, aber eben nicht in die einzelnen Werte wie du es vorgesehen hast.
Deshalb würde ich zur Verwendung von preg_match_all() tendieren, mit welcher der gewünschte Array erstellt werden kann.

Hier mal mein Ansatz:

Code: Alles auswählen
$head = array();

if(preg_match_all('#(.*): (.*)\r\n#U',$dein_header,$result))
{
  $result_number = count($result[0]);

  for($i=0; $i<$result_number; $i++)
  {
    $header_name = $result[1][$i];
    $header_info   = $result[2][$i];

   $head[$header_name] = $header_info;
  }
}


Mit diesem Code wird für jede Zeile mit einer Header-Information ein neues Element im Array erzeugt, das als Key den Namen besitzt ("Server", "Content-Lenght", ...) und als Inhalt die jeweilige Information ("Apache/1.3.29 (Unix) PHP/4.3.4", ...).
Der Array $result enthält sowohl das gesamte gefundene Suchmuster $result[0][$i] als auch die Teilgruppierungen $result[1][$i] und $result[2][$i] für den Namen und die Information. Im Grunde genommen könnte das "\r\n" im Regulären Ausdruck auch weggelassen werden, es sei denn du möchtest nur bis zur vorletzten Zeile auslesen.

Der Rest sollte ja eigentlich verständlich sein.

// edit: Da war Ingo wohl schneller ... aber ich habe ja auch etwas mehr geschrieben ;)
Benutzeravatar
Basti
Moderator
 
Beiträge: 1774
Registriert: 15.06.2006, 17:33
Wohnort: Rheinbreitbach

Re: HTTP Klasse

Beitragvon Avedo am 28.04.2008, 23:21

Abend!
Danke erstmal für eure Hilfe. Ich habe etwas an der Klasse gearbeitet und die Version 0.2 abgeschlossen. Als erstes möchte ich euch meine weitere Planung vorstellen und würde euch dann bitten Verbesserungsvorschläge und Anregungen einzubringen.

Laufplan
v0.3 Hinzufügen von GET
v0.4 Hinzufügen von POST
v0.5 Hinzufügen weiterer Verbindungsarten (proxy /ssl)
v0.6 bis v0.9 Fehlerbehebung
v1.0 Final

HttpConnect.php
Code: Alles auswählen
<?php 
error_reporting(E_ALL);

/***
* HttpConnect class allows easy connecting to a foreign server.

* @package HttpConnect
* @version 0.2
* @author Andreas Wilhelm <Andreas2209@web.de>
* @copyright Andreas Wilhelm
**/ 
class HttpConnect
{
   // protected class variables
   protected $host;
   protected $port;
   
   protected $logStats;
   protected $log;

   /**
   * Constructor - Is called when the class is instanced
   *
   * @access: public
   * @param Str $host
   * @param Int $port
   * @param Bool $log   
   * @return NONE
   */
   public function __construct($host='localhost', $port=80, $log = false)
   {
      // set server-variables
      $this->host = $host;
      $this->port = $port;
      
      // set if the connection with the server should be logged
      $this->logStats = $log;
   }

   /**
   * login() - Connects to the server
   *
   * @access: private
   * @param Str $host
   * @param Int $port
   * @return Handle
   */
   private function login()
   {      
      // control-connection handle is saved to $handle
      $handle = @fsockopen($this->host, $this->port);
      if (!$handle)
         throw new Exception("Connection failed.\n");
      
      // switch to non-blocking mode - just return data no response
      set_socket_blocking($handle, true);
      
      // set timeout of the server connection
      stream_set_timeout($handle, 0, 200000);
      
      return $handle;
   }
 
   /**
   * logout() - Closes the connection
   *
   * @access: private
   * @return NONE
   */     
   private function logout($handle)
   {
      fclose($handle);
   }

   /**
   * sendCmd() - Sends a command to the server
   *
   * @access: public
   * @param Str $cmd
   * @return NONE
   */
   public function sendCmd($handle, $cmd)
   {
      // send the request
      fputs($handle, $cmd);
      
      // log the request
      $this->log("-> $cmd");
   }
   
   /**
   * readSock() - Reads out the response from the server
   *
   * @access: private
   * @return String
   */
   private function readSock($handle)
   {   
      $response = "";

      while(!feof($handle))
      {
         $response .= fread($handle, 1025);
      }
      
      $this->log($response);
      
      return $response;
   }
         
   /**
   * divideReply() - Spilts up the reply into the different information
   *
   * @access: private
   * @param Str $reply
   * @return NONE
   */
   private function divideReply($reply)
   {
      // separate header and content
      list($head, $content) = split("\r\n\r\n", $reply);
      
      // unpack header information
      $header = array();

      if( preg_match_all('#(.*): (.*)\r\n#U', $head, $result) )
      {
         $num = count($result[0]);

         for($i=0; $i<$num; $i++)
         {
            $name = $result[1][$i];
            $info   = $result[2][$i];

            $header[$name] = $info;
         }
      }
      
      $data = array('head'=>$header, 'content'=>$content);
      
      return $data;
   }
         
   /**
   * head() - Returns the HTTP-header like a GET or POST reply but without the file
   *
   * @access: private
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @return NONE
   */
   public function head($uri='/', $params=false, $cookies=false)
   {
      // login to the server
      $handle = $this->login();
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      // send request to the server
      $this->sendCmd($handle, "HEAD $uri.$params HTTP/1.1\r\n");
      $this->sendCmd($handle, "Host: $host\r\n$cookies");
      $this->sendCmd($handle, "Connection: close\r\n\r\n");
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers and file
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * log() - Saves all request to the server and their responses into $log
   *
   * @access: private
   * @param Str $str
   * @return NONE
   */
   private function log($str)
   {
      if($this->logStats)
      {
         $this->log .= $str;
      }
   }
         
   /**
   * getLog() - Prints out all requests to the server and their responses
   *
   * @access: public
   * @return NONE
   */
   public function getLog()
   {
      return $this->log;
   }
}

try
{
   // change Content-Type
   header('Content-Type: text/plain');
   $http = new HttpConnect("www.avedo.net", 80, true);
   
   $data = $http->head();
   
   echo $http->getLog();
   
   print_r ($data);
}

catch(Exception $e)
{
   echo $e->getMessage();
}
?>

Wäre wie immer über jede Hilfe sehr froh.
MfG, Andy

//EDIT: Hier mal ein kleiner Testlink.
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Avedo am 30.04.2008, 00:41

Morgen!
Habe mal etwas an der Klasse weitergearbeitet und musste bei der Integration der get()-Methode feststellen, dass mir in der divideReply()-Methode ein Fehler unterlaufen sein muss. Und zwar habe ich die Klasse in ihrem momentanen Zustand mit folgendem Script getestet (Testaufruf befindet sich am Ende der Klasse):

test.php
Code: Alles auswählen
<?php
   if( $_GET['num'] == 45)
   {
      echo "Hello world!";
   }
   
   else
   {
      echo "Try again!";
   }   
?>

Zwar wird, wie erhofft, Hello world! oder Try again! zurückgegeben, aber vor und hinter der jeweiligen Zeile steht irgendetwas anderes im Array $data für den key content. Zudem wird der Content-Type zwar zurückgeliefert, aber nicht in das Array $data aufgenommen. Kann mir jemand sagen, wo mein Fehler liegt? Die Klasse in der neueren Version habe ich am Ende angehängt. Vielen vielen Dank schon mal für eure Bemühungen.
MfG, Andy

HttpConnect.php
Code: Alles auswählen
<?php 
error_reporting(E_ALL);

/***
* HttpConnect class allows easy connecting to a foreign server.

* @package HttpConnect
* @version 0.2
* @author Andreas Wilhelm <Andreas2209@web.de>
* @copyright Andreas Wilhelm
**/ 
class HttpConnect
{
   // protected class variables
   protected $host;
   protected $port;
   
   protected $ssl;
   
   // tip by Denis Wronka, who said, taht many servers need a referrer
   protected $referrer;
   
   protected $logStats;
   protected $log;

   /**
   * Constructor - Is called when the class is instanced
   *
   * @access: public
   * @param Str $host
   * @param Int $port
   * @param Bool $log   
   * @return NONE
   */
   public function __construct($host='localhost', $port=80, $log=false, $ssl=false, $referrer="PHP/Http-Referrer")
   {
      // set server-variables
      $this->host = $host;
      $this->port = $port;
      
      $this->ssl = $ssl;
      $this->referrer = $referrer;
      
      // set if the connection with the server should be logged
      $this->logStats = $log;
   }

   /**
   * login() - Connects to the server
   *
   * @access: private
   * @param Str $host
   * @param Int $port
   * @return Handle
   */
   private function login()
   {   
      if ($this->ssl == true)
      {   
         // use ssl-connection and save connection handle
         $handle = @fsockopen('ssl://'.$this->host, $this->port);
         
         // throw error in case of failure
         if (!$handle)
         {
            throw new Exception("SSL-connection failed.\n");
         }
      }

      else
      {
         // connection handle is saved to $handle
         $handle = @fsockopen($this->host, $this->port);
                  
         // throw error in case of failure
         if (!$handle)
         {
            throw new Exception("Connection failed.\n");
         }
      }
      
      
      // switch to non-blocking mode - just return data no response
      set_socket_blocking($handle, true);
      
      // set timeout of the server connection
      stream_set_timeout($handle, 0, 200000);
      
      return $handle;
   }

   /**
   * auth() - Creates a connection to a secured server
   *
   * @access: private
   * @param Str $user
   * @param Str $password
   * @return String
   */
   private function auth($user, $password)
   {      
      if (!empty($user))
      {
         $auth = 'Authorization: Basic '.base64_encode($user.':'.$password)."\r\n";
      }

      else
      {
         $auth = '';
      }
      
      return $auth;
   }
 
   /**
   * logout() - Closes the connection
   *
   * @access: private
   * @return NONE
   */     
   private function logout($handle)
   {
      fclose($handle);
   }

   /**
   * sendCmd() - Sends a command to the server
   *
   * @access: private
   * @param Str $cmd
   * @return NONE
   */
   private function sendCmd($handle, $cmd)
   {
      // send the request
      fputs($handle, $cmd);
      
      // log the request
      $this->log("-> $cmd");
   }
   
   /**
   * readSock() - Reads out the response from the server
   *
   * @access: private
   * @return String
   */
   private function readSock($handle)
   {   
      $response = "";

      while(!feof($handle))
      {
         $response .= fread($handle, 1025);
      }
      
      $this->log($response);
      
      return $response;
   }
         
   /**
   * divideReply() - Spilts up the reply into the different information
   *
   * @access: private
   * @param Str $reply
   * @return Array
   */
   private function divideReply($reply)
   {      
       if( !preg_match('/^HTTP\/(1\.[01]) ([1-5][0-9]{2})/', $reply, $match) )
       {
         return false;
       }
      
       $hb = strpos($reply, "\r\n")+2;
       $cb = strpos($reply, "\r\n\r\n")+4;
      
       $parsed = array(
         'HTTP_VERSION'  => $match[1],
         'STATUS_CODE'   => $match[2],
         'HEADER_FIELDS' => array(),
         'CONTENT'       => (string) substr($reply, $cb+2)
       );
      
       $headerFields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', substr($reply, $hb, $cb-$hb-4)));
       foreach( $headerFields as $headerField )
       {
         if( preg_match('/([^:]+):(.+)/m', $headerField, $match) )
         {
           $parsed['HEADER_FIELDS'][$this->getName($match[1])] = trim($match[2]);
         }
       }
      
       return $parsed;
   }
   
   /**
   * getName() - Returns the name of a received htpp-header-field
   *
   * @access: private
   * @param Str $string
   * @return String
   */
   private function getName( $string )
   {
       return preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($string)));
   } 
         
   /**
   * head() - Returns the HTTP-header like a GET or POST reply but without the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @param Str $user
   * @param Str $password
   * @return NONE
   */
   public function head($uri='/', $params=false, $cookies=false, $user="", $password="")
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      // send request to the server
      $this->sendCmd($handle, "HEAD $uri"."$params HTTP/1.1\r\n");
      $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
      $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
      $this->sendCmd($handle, "Connection: close\r\n\r\n");
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * get() - Returns the HTTP-header and the output of the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @param Str $user
   * @param Str $password
   * @return NONE
   */
   public function get($uri='/', $params=false, $cookies=false, $user="", $password="")
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      // send request to the server
      $this->sendCmd($handle, "GET $uri"."$params HTTP/1.1\r\n");
      $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
      $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
      $this->sendCmd($handle, "Connection: close\r\n\r\n");
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers and file
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * post() - Returns the HTTP-header and the output of the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @return NONE
   */
   public function post($uri='/', $params=false, $cookies=false, $fileparams=false, $mimes=false, $user='',$password='')
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      if (($fileparams==false) || (empty($fileparams)))
      {
         if (($params!=false) && (!empty($params)))
         {
            //prepare the attribut Content-Length
            $length = strlen($params);
            
            // send request and parameters to the server
            $this->sendCmd($handle, "POST ".$uri." HTTP/1.1\r\n");
            $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
            $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
            $this->sendCmd($handle, "Connection: close\r\n");
            
            $this->sendCmd($handle, "Content-Type: application/x-www-form-urlencoded\r\n");
            $this->sendCmd($handle, "Content-Length: ".$length."\r\n\r\n".$params");
         }

         else
         {
            // send request without parameters
            $this->sendCmd($handle, "POST ".$uri." HTTP/1.1\r\n");
            $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
            $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
            $this->sendCmd($handle, "Connection: close\r\n");
         }
      }
      
      else
      {
      }
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers and file
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * log() - Saves all request to the server and their responses into $log
   *
   * @access: private
   * @param Str $str
   * @return NONE
   */
   private function log($str)
   {
      if($this->logStats)
      {
         $this->log .= $str;
      }
   }
         
   /**
   * getLog() - Prints out all requests to the server and their responses
   *
   * @access: public
   * @return NONE
   */
   public function getLog()
   {
      return $this->log;
   }
}

try
{
   // change Content-Type
   header('Content-Type: text/plain');
   $http = new HttpConnect("www.avedo.net", 80, true);
   
   $data = $http->head();
   
   $data2 = $http->get("httptest/test.php", "num=45");
   
   echo $http->getLog();
   
   print_r ($data);
   
   print_r ($data2);
}

catch(Exception $e)
{
   echo $e->getMessage();
}
?>
Zuletzt geändert von Avedo am 08.05.2008, 15:37, insgesamt 1-mal geändert.
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Avedo am 04.05.2008, 15:17

Hallo!
Ich habe mal eine Bitte. Ich habe leider noch etwas Probleme beim "Lesen" von Regexen. Könnte mir vielleicht jemand die drei folgenden "übersetzen"?
Code: Alles auswählen
/\x0D\x0A[\x09\x20]+/

Code: Alles auswählen
/([^:]+):(.+)/m

Code: Alles auswählen
/(?<=^|[\x09\x20\x2D])./e

MfG, Andy
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Ingo am 04.05.2008, 16:23

Hi.
So'ne kurze Frage, und dann so'ne lange Antwort :lol: .Aus meinen Perl-Zeiten kenne ich da
noch einiges; in PHP funktionieren RegExp ganz ähnlich, also versuch ich's mal:

/\x0D\x0A[\x09\x20]+/

Die Hex-Codes bedeuten in der Reihenfolge "CR LF [TAB Space]+"; finde also einen Zeilenumbruch
(bestehend aus Wagenrücklauf und Zeilenvorschub), gefolgt von mindestens 1 TAB oder Leerzeichen.
Eckige Klammern umschließen eine Zeichenklasse, der Quantifizierer "+" bedeutet "mindestens
1 Zeichen". Ein ^ zu Beginn der Klasse verneint die Klasse (steht für jedes Zeichen, das nicht zu den
genannten Zeichen gehört):

/([^:]+):(.+)/m

Finde mindestens ein Zeichen, das kein Doppelpunkt ist, gefolgt von einem Doppelpunkt (: aber kein ::),
gefolgt von mindestens einem beliebigen Zeichen. Der Modifizierer "m" bedeutet: behandele den
zu untersuchenden Ausdruck als mehrzeilig (multiline). Siehe auch den Link zum Modifikator "e" unten.

Die runden Klammern merken sich (außer bei assertions, fangen mit ? an) einen gefundenen Teilausdruck.
Wenn das Muster also zutrifft, merken wir uns das/die nicht-:-Zeichen und das/die Zeichen, die auf den
Doppelpunkt folgen. Diese Teilausdrücke findet man später zum Beispiel in einem Antwort-Array wieder.

/(?<=^|[\x09\x20\x2D])./e

(?<=...) ist eine "positive lookbehind - assertion", für PHP vergleiche Abschnitt "assertion" bei php.net.
Hier also: finde ein beliebiges Zeichen (.), dem ein ^ oder eines der Zeichen 'TAB', 'Space' oder '-' vorangeht.
Der Assertion-Teil ist dabei kein Teil des "Treffers", als Trefferstelle gelten nur die Zeichen hinter der
assertion. - Zum Modifikator "e" siehe Modifikatoren bei php.net. - Ich hoffe, das ist nicht zu verwirrend :xx:

Gruß, Ingo :)
Die beste Browserweiche ... sitzt zwischen den Ohren ;o]
Benutzeravatar
Ingo
Moderator
 
Beiträge: 434
Registriert: 01.04.2007, 23:21
Wohnort: Neuss/NRW

Re: HTTP Klasse

Beitragvon Avedo am 08.05.2008, 15:36

Hallo!
Es geht voran. Die get()-Methode ist nun vollkommen integriert und ich habe mit der post()-Methode angefangen. Habe vorher schon die Authentifizierung und ssl-Unterstützung in die Klasse implementiert, da das, meiner Meinung nach, deutlich leichter zu verstehen ist, als die post()-Methode. Die Authentifizierung wird durch die auth()-Methode vorgenommen. Eigentlich erstellt diese nur den String, der dann an den Server geschickt wird. Die ssl-Unterstützung kann bei der Instanzierung der Klasse ausgewählt werden und wird dann automatisch bei jedem Request durch die login()-Methode angewandt.

Leider habe ich noch einige Probleme mit der Klasse. Und zwar erhalte ich bei der Testausgabe via get() weiterhin am Ende des Contents eine NULL gefolgt von zwei Absätzen. Das sollte eigentlich nicht so sein. Allerdings ist nun wenigstens das c am Anfang des Contents weg. Die Ausgabe ist nun auch etwas übersichtlicher. Allerdings muss da auch noch was gemacht werden. hat hier vielleicht schon jemand eine Idee oder einen Rat? Oder hat jemand eine Anregung oder einen Vorschlag, wie man die momentane Struktur des zurückgegebenen Arrays verbessern kann? Wie dieses Array momentan aussieht und wie der Aufruf von head() und get() aussieht, kann man bei der Testausgabe sehen, die hier zu finden ist.

Ein weiteres Problem habe ich bei der post()-Methode. Ich komm da einfach nicht weiter. verstehe nicht, in welcher Form ich die "normalen" Parameter, die Parameter für Dateiübertragungen und die dazugehörigen Mimetyps übergeben soll. Kann mir da jemand helfen? Der erste Teil ist ja im Prinzip ganz einfach. ist ja eigentlich das gleiche, wie in der get()-Methode ohne Parameter, die an die URL angehängt werden müssten. kann mir also jemand sagen, in welcher Form diese Sachen an den Server übergeben werden müssen?

Wäre euch für eure Hilfe wie immer sehr dankbar. Das Update der Klasse findet ihr unten im alten Beitrag. Das Testscript ist gleich geblieben.

@Ingo
Vielen vielen Dank für deine Mühe. hat mir sehr geholfen.

Ein kleines Danke übrigens auch an Denis Wronka, durch den ich darauf aufmerksam geworden bin, dass viele Server bei HTTP-Requests die Angabe eines Referrers erwarten.

MfG, Andy
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon .wired am 08.05.2008, 15:46

Könntest du den Quellcode bitte nochmal vernünftig posten? Ich habe wenig Lust, den Thread nochmal durchzugehen nach der aktuellen "Version" :? ...
Bild Bild
Benutzeravatar
.wired
Mitglied
 
Beiträge: 315
Registriert: 24.06.2007, 20:36
Wohnort: Diekholzen

Re: HTTP Klasse

Beitragvon Avedo am 08.05.2008, 16:03

Hier der Code.
Code: Alles auswählen
<?php 
error_reporting(E_ALL);

/***
* HttpConnect class allows easy connecting to a foreign server.

* @package HttpConnect
* @version 0.3
* @author Andreas Wilhelm <Andreas2209@web.de>
* @copyright Andreas Wilhelm
**/ 
class HttpConnect
{
   // protected class variables
   protected $host;
   protected $port;
   
   protected $ssl;
   
   // tip by Denis Wronka, who said, taht many servers need a referrer
   protected $referrer;
   
   protected $logStats;
   protected $log;

   /**
   * Constructor - Is called when the class is instanced
   *
   * @access: public
   * @param Str $host
   * @param Int $port
   * @param Bool $log   
   * @return NONE
   */
   public function __construct($host='localhost', $port=80, $log=false, $ssl=false, $referrer="PHP/Http-Referrer")
   {
      // set server-variables
      $this->host = $host;
      $this->port = $port;
      
      $this->ssl = $ssl;
      $this->referrer = $referrer;
      
      // set if the connection with the server should be logged
      $this->logStats = $log;
   }

   /**
   * login() - Connects to the server
   *
   * @access: private
   * @param Str $host
   * @param Int $port
   * @return Handle
   */
   private function login()
   {   
      if ($this->ssl == true)
      {   
         // use ssl-connection and save connection handle
         $handle = @fsockopen('ssl://'.$this->host, $this->port);
         
         // throw error in case of failure
         if (!$handle)
         {
            throw new Exception("SSL-connection failed.\n");
         }
      }

      else
      {
         // connection handle is saved to $handle
         $handle = @fsockopen($this->host, $this->port);
                  
         // throw error in case of failure
         if (!$handle)
         {
            throw new Exception("Connection failed.\n");
         }
      }
      
      
      // switch to non-blocking mode - just return data no response
      set_socket_blocking($handle, true);
      
      // set timeout of the server connection
      stream_set_timeout($handle, 0, 200000);
      
      return $handle;
   }

   /**
   * auth() - Creates a connection to a secured server
   *
   * @access: private
   * @param Str $user
   * @param Str $password
   * @return String
   */
   private function auth($user, $password)
   {      
      if (!empty($user))
      {
         $auth = 'Authorization: Basic '.base64_encode($user.':'.$password)."\r\n";
      }

      else
      {
         $auth = '';
      }
      
      return $auth;
   }
 
   /**
   * logout() - Closes the connection
   *
   * @access: private
   * @return NONE
   */     
   private function logout($handle)
   {
      fclose($handle);
   }

   /**
   * sendCmd() - Sends a command to the server
   *
   * @access: private
   * @param Str $cmd
   * @return NONE
   */
   private function sendCmd($handle, $cmd)
   {
      // send the request
      fputs($handle, $cmd);
      
      // log the request
      $this->log("-> $cmd");
   }
   
   /**
   * readSock() - Reads out the response from the server
   *
   * @access: private
   * @return String
   */
   private function readSock($handle)
   {   
      $response = "";

      while(!feof($handle))
      {
         $response .= fread($handle, 1025);
      }
      
      $this->log($response);
      
      return $response;
   }
         
   /**
   * divideReply() - Spilts up the reply into the different information
   *
   * @access: private
   * @param Str $reply
   * @return Array
   */
   private function divideReply($reply)
   {      
       if( !preg_match('/^HTTP\/(1\.[01]) ([1-5][0-9]{2})/', $reply, $match) )
       {
         return false;
       }
      
       $hb = strpos($reply, "\r\n")+2;
       $cb = strpos($reply, "\r\n\r\n")+4;
      
       $parsed = array(
         'HTTP_VERSION'  => $match[1],
         'STATUS_CODE'   => $match[2],
         'HEADER_FIELDS' => array(),
         'CONTENT'       => (string) substr($reply, $cb+2)
       );
      
       $headerFields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', substr($reply, $hb, $cb-$hb-4)));
       foreach( $headerFields as $headerField )
       {
         if( preg_match('/([^:]+):(.+)/m', $headerField, $match) )
         {
           $parsed['HEADER_FIELDS'][$this->getName($match[1])] = trim($match[2]);
         }
       }
      
       return $parsed;
   }
   
   /**
   * getName() - Returns the name of a received htpp-header-field
   *
   * @access: private
   * @param Str $string
   * @return String
   */
   private function getName( $string )
   {
       return preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($string)));
   } 
         
   /**
   * head() - Returns the HTTP-header like a GET or POST reply but without the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @param Str $user
   * @param Str $password
   * @return Array
   */
   public function head($uri='/', $params=false, $cookies=false, $user="", $password="")
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      // send request to the server
      $this->sendCmd($handle, "HEAD $uri"."$params HTTP/1.1\r\n");
      $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
      $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
      $this->sendCmd($handle, "Connection: close\r\n\r\n");
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * get() - Returns the HTTP-header and the output of the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @param Str $user
   * @param Str $password
   * @return Array
   */
   public function get($uri='/', $params=false, $cookies=false, $user="", $password="")
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      // send request to the server
      $this->sendCmd($handle, "GET $uri"."$params HTTP/1.1\r\n");
      $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
      $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
      $this->sendCmd($handle, "Connection: close\r\n\r\n");
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers and file
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * post() - Returns the HTTP-header and the output of the file
   *
   * @access: public
   * @param Str $uri
   * @param Str $params
   * @param Str $cookies
   * @param Str $fileparams
   * @param Str $mimes
   * @param Str $user
   * @param Str $password
   * @return Array
   */
   public function post($uri='/', $params=false, $cookies=false, $fileparams=false, $mimes=false, $user='',$password='')
   {
      // login to the server
      $handle = $this->login();
      
      // create authorization-string
      $auth = $this->auth($user, $password);
      
      // prepare uri for request
      if (empty($uri) || ($uri{0}!='/'))
      {
         $uri = "/$uri";
      }
            
      // check if parameters should be used and prepare them for request
      if (($params!=false) && (!empty($params)))
      {
         $params = "?$params";
      }
      
      else
      {
         $params = '';
      }
      
      // check if cookies should be used and prepare them for request
      if (($cookies!=false) && (!empty($cookies)))
      {
            $cookies = "Cookie: $cookies\r\n";
      }
      
      else
      {
         $cookies = '';
      }
      
      // prepare host-data
      $host = $this->host;
      if ($this->port != 80)
      {
         $host .= ':'.$this->port;
      }
      
      if (($fileparams==false) || (empty($fileparams)))
      {
         if (($params!=false) && (!empty($params)))
         {
            //prepare the attribut Content-Length
            $length = strlen($params);
            
            // send request and parameters to the server
            $this->sendCmd($handle, "POST ".$uri." HTTP/1.1\r\n");
            $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
            $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
            $this->sendCmd($handle, "Connection: close\r\n");
            
            $this->sendCmd($handle, "Content-Type: application/x-www-form-urlencoded\r\n");
            $this->sendCmd($handle, "Content-Length: ".$length."\r\n\r\n".$params");
         }

         else
         {
            // send request without parameters
            $this->sendCmd($handle, "POST ".$uri." HTTP/1.1\r\n");
            $this->sendCmd($handle, "Host: $host\r\n".$cookies.$auth);
            $this->sendCmd($handle, "User-Agent: ".$this->referrer."\r\n");
            $this->sendCmd($handle, "Connection: close\r\n");
         }
      }
      
      else
      {
      }
      
      // get server response
      $reply = $this->readSock($handle);
      
      // end connection to the server
      $this->logout($handle);
      
      // prepare headers and file
      $data = $this->divideReply($reply);
      
      return $data;
   }
         
   /**
   * log() - Saves all request to the server and their responses into $log
   *
   * @access: private
   * @param Str $str
   * @return NONE
   */
   private function log($str)
   {
      if($this->logStats)
      {
         $this->log .= $str;
      }
   }
         
   /**
   * getLog() - Prints out all requests to the server and their responses
   *
   * @access: public
   * @return NONE
   */
   public function getLog()
   {
      return $this->log;
   }
}

try
{
   // change Content-Type
   header('Content-Type: text/plain');
   $http = new HttpConnect("www.avedo.net", 80, true);
   
   $data = $http->head();
   
   $data2 = $http->get("httptest/test.php", "num=45");
   
   echo $http->getLog();
   
   print_r ($data);
   
   print_r ($data2);
}

catch(Exception $e)
{
   echo $e->getMessage();
}
?>

MfG, Andy

PS: Generelle Anregungen zur Verbesserung sind natürlich auch erwünscht.
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Avedo am 12.05.2008, 17:48

Abend!
Habe eigentlich eine sehr einfache Frage. Habe schon wieder Probleme mit diesen nervigen RegEchsen. :lol: Ich möchte einen Parameter-String der an eine URL angehängt ist zerlegen und habe nun Probleme Dabei, das richtige RegEx dazu zu schreiben bzw. Außer einer for()-Schleife um diese Parameter-Liste zu zerlegen, fällt mir leider nichts ein. Hat jemand eine Idee? Das sieht ja im Allgemeinen so aus:
Code: Alles auswählen
name1=value1&name2=value2&name3=value3

Bin für jede Idee sehr dankbar. Würde das gerne ähnlich diesem hier lösen:
Code: Alles auswählen
    foreach( $params as $parameters)
    {
        if( preg_match('das Regex', $parameters, $match) )
        {
            $param[$match[1]] = trim($match[2]);
        }
    }


Das Problem mit dem Speichern des Contents im Array, also der Fehler in der divideReply()-Methode, besteht übrigens immer noch. Bin da also auch für jede Hilfe offen.
MfG, Andy
Ich bin zu Mimis Religion konvertiert!
I'm so tired of slitting the throats of people calling me a violent psychopath.
Benutzeravatar
Avedo
Mitglied
 
Beiträge: 464
Registriert: 09.12.2007, 20:12
Wohnort: Göttingen

Re: HTTP Klasse

Beitragvon Basti am 12.05.2008, 19:22

Begrenzen sich die Parameter auf die Zahl von drei oder soll eine beliebige Zahl an Parametern mit name1, name2, ... name n möglich sein? Oder hast du die Namen sogar nur zufällig so gewählt?

Denn dann würden die entsprechenden regulären Ausdrücke auch unterschiedlich aussehen. Grundsätzlich würde ich dann aber wieder preg_split() verwenden, da du andernfalls zumindest preg_match_all() bräuchtest, was vermutlich rechenintensiver ist.

Ich kann dir aber auch den RegExp-Evaluator zum Erlernen von Regulären Ausdrücken empfehlen, im Tutorial-Bereich finden sich dort alle wichtigen Informationen die du benötigst.
Ich selbst hatte anfangs auch so meine Probleme mit RegExp, vorallem weil ich sie nur selten brauchte und dann keine Routine reinbekam. Aber mithilfe der genannten Seite und durch häufigere Anwendungen (z.B. bei einer TemplateEngine) habe ich es dann doch geschafft.
Vielleicht hilft dir das ja auch ein wenig ;)
Benutzeravatar
Basti
Moderator
 
Beiträge: 1774
Registriert: 15.06.2006, 17:33
Wohnort: Rheinbreitbach

Nächste

Zurück zu PHP

Wer ist online?

Mitglieder in diesem Forum: 0 Mitglieder und 2 Gäste