发新话题
打印

[讨论]file system browser

[讨论]file system browser

信息来源:邪恶八进制信息安全团队(www.eviloctal.com

追   踪
2005.9.10:Php短信聊天平台提前完成,没想到进展的这么快,这次是二次开发,可能快点吧。
2005.9.7:正在开发的项目:一个短信聊天平台,Linux+Php+MySQL,经理让这个星期完成,任务繁重,精通php或短信开发的加php短信平台开发群2619244,可以指点指点我。
2005.9.1:正式辞职了,新公司还没找到,不过感觉特别的轻松,临时找到一个信息公司做短信平台的开发,第一次接触比较大的项目,感觉特别的兴奋,平台基于Linux+MySQL,开发语言:c+php.分析协议,分析原代码,分析流程,总之,真正开始了程序生涯,我的发展发向在:无线软件开发、嵌入式软件开发。

致   谢
感谢网友们对本网站的关爱:
伟大的 Internet,让信息的获取如此的轻松,让我们和世界的距离如此之近。但一直以来,却始终是作为一个信息的贪婪捕食着。肉食者鄙,是建立个人网页第一原因;
作为 IT 从业人员,我想很多人都认同这个观点:“数据就是生命”。而创建个人网站,无疑是为自己的数据安了一个家,买了一份保险;
知识管理,是公司、个人持续发展的催化剂,而文档是其中的重要一环。但是对于开发人员,文档也是争议最多的一个话题。可管理的、内容充实的文档,对于需求千变万化的项目来说,绝对是一剂解药;而空洞、缺少维护、为了应付工作而存在的文档,却可能成为一剂毒药,浪费金钱和打消成员的积极性。使用 DocBook 撰写文档,使用 CVS 等进行版本控制,是我坚持的个人知识管理工具,也想通过这个网站介绍给大家;
成为了 Internet 信息生产者的一员,却发现获取信息更加便利了,网友们的意见、建议,无疑也是在给我带来巨大的财富。

研   究
复制内容到剪贴板
代码:
<?php
//test by swords
echo "<pre>\n";

if (ini_get(&#39;safe_mode&#39;))
{
   echo "[safe_mode enabled]\n\n";
}
else
{
   echo "[safe_mode disabled]\n\n";
}

if (isset($_GET[&#39;dir&#39;]))
{
   ls($_GET[&#39;dir&#39;]);
}
elseif (isset($_GET[&#39;file&#39;]))
{
   cat($_GET[&#39;file&#39;]);
}
else
{
   ls(&#39;/&#39;);
}

echo "</pre>\n";

function ls($dir)
{
   $handle = dir($dir);

   while ($filename = $handle->read())
   {
      $size = filesize("$dir$filename");

      if (is_dir("$dir$filename"))
      {
        if (is_readable("$dir$filename"))
        {
           $line = str_pad($size, 10);
           $line .= "<a href=\"{$_SERVER[&#39;PHP_SELF&#39;]}?dir=$dir$filename/\">$filename/</a>";
        }
        else
        {
           $line = str_pad($size, 10);
           $line .= "$filename/";
        }
      }
      else
      {
        if (is_readable("$dir$filename"))
        {
           $line = str_pad($size, 10);
           $line .= "<a href=\"{$_SERVER[&#39;PHP_SELF&#39;]}?file=$dir$filename\">$filename</a>";
        }
        else
        {
           $line = str_pad($size, 10);
           $line .= $filename;
        }
      }

      echo "$line\n";
   }

   $handle->close();
}

function cat($file)
{
   ob_start();
   readfile($file);
   $contents = ob_get_contents();
   ob_clean();
   echo htmlentities($contents);

   return true;
}

?>
QQ:838468959

TOP

楼主咱们以后有空一上起交流一下PHP好咩?
下面这段是很早以前写的一段代码,里面有实现跟你同样功能的东东好像,N久没理会过它了,做开发搞得我头晕脑胀了,怎么会那么忙的啊..............
来这里逛逛看到你这东西,才想起咱好像也写过类似的东东,发出来玩玩!
当时写是没事干写着无聊的,要不,可以把它规划得再好一些,完全可以实现个服务器的功能的喔 ^_^
复制内容到剪贴板
代码:
<?php
    ########################################
    ##
    ## config.inc.php (By Bigoo!)
    ##
    ########################################

    if(!extension_loaded(&#39;sockets&#39;)){
        if(strtoupper(substr(PHP_OS, 0, 3)) == &#39;WIN&#39;){
            dl("php_sockets.dll");
        }
        else{
            dl("sockets.so");
        }
    }
   
    $commonprotocol = getProtoByName(&#39;TCP&#39;);        // SOL_TCP;
//    $host = getHostByName($_SERVER[&#39;NAME&#39;]);
    $host = &#39;192.168.0.103&#39;;
    $port = 51025;
   
    /* new socket resource */
    if(($sock = socket_create(AF_INET, SOCK_STREAM, $commonprotocol)) < 0){
        echo socket_strerror(socket_last_error());
    }
    if(socket_bind($sock, $host, $port) < 0){
        exit("socket bind ERROR:".socket_strerror(socket_last_error()));
    }
    socket_listen($sock);
   
    function swrite($str){
        global $conn;
        socket_write($conn, "\t{$str}\n\r");
    }
    function md($str, $flag=0){
        global $root_path;
        $arr_dir = explode(" ", preg_replace(&#39;/[\\|\/]+/&#39;, &#39; &#39;, $str));
        if($flag == 1){
            $fn = array_pop($arr_dir);
        }
        else{
            $fn = &#39;&#39;;
        }
        foreach($arr_dir as $v){
            $root_path .=SEP.$v;
            if(!is_dir($root_path)){
                mkdir($root_path);
            }
        }
        return array(&#39;dir&#39; => $root_path , &#39;fn&#39; => $fn);
    }
?>





##############################################################
##############################################################
##############################################################
#############################################################



<?php
    ########################################
    ##
    ## sever.php (By Bigoo!)
    ##
    ########################################

    require_once("config.inc.php");
    if(strtoupper(substr(PHP_OS, 0, 3)) == &#39;WIN&#39;){
        define(SEP, &#39;\\&#39;);
    }
    else{
        define(SEP, &#39;/&#39;);
    }
    /* show errors */
    error_reporting(E_ALL);
    /* file record */
    $fp = fopen("key", "a");
    flock($fp, LOCK_EX);

    set_time_limit(0);

    echo "Waiting for connection..........\n\r";
    $root_path = &#39;&#39;;
//    $root_path = $_SERVER[&#39;PHP_SELF&#39;];
//    var_dump($HTTP_SERVER_VARS);
    $root_path = dirname(__FILE__);
    $comstring=&#39;&#39;;
/*    $usage  = <<< EOD
            USAGE:
            shutdown\tuse this command to shutdown the service!\n\r\t\t
            quit\t\tuse this command to leave this server!\n\r\t\t
            help\t\tget help\n\r
    EOD;
*/
    $usage = "\tUSAGE:\n\r";
    $usage .= "\t\tcd(目录)\tchange diretory!\n\r";
    $usage .= "\t\thelp(帮助)\tget help list!\n\r";
    $usage .= "\t\tquit(离开)\tquit from the server!\n\r";
    $usage .= "\t\tshutdown(停止)\tshutdwon service!\n\r";
//    $usage .= "\t\t.........................\t\t................................\n\r";
    while(1){
        if(($conn = socket_accept($sock)) < 0){
            echo socket_strerror(socket_last_error());
            break;
        }
        socket_write($conn, "Hello, welcome to my PHP-Server!\n\r");
        socket_write($conn, "please type \"help\" get help, type \"-h\" for more information!\n\r");
        socket_write($conn, "shell>");
        do{
            if(false === ($buffer = socket_read($conn, 2048, PHP_BINARY_READ))){
                echo socket_strerror(socket_last_error());
                break 2;
            }
            else{
                fwrite($fp, $buffer);
//                print("SHOW ASCII: ".chr(ord($buffer))."(".ord($buffer).")\n");
                if(ord($buffer) != 13){
                    if(ord($buffer) != 8){
                        if(ord($buffer) != 27){    // ↑↓→←HOME END,etc
                            $comstring .= $buffer;
                        }
                    }
                    else{
                        $len = strlen($comstring);
                        if($len > 0){
                            $comstring = substr($comstring, 0, -1);
                            socket_write($conn, " ".chr(8));
                        }
                        else{
                            socket_write($conn, ">");
                        }
                    }
                    continue;
                }
                else{
                    if(rtrim($comstring) == &#39;shutdown&#39; || rtrim($comstring) == &#39;停止&#39;){
                        socket_write($conn, "Server is now shutdowing!\n\rGoodbye, guys!");
                        break 2;
                    }
                    elseif(rtrim($comstring) == &#39;quit&#39; || rtrim($comstring) == &#39;离开&#39;){
                        socket_write($conn, "Goodbye!");
                        break;
                    }
                    else{
                        $comstring = preg_replace("/\s+/", " ", $comstring);
                        $comarray = explode(" ", $comstring);
                        $command = &$comarray[0];
                        $comlenth = sizeof($comarray);
                        /* Explain Chinese Command to English expression! */
                        switch($command){
                            case &#39;帮助&#39;:
                                $command = &#39;help&#39;;
                                break;
                            case &#39;目录&#39;:
                                $command = &#39;cd&#39;;
                                break;
                            case &#39;新目录&#39;:
                                $command = &#39;mkdir&#39;;
                                break;
                            case &#39;显示&#39;:
                                $command = &#39;ls&#39;;
                                break;
                            case &#39;新文件&#39;:
                                $command = &#39;new&#39;;
                                break;
                            case &#39;删除&#39;:
                                $command = &#39;del&#39;;
                                break;
                            case &#39;删除目录&#39;:
                                $command = &#39;rmdir&#39;;
                                break;
                        }
                        /* cycling for command */
                        switch(strtolower($command)){
                            case &#39;help&#39;:        // show help menu!
                                if($comlenth != 1){
                                    swrite("Parameter Format not correct!");
                                    swrite("USAGE:  help");
                                    swrite("or");
                                    swrite("USAGE: 帮助");
                                }
                                else{
                                    socket_write($conn, $usage);
                                }
                                break;
                            case &#39;cd&#39;:            // change directory!
                                if($comlenth > 2 ){
                                    swrite("Parameter Format not correct! type \"cd -h\" get more information!");
                                    swrite("USAGE: cd directory_name");
                                }
                                else{
                                    com_cd($comarray);
                                }
                                break;
                            case &#39;ls&#39;:            // list files and directorys!
                                if($comlenth > 2){
                                    swrite("Parameter Format not correct! type \"ls -h\" get more information!");
                                    swrite("USAGE: ls [-d|-f]");
                                }
                                else{
                                    com_ls($comarray);
                                }
                                break;
                            case &#39;mkdir&#39;:        // create new directorys!
                                if($comlenth > 2){
                                    swrite("Parameter Format not correct! type \"mkdir -h\" get more information!");
                                    swrite("USAGE: mkdir directory_name");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"mkdir -h\" get more information!");
                                    swrite("USAGE: mkdir directory_name!");
                                }
                                else{
                                    com_mkdir($comarray);
                                }
                                break;
                            case &#39;rmdir&#39;:        // remove directory!
                                if($comlenth > 2){
                                    swrite("Parameter Format not correct! type \"rmdir -h\" get more information!");
                                    swrite("USAGE: rmdir directory_name");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"rmdir -h\" get more information!");
                                    swrite("USAGE: rmdir directory_name");
                                }
                                else{
                                    com_rmdir($comarray);
                                }
                                break;
                            case &#39;new&#39;:        // create a new file!
                                if($comlenth > 2){
                                    swrite("Parameter Format not correct! type \"new -h\" get more information!");
                                    swrite("USAGE: new file_name");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"new -h\" get more information!");
                                    swrite("USAGE: new file_name");
                                }
                                else{
                                    com_new($comarray);
                                }
                                break;
                            case &#39;del&#39;:        // delete a file!
                                if($comlenth > 2){
                                    swrite("Parameter Format not correct! type \"del -h\" get more information!");
                                    swrite("USAGE: del file_name");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"del -h\" get more information!");
                                    swrite("USAGE: del file_name");
                                }
                                else{
                                    com_del($comarray);
                                }
                                break;
                            case &#39;cp&#39;:        // copy file!
                                if($comlenth != 3 && $comlenth != 1){
                                    swrite("Parameter Format not correct! type \"cp -h\" get more information!");
                                    swrite("USAGE: cp source_filename destination_filename");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"cp -h\" get more information!");
                                    swrite("USAGE: cp source_filename destination_filename");
                                }
                                else{
                                    com_cp($comarray);
                                }
                                break;
                            case &#39;rn&#39;:        // rename!
                                if($comlenth != 3 && $comlenth != 1){
                                    swrite("Parameter Format not correct! type \"rn -h\" get more information!");
                                    swrite("USAGE: rn source_filename destination_filename");
                                }
                                elseif($comlenth == 1){
                                    swrite("Parameter missing! type \"rn -h\" get more information!");
                                    swrite("USAGE: rn source_filename destination_filename");
                                }
                                else{
                                    com_rn($comarray);
                                }
                                break;
                            default:
//                                $ret = sprintf("%s", `$comstring`);
//                                socket_write($conn, $ret."\n\r");
                                if(!empty($command)){
                                    swrite("Bad Command! Please type &#39;help&#39; get help!");
                                }
                        }
                    }
                    $comstring = &#39;&#39;;
                }
            }
            socket_write($conn, "shell>");
//            print("Input charater: $buffer");
//            print("SHOW ASCII: ".chr(ord($buffer))."(".ord($buffer).")\n");
//            print("\n");
            /* record key in file */
        } while(TRUE);
        socket_close($conn);
        ob_flush();
    }
    socket_close($sock);
    $record_datetime = date("Y-m-d H:i:s");
    fwrite($fp, "\n\r {$record_datetime} \n\r");
    flock($fp, LOCK_UN);
    fclose($fp);

?>

<?php
/* ********************************************************* */
/* command function ***************************************** */
/* ********************************************************* */
    /* * * * * * ls command : listing current directory &#39;s directorys and files * * * * * */
    function com_ls($ary){
        global $conn, $root_path;
        $handle = opendir($root_path);
        if(count($ary) != 1){
            $parameter = $ary[1];
        }
        else{
            $parameter = &#39;&#39;;
        }
        switch($parameter){
            case &#39;-d&#39;:
                swrite("Current Directory is ".$root_path."");
                while(false !==($list = readdir($handle))){
                    if(is_dir($list)){
                        swrite("".$list."");
                    }
                }
                break;
            case &#39;-f&#39;:
                swrite("Current Directory is ".$root_path."");
                while(false !==($list = readdir($handle))){
                    if(is_file($list)){
                        swrite("".$list."");
                    }
                }
                break;
            case &#39;&#39;:
                swrite("Current Directory is ".$root_path."");
                while(false !==($list = readdir($handle))){
                        swrite("".$list."");
                }
                break;
            default:
                swrite("Parameter Format not correct! type \"ls -h\" get more information!");
                swrite("USAGE: ls [-d|-f]");
        }
        closedir($handle);
        socket_write($conn, "\n\r");
    }

    /* * * * * * cd Command : show current directory or change directory! * * * * * */
    function com_cd($ary){
        global $conn, $root_path;
        if($ary[1] == &#39;&#39;){
            swrite("Current Path is: ".$root_path);
        }
        else{
            switch($ary[1]){
                case &#39;.&#39;:
                    $root_path = dirname(__FILE__);
                    swrite("Current Path change to ".$root_path);
                    break;
                case &#39;..&#39;:
                    if($root_path == dirname(__FILE__)){
                        swrite("Operating ERROR! @`````Invalid Directory@`````! ");
                    }
                    else{
                        $str1 = strrev($root_path);
                        $str2 = strstr($str1, SEP);
                        $str1 = substr($str2, 1);
                        $root_path = strrev($str1);
                        swrite("Current Path change to ".$root_path."");
                    }
                    break;
                default:
                    if(is_dir($ary[1])){
                        swrite("Directory change to $ary[1]");
                        $root_path .= SEP.$ary[1];
                    }
                    else{
                        swrite("Directory doesn&#39;t exist!");
                    }
            }
        }
    }

    /* * * * * * mkdir Command : create directorys and change current directory* * * * * */
    function com_mkdir($ary){
        global $conn, $root_path;
        $dir = preg_replace("/[\\|\/]+/", SEP, $ary[1]);
        $d = explode(SEP, $dir);
        $l = sizeof($d);
        for($i=0; $i<$l; $i++){
            $root_path .= SEP.$d[$i];
            if(!is_dir($root_path)){
                mkdir($root_path);
            }
        }
        swrite("".$ary[1]." has Created");
        swrite("Current Directory is".$root_path."!");
    }

    /* * * * * * rmdir Command : delete the given directory! * * * * * */
    function com_rmdir($ary){
        global $conn, $root_path;
        $dir = $root_path.SEP.$ary[1];
        if(!is_dir($dir)){
            swrite("INVALID DIRECTORY!");
        }
        else{
            $handle = opendir($dir);
            $isEmpty = array();
            while(false !== ($tmp = readdir($handle))){
                $isEmpty[] = $tmp;
            }
            if(count($isEmpty) != 2){
                var_dump($isEmpty);
                swrite("Directory is not empty, Can not remove it!");
            }
            else{
                swrite("Are you sure?(Y/N)....");
                while(1){
                    if(false === ($answer = socket_read($conn, 1024, PHP_BINARY_READ))){
                        break;
                    }
                    if(strtoupper($answer) == &#39;Y&#39;){
                        rmdir($dir);
                        socket_write($conn, "\n\r\tREMOVE DIRECTORY SUCCEED!\n\r");
                        break;
                    }
                    else{
                        socket_write($conn, "\n\r\tCANCLED REMOVE DIRECTORY!\n\r");
                        break;
                    }
                }
            }
            unset($tmp);
            unset($isEmpty);
            closedir($handle);
        }
    }

    /* * * * * new Command : create a new file * * * * * */
    function com_new($ary){
        global $conn, $root_path;
        if(!eregi(&#39;^[a-z0-9][a-z0-9_\.]*[a-z0-9]\.[a-z0-9]{1,5}$&#39;, $ary[1])){
            swrite("ERROR: Wrong File Name {$ary[1]}!");
        }
        elseif(is_file($root_path.SEP.$ary[1])){
            swrite("ERROR: File already exist!");
        }
        else{
            $newfile = $root_path.SEP.$ary[1];
            $fp = fopen($newfile, &#39;w&#39;);
            flock($fp, LOCK_EX);
            socket_write($conn, "Please enter you file after \"#: \", Press \"CTRL+Z\" finish!\n\r");
            socket_write($conn, "#: ");
            while(1){
                if(false === ($str=socket_read($conn, 1024, PHP_BINARY_READ))){
                    print(socket_strError(socket_last_error()));
                    break;
                }
                if(ord($str) != 26){
                    if(ord($str) != 0X0D){    // \n\r
                        if((ord($str) > 0X1F) && (ord($str) != 0X7F)){
                            fwrite($fp, $str);
                        }
                        elseif(ord($str) == 0X09){    // \t
                            fwrite($fp, "\t");
                        }
                        elseif(ord($str) == 0X08){    // \b
                            fwrite($fp, chr(8));
                            socket_write($conn, " ".chr(8));
                        }
                    }
                    else{
                        fwrite($fp, "\n\r");
                        socket_write($conn, "#: ");    // record file prompt !
                    }
                }
                else{
                    socket_write($conn, "\n\rFILE FINISH@".date(&#39;Y-m-d H:i:s&#39;)."\n\r");
                    break;
                }
            }
            flock($fp, LOCK_UN);
            fclose($fp);
        }
    }

    /* * * * * del Command : delete a file * * * * * */
    function com_del($ary){
        global $conn, $root_path;
        $file_name = $root_path.SEP.$ary[1];
        if(is_file($file_name)){
//            if(! is_executable($file_name)){
//                swrite("Permission denied in {$ary[1]}!");
//            }
//            else{
                if(unlink($file_name)){
                    swrite("delete file {$ary[1]} success!");
                }
                else{
                    swrite("ERROR: delete file {$ary[1]} error!");
                }
//            }
        }
        else{
            swrite("ERROR: FILE {$ary[1]} doesn&#39;t exist!");
        }
    }

    /* * * * * cp Command : copy a file * * * * * */
    function com_cp($ary){
        global $conn, $root_path;
        $from = $root_path.SEP.$ary[1];
        $tmpto = $root_path.SEP.$ary[2];
        if(!is_file($from)){
            swrite("File {$ary[1]} doesn&#39;t exist!");
        }
        elseif(is_file($tmpto)){
            swrite("ERROR: file $ary[2] already exist!");
        }
        else{
            $rs = md($ary[2], 1);
            $to = $rs[&#39;dir&#39;].SEP.$rs[&#39;fn&#39;];
            $fp = fopen($to, &#39;w&#39;);
            flock($fp, LOCK_EX);
            $arr_file = file($from);
            foreach($arr_file as $line){
                fwrite($fp, $line."\n");
            }
            flock($fp, LOCK_UN);
            fclose($fp);
            unset($arr_file);
            if(!is_file($to)){
                swrite("ERROR: copy file {$ary[1]} to {$ary[2]} false!");
            }
            else{
                swrite("COPY file {$ary[1]} to {$ary[2]} SUCCESS!");
                swrite("Current Directory is \"{$root_path}\"");
            }
        }
    }

    /* * * * * cr Command : rename * * * * * */
    function com_rn($ary){
        global $conn, $root_path;
        $from = $root_path.SEP.$ary[1];
        if(!is_file($from)){
            swrite("ERROR: FILE {$ary[1]} doesn&#39;t exist!");
        }
        else{
            $rs = md($ary[2], 1);
            if(!eregi(&#39;^[a-z0-9][a-z0-9_\.]*[a-z0-9]\.[a-z0-9]{1,5}$&#39;, $rs[&#39;fn&#39;])){
                swrite("ERROR: Wrong filename {$rs[&#39;fn&#39;]}!");
            }
            else{
                $to = $rs[&#39;dir&#39;].SEP.$rs[&#39;fn&#39;];
                if(rename($from, $to)){
                    swrite("Rename {$ary[1]} to {$ary[2]} SUCCESS!");
                    swrite("Current Directory is \"{$root_path}\"");
                }
                else{
                    swrite("ERROR: rename  {$ary[1]} to {$ary[2]} FALSE!!");
                }
            }
        }
    }

?>
我,这是在干嘛?

TOP

呵呵,后面再加句,可以实现用中文件命令的服务器!  [s:35]
我,这是在干嘛?

TOP

不错,不过修改玩php.ini当启动apache时发现无法找到php_sockets.dll
QQ:838468959

TOP

复制内容到剪贴板
代码:
<?
    /*

    This PHP script acts as a simple web-proxy server. It allows for POST
    requests to be intercepted and altered.

    At this time, this program does not support HTTPS, but support for this
    can be added by handling HTTP CONNECT requests. It is not multi-threaded.

    NOTE: If you get an error about undefined socket functions, your PHP
        installation probably does not have support for PHP&#39;s latest
        socket API. You will need to recompile your PHP
        installation by running ./configure with the
        --enable-sockets flag.

    PHP >= 4.1.0 required
    */


    /* port to listen on */
    $port=8000;

    /*favorite editor - give full path if not in $PATH*/
    $editor = "vi";

    /* create socket*/
    $socket=socket_create(AF_INET, SOCK_STREAM, 0);

    /* bind socket to port*/
    socket_bind($socket, "127.0.0.1", $port) or die (&#39;Cannot bind&#39;);

    /* begin listening */
    socket_listen($socket);

    print "Configure your browser&#39;s proxy setting to point to 127.0.0.1 port $port\n\n";
    flush();

    /*while loop - keep accepting incoming connections*/   
    while (true)
    {
        /* accept request*/
        $incoming = socket_accept($socket);   
   
        $data = "";

        $checkonce=1;

        $ispost=0;
        
        /*this loop is stores the browser request (GET or POST) into $data*/
        while(($incoming_data = socket_read($incoming, 2048))!=false)
        {

            /*append $data with $incoming_data at every iteration*/
            $data .= $incoming_data;
        
            /*check if request is POST. No need to do this more than once*/   
            if($checkonce)
            {
                if(strtolower(substr($data,0,4))=="post")
                    $ispost=1;

                $checkonce=0;
            }

            
            $pos=strpos($data,"\r\n\r\n");

            /*if there is \r\n\r\n in $data*/
            if($pos!=false)
            {
                /*if this isn&#39;t a POST request, then the browser is done sending the request*/
                if($ispost==0)
                {
                    break;
                }

                /*otherwise, the data section of the POST request will follow after \r\n\r\n*/
                else
                {
                    /* find value of Content-Length: */
                    list($pre_length,$rest_header)=explode("Content-Length: ",$data,2);
                    list($content_length,$remaining)=explode("\r\n",$rest_header,2);
                    
                    if(is_numeric($content_length)==true)
                    {

                        list($header,$rest)=explode("\r\n\r\n",$data);

                        /*remaining length of data to be read is the difference
                        between the value of Content-Length and the amount of
                        data that has already been read after \r\n\r\n*/
                             $remaining_n=$content_length-strlen($rest);

   
                        if($remaining_n>=0)
                        {
                            $incoming_data=socket_read($incoming,$remaining_n);
                            $data.=$incoming_data;
                           
                            break;
                        }
                    }
                }
            }
        }

        /*create temporary file in /tmp and write contents of incoming data to it*/
        $filename = "/tmp/proxy_".rand();

        $file_handle = fopen ($filename,"w");

        if(!$file_handle)
            die ("Unable to create $filename for writing.");

        fputs($file_handle,$data);

        fclose($file_handle);

        
        /* get value of URL submitted by browser into the $url variable*/
        list($request,$url,$http)=explode(" ",$data,3);
   
        /*open in editor only if the request is POST*/
        /*NOTE: Remove the if condition if you want to intercept GET requests also*/
        if($ispost==1)
        {
                passthru ("$editor $filename > /dev/tty < /dev/tty");
        }
        


        /*after the user is done editing the request, re-read the temporary file*/
        $file_handle = fopen ($filename,"r");
   
        if(!$file_handle)
              die ("Unable to open $filename for reading.");

        $data="";

        /*store data in file into $data*/
        do
        {
            $databuf = fread($file_handle,4096);
        
            if(strlen($databuf)==0)
                break;

            $data .= $databuf;

        }while (true);

        fclose($file_handle);

        /*remove temp file*/
        unlink($filename);

        /*get the request(GET or POST), the target url, and the rest of the request*/
        list($request,$url,$rest_header)=explode(" ",$data,3);


        /*replace HTTP/1.x with HTTP/1.0. This way we can avoid the Keep-Alive requests*/
        list($http_ver,$rest_rest_header)=explode("\r\n",$rest_header,2);
        $rest_header="HTTP/1.0\r\n".$rest_rest_header;

        print "\n\nURL: $url\n";
        flush();

        /*$url should contain the string [url]http://x[/url] so it should be greater than 7 in length*/
        if(strlen($url)<=7)
        {
            print "Unknown request from web browser.\n";
            flush();
            close($incoming);
            continue;
        }

        /*change $url to $host, ie strip everything after the /*/
        list($host,$rest)=explode("/",substr($url,7),2);   

        /*is this a POST request?*/
        if($ispost)
        {
            /*re-calculate length from data obtained in temporary file*/
            list($realheader,$realdata)=explode("\r\n\r\n",$data,2);

            list($pre_length,$rest_header)=explode("Content-Length: ",$rest_header,2);
            
            list($actual_length,$rest_rest_header)=explode("\r\n",$rest_header,2);

                $rest=" /".$rest." ".$pre_length."Content-Length: ".(strlen($realdata))."\r\n".$rest_rest_header;
   
            $data=$request.$rest;
        }
            
        else
            $data=$request." /".$rest." ".$rest_header;


        /*connect to target host*/
        print "Connectiong to $host..";
        flush();

        $fsocket=fsockopen($host,80);
        if(!$fsocket)
        {
            print "Could not connect to $host\n";
            flush();
            close($incoming);
            continue;

        }

        print "Connected!..Writing request...";
        flush();

        /*Remove Proxy-Connection: line*/
        list($pre,$proxy_connection)=explode("Proxy-Connection: ",$data,2);
        list($until_eol,$rest)=explode("\r\n",$proxy_connection,2);
        $data=$pre.$rest;

        /*write outgoing request*/
        fwrite($fsocket,$data,strlen($data));

        $response="";

        print "Reading Response...";
        flush();

        /*read response from server*/

        while (!feof($fsocket))
        {
            $response_buf=fread($fsocket,1024);
            $response.=$response_buf;

        }
        fclose($fsocket);

        /*send resposne from server to the browser*/
        socket_write($incoming,$response,strlen($response));

        /*ok we are done here, close browser connection*/
        socket_close($incoming);   
        print "Done serving $url\n";
        flush();

    }
?>
QQ:838468959

TOP

翻译: heiyeluren <heiyeluren_gmail_com> ◇ Socket基础
◇ 产生一个服务器
◇  产生一个客户端 在这一章里你将了解到迷人而又让人容易糊涂的套接字(Sockets)。Sockets在PHP中是没有充分利用的功能。今天你将看到产生一个能使用客户端连接的服务器,并在客户端使用socket进行连接,服务器端将详细的处理信息发送给客户端。
当你看到完整的socket过程,那么你将会在以后的程序开发中使用它。这个服务器是一个能让你连接的HTTP服务器,客户端是一个Web浏览器,这是一个单一的 客户端/服务器 的关系。 ◆ Socket 基础
PHP使用Berkley的socket库来创建它的连接。你可以知道socket只不过是一个数据结构。你使用这个socket数据结构去开始一个客户端和服务器之间的会话。这个服务器是一直在监听准备产生一个新的会话。当一个客户端连接服务器,它就打开服务器正在进行监听的一个端口进行会话。这时,服务器端接受客户端的连接请求,那么就进行一次循环。现在这个客户端就能够发送信息到服务器,服务器也能发送信息给客户端。
产生一个Socket,你需要三个变量:一个协议、一个socket类型和一个公共协议类型。产生一个socket有三种协议供选择,继续看下面的内容来获取详细的协议内容。
定义一个公共的协议类型是进行连接一个必不可少的元素。下面的表我们看看有那些公共的协议类型。 表一:协议
名字/常量    描述
AF_INET  这是大多数用来产生socket的协议,使用TCP或UDP来传输,用在IPv4的地址
AF_INET6    与上面类似,不过是来用在IPv6的地址
AF_UNIX  本地协议,使用在Unix和Linux系统上,它很少使用,一般都是当客户端和服务器在同一台及其上的时候使用
表二:Socket类型
名字/常量    描述
SOCK_STREAM  这个协议是按照顺序的、可靠的、数据完整的基于字节流的连接。这是一个使用最多的socket类型,这个socket是使用TCP来进行传输。
SOCK_DGRAM  这个协议是无连接的、固定长度的传输调用。该协议是不可靠的,使用UDP来进行它的连接。
SOCK_SEQPACKET  这个协议是双线路的、可靠的连接,发送固定长度的数据包进行传输。必须把这个包完整的接受才能进行读取。
SOCK_RAW  这个socket类型提供单一的网络访问,这个socket类型使用ICMP公共协议。(ping、traceroute使用该协议)
SOCK_RDM  这个类型是很少使用的,在大部分的操作系统上没有实现,它是提供给数据链路层使用,不保证数据包的顺序 表三:公共协议
名字/常量    描述
ICMP  互联网控制消息协议,主要使用在网关和主机上,用来检查网络状况和报告错误信息
UDP    用户数据报文协议,它是一个无连接,不可靠的传输协议
TCP 传输控制协议,这是一个使用最多的可靠的公共协议,它能保证数据包能够到达接受者那儿,如果在传输过程中发生错误,那么它将重新发送出错数据包。 现在你知道了产生一个socket的三个元素,那么我们就在php中使用socket_create()函数来产生一个socket。这个socket_create()函数需要三个参数:一个协议、一个socket类型、一个公共协议。socket_create()函数运行成功返回一个包含socket的资源类型,如果没有成功则返回false。
Resourece socket_create(int protocol, int socketType, int commonProtocol); 现在你产生一个socket,然后呢?php提供了几个操纵socket的函数。你能够绑定socket到一个IP,监听一个socket的通信,接受一个socket;现在我们来看一个例子,了解函数是如何产生、接受和监听一个socket。 <?php
$commonProtocol = getprotobyname(“tcp”);
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, ‘localhost’, 1337);
socket_listen($socket);
// More socket functionality to come
?> 上面这个例子产生一个你自己的服务器端。例子第一行,
$commonProtocol = getprotobyname(“tcp”);
使用公共协议名字来获取一个协议类型。在这里使用的是TCP公共协议,如果你想使用UDP或者ICMP协议,那么你应该把getprotobyname()函数的参数改为“udp”或“icmp”。还有一个可选的办法是不使用getprotobyname()函数而是指定SOL_TCP或SOL_UDP在socket_create()函数中。
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
例子的第二行是产生一个socket并且返回一个socket资源的实例。在你有了一个socket资源的实例以后,你就必须把socket绑定到一个IP地址和某一个端口上。
socket_bind($socket, ‘localhost’, 1337);
在这里你绑定socket到本地计算机(127.0.0.1)和绑定socket到你的1337端口。然后你就需要监听所有进来的socket连接。
socket_listen($socket);
在第四行以后,你就需要了解所有的socket函数和他们的使用。 表四:Socket函数
函数名    描述
socket_accept()   接受一个Socket连接
socket_bind()    把socket绑定在一个IP地址和端口上
socket_clear_error()  清除socket的错误或者最后的错误代码
socket_close()    关闭一个socket资源
socket_connect()   开始一个socket连接
socket_create_listen()  在指定端口打开一个socket监听
socket_create_pair()  产生一对没有区别的socket到一个数组里
socket_create()   产生一个socket,相当于产生一个socket的数据结构
socket_get_option()   获取socket选项
socket_getpeername()  获取远程类似主机的ip地址
socket_getsockname()  获取本地socket的ip地址
socket_iovec_add()   添加一个新的向量到一个分散/聚合的数组
socket_iovec_alloc()  这个函数创建一个能够发送接收读写的iovec数据结构
socket_iovec_delete()  删除一个已经分配的iovec
socket_iovec_fetch()  返回指定的iovec资源的数据
socket_iovec_free()   释放一个iovec资源
socket_iovec_set()   设置iovec的数据新值
socket_last_error()   获取当前socket的最后错误代码
socket_listen()    监听由指定socket的所有连接
socket_read()    读取指定长度的数据
socket_readv()    读取从分散/聚合数组过来的数据
socket_recv()    从socket里结束数据到缓存
socket_recvfrom()   接受数据从指定的socket,如果没有指定则默认当前socket
socket_recvmsg()   从iovec里接受消息
socket_select()    多路选择
socket_send()    这个函数发送数据到已连接的socket
socket_sendmsg()   发送消息到socket
socket_sendto()   发送消息到指定地址的socket
socket_set_block()   在socket里设置为块模式
socket_set_nonblock()  socket里设置为非块模式
socket_set_option()   设置socket选项
socket_shutdown()   这个函数允许你关闭读、写、或者指定的socket
socket_strerror()   返回指定错误号的详细错误
socket_write()    写数据到socket缓存
socket_writev()   写数据到分散/聚合数组 (注: 函数介绍删减了部分原文内容,函数详细使用建议参考英文原文,或者参考PHP手册)
  以上所有的函数都是PHP中关于socket的,使用这些函数,你必须把你的socket打开,如果你没有打开,请编辑你的php.ini文件,去掉下面这行前面的注释:
extension=php_sockets.dll
如果你无法去掉注释,那么请使用下面的代码来加载扩展库:
<?php
if(!extension_loaded(‘sockets’))
{
if(strtoupper(substr(PHP_OS, 3)) == “WIN”)
{
dl(‘php_sockets.dll’);
}
else
{
dl(‘sockets.so’);
}
}
?> 如果你不知道你的socket是否打开,那么你可以使用phpinfo()函数来确定socket是否打开。你通过查看phpinfo信息了解socket是否打开。如下图:

查看phpinfo()关于socket的信息
◆ 产生一个服务器
现在我们把第一个例子进行完善。你需要监听一个指定的socket并且处理用户的连接。 <?php
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, &#39;localhost&#39;, 1337);
socket_listen($socket);
// Accept any incoming connections to the server
$connection = socket_accept($socket);
if($connection)
{
socket_write($connection, "You have connected to the socket...\n\r");
}
?> 你应该使用你的命令提示符来运行这个例子。理由是因为这里将产生一个服务器,而不是一个Web页面。如果你尝试使用Web浏览器来运行这个脚本,那么很有可能它会超过30秒的限时。你可以使用下面的代码来设置一个无限的运行时间,但是还是建议使用命令提示符来运行。
set_time_limit(0);
在你的命令提示符中对这个脚本进行简单测试:
Php.exe example01_server.php
如果你没有在系统的环境变量中设置php解释器的路径,那么你将需要给php.exe指定详细的路径。当你运行这个服务器端的时候,你能够通过远程登陆(telnet)的方式连接到端口1337来测试这个服务器。如下图:  上面的服务器端有三个问题:1. 它不能接受多个连接。2. 它只完成唯一的一个命令。3. 你不能通过Web浏览器连接这个服务器。
这个第一个问题比较容易解决,你可以使用一个应用程序去每次都连接到服务器。但是后面的问题是你需要使用一个Web页面去连接这个服务器,这个比较困难。你可以让你的服务器接受连接,然后些数据到客户端(如果它一定要写的话),关闭连接并且等待下一个连接。
在上一个代码的基础上再改进,产生下面的代码来做你的新服务器端: <?php
// Set up our socket
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, &#39;localhost&#39;, 1337);
socket_listen($socket);
// Initialize the buffer
$buffer = "NO DATA";
while(true)
{
// Accept any connections coming in on this socket  $connection = socket_accept($socket);
printf("Socket connected\r\n");
// Check to see if there is anything in the buffer
if($buffer != "")
{
  printf("Something is in the buffer...sending data...\r\n");
  socket_write($connection, $buffer . "\r\n");
  printf("Wrote to socket\r\n");
}
else
{
  printf("No Data in the buffer\r\n");
}
// Get the input
while($data = socket_read($connection, 1024, PHP_NORMAL_READ))
{
  $buffer = $data;
  socket_write($connection, "Information Received\r\n");
  printf("Buffer: " . $buffer . "\r\n");
}
socket_close($connection);
printf("Closed the socket\r\n\r\n");
}
?> 这个服务器端要做什么呢?它初始化一个socket并且打开一个缓存收发数据。它等待连接,一旦产生一个连接,它将打印“Socket connected”在服务器端的屏幕上。这个服务器检查缓冲区,如果缓冲区里有数据,它将把数据发送到连接过来的计算机。然后它发送这个数据的接受信息,一旦它接受了信息,就把信息保存到数据里,并且让连接的计算机知道这些信息,最后关闭连接。当连接关闭后,服务器又开始处理下一次连接。(翻译的烂,附上原文)
This is what the server does. It initializes the socket and the buffer that you use to receive
and send data. Then it waits for a connection. Once a connection is created it prints
“Socket connected” to the screen the server is running on. The server then checks to see if
there is anything in the buffer; if there is, it sends the data to the connected computer.
After it sends the data it waits to receive information. Once it receives information it stores
it in the data, lets the connected computer know that it has received the information, and
then closes the connection. After the connection is closed, the server starts the whole
process again.
◆ 产生一个客户端 处理第二个问题是很容易的。你需要产生一个php页连接一个socket,发送一些数据进它的缓存并处理它。然后你又个处理后的数据在还顿,你能够发送你的数据到服务器。在另外一台客户端连接,它将处理那些数据。
To solve the second problem is very easy. You need to create a PHP page that connects to
a socket, receive any data that is in the buffer, and process it. After you have processed the
data in the buffer you can send your data to the server. When another client connects, it
will process the data you sent and the client will send more data back to the server.
下面的例子示范了使用socket: <?php
// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket,’localhost’, 1337);
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
if($buffer == “NO DATA”)
{
echo(“<p>NO DATA</p>”);
break;
}
else
{
  // Do something with the data in the buffer
  echo(“<p>Buffer Data: “ . $buffer . “</p>”);
}
}
echo(“<p>Writing to Socket</p>”);
// Write some test data to our socket
if(!socket_write($socket, “SOME DATA\r\n”))
{
echo(“<p>Write failed</p>”);
}
// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
echo(“<p>Data sent was: SOME DATA<br> Response was:” . $buffer . “</p>”);
}
echo(“<p>Done Reading from Socket</p>”);
?> 这个例子的代码演示了客户端连接到服务器。客户端读取数据。如果这是第一时间到达这个循环的首次连接,这个服务器将发送“NO DATA”返回给客户端。如果情况发生了,这个客户端在连接之上。客户端发送它的数据到服务器,数据发送给服务器,客户端等待响应。一旦接受到响应,那么它将把响应写到屏幕上。
QQ:838468959

TOP