host = $host; $this->port = $port; } function connect() { $this->sock = fsockopen($this->host,$this->port,&$this->errno,&$this->errstr,30); set_socket_blocking($this->sock,false); return $this->sock; } /** * will read data from the socket. Since we are using non blocking * mode, if we attempt to read the data even a millisecond before * it becomes available, the method just returns null. * * So what's the cure? we will loop for a while and try to read it * in multiple times. Note that if we used blocking mode there may * be instances when this function NEVER returns. */ function sock_read($i=0) { $s = fgets($this->sock); if($s=='') { if($i==30) { return ""; } else { sleep(1); return $this->sock_read($i+1); } } return $s; } function is_ok() { $this->message = $this->sock_read(); if($this->message == "" || preg_match('/^5/',$this->message) ) { return 0; } else { return 1; } } function sock_write($s) { echo "< $s\n"; fputs($this->sock,"$s\n"); } function dir_list($path="") { $s=""; if($this->pasv()) { if($path == '') { $this->sock_write("LIST"); } else { $this->sock_write("LIST $path"); } if($this->is_ok()) { while(true) { $line = fgets($this->data_sock); $s .= $line; if($line =='') break; } } } return $s; } function pasv() { $this->sock_write("PASV"); if($this->is_ok()) { $offset = strpos($this->message,"("); $s = substr($this->message,++$offset,strlen($this->messsage)-2); $parts = split(",",trim($s)); $data_host = "$parts[0].$parts[1].$parts[2].$parts[3]"; $data_port = ((int)$parts[4] << 8) + (int) $parts[5]; $this->data_sock = fsockopen($data_host,$data_port,&$errno,&$errstr,30); return $this->data_sock; } return ""; } } $ftp = new FTP("localhost"); $sock = $ftp->connect(); if($sock) { if($ftp->is_ok()==1) { $ftp->sock_write("user imapuser"); if($ftp->is_ok()) { $ftp->sock_write("pass 123"); if($ftp->is_ok()) { echo $ftp->dir_list(); } } } } ?>