php stdev 標準差計算範例

用這組數字20,25,21,30,26,28,23,26,30,27計算標準差

可以在這個頁面計算

https://www.easycalculation.com/statistics/standard-deviation.php

答案是 3.4383458555

用 LibreOffice 計算也是這個答案

用 PHP PECL 計算的方式如下

$a = array();
array_push($a, 20);                                                                                                                                                                                          
array_push($a, 25);
array_push($a, 21);
array_push($a, 30);
array_push($a, 26);
array_push($a, 28);
array_push($a, 23);
array_push($a, 26);
array_push($a, 30);
array_push($a, 27);
echo stats_standard_deviation($a, true);

PHP 預設是沒有安裝這個 function 的,必須透過下面這個方式安裝

sudo apt-get install php-pear php5-dev
sudo pecl install stats
sudo echo "extension=stats.so" >> /etc/php5/cli/php.ini

如果 PHP 版本太高,無法安裝 PECL stats 套件的話

$ sudo pecl install stats
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
pecl/stats requires PHP (version >= 5.3.0, version <= 5.6.99), installed version is 7.0.9-1+deb.sury.org~trusty+1
No valid packages found
install failed

下面這個網址有提供實作,貼到自己的 PHP 裡面就可以用了
http://php.net/manual/en/function.stats-standard-deviation.php#99792

ElasticSearch php spider and index page

show you the screen shot:
Screenshot from 2015-04-29 22:15:43
below demo site is on Amazon EC2 free tier, will close before 2016/4/1
http://owen-wen.twbbs.org/

and I have create a github for this simple example
https://github.com/wenchiching/elasticsearch_webspider

the php spider from here http://phpcrawl.cuab.de/
the php dom parser from here http://simplehtmldom.sourceforge.net/

https://github.com/wenchiching/elasticsearch_webspider/commit/65f628441d98471f4d37c030ad08bda31efa67e9?diff=split
this commit show how to retrieve web and index web into ElasticSeach

And when I want to index more page, I encounter a problem that a page will be indexed again, and redundant index produced.

because I didn’t specify an ID when index a page, so if I want to index a page with an ID, what ID should I use? I have no idea.

Can I use an increment integer as ID? No, it will just index the same page with another integer ID

Head first elasticsearch-php

read https://wenchiching.wordpress.com/2015/04/02/head-first-elasticsearch/ to install ElasticSearch

follow the quick start http://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_quickstart.html

1. edit a file named composer.json and content as below

{
    "require": {
        "elasticsearch/elasticsearch": "~1.0"
    }
}

2. download php lib via below command

curl -s http://getcomposer.org/installer | php
php composer.phar install

3. edit a php file (such as: example.php) and content as below

require 'vendor/autoload.php';

$client = new Elasticsearch\Client();
$params = array();
$params['body']  = array('testField' => 'abc');
$params['index'] = 'my_index';
$params['type']  = 'my_type';
$params['id']    = 'my_id';
$ret = $client->index($params);

4. test if index success

curl -XPOST 'localhost:9200/my_index/_search?pretty' -d '
{
  "query": { "match": { "testField": "abc" } }
}'

you can see something like below if success

{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.30685282,
    "hits" : [ {
      "_index" : "my_index",
      "_type" : "my_type",
      "_id" : "my_id",
      "_score" : 0.30685282,
      "_source":{"testField":"abc"}
    } ]
  }
}

php 下載 youtube 的影片,並且取出 mp3 or ogg 音源

如何從 youtube 下載影片並且自動轉出 mp3 or ogg 檔案


解析出來的網址如下:


array(10) {
  [0]=>
  string(422) "url=http://o-o.preferred.ascc-tpe1.v24.lscache3.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=46&ip=140.0.0.0&signature=3CA6BBF9474841CF105653580E29EB74BB9148FC.325416BE1EBD7407467F642EEFBECCFEBCD5951D&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [1]=>
  string(421) "url=http://o-o.preferred.ascc-tpe1.v6.lscache1.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=37&ip=140.0.0.0&signature=3DD8E663008956A26A1DABFADFC0BD852D0C8CF5.CD9C6458FAB292D8144FA8284ED55479B8065734&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [2]=>
  string(422) "url=http://o-o.preferred.ascc-tpe1.v14.lscache3.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=45&ip=140.0.0.0&signature=5E6D3DBAEA96C7937278BD88FA520F7FAF287A6D.196CA2DBD1F58D5B0C63370FC0CE2097321F53A2&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [3]=>
  string(421) "url=http://o-o.preferred.ascc-tpe1.v7.lscache1.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=22&ip=140.0.0.0&signature=9521DF5BF21112B0C5AC95D4135057DE6EDF6EAD.0DBD9897B1442F30F2436D61459281F266B0E171&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [4]=>
  string(422) "url=http://o-o.preferred.ascc-tpe1.v16.lscache4.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=44&ip=140.0.0.0&signature=708BC1DE44BF36D838A7A343343D448D13070901.B6D3417B3410D1CA4AE590DFD1A2444859711B61&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [5]=>
  string(470) "url=http://o-o.preferred.ascc-tpe1.v19.lscache3.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Calgorithm%2Cburst%2Cfactor%2Ccp&fexp=912302%2C906429%2C913105&algorithm=throttle-factor&itag=35&ip=140.0.0.0&burst=40&sver=3&signature=5FBC0A0F53CA3B475D3F50404F0A9CCD30CDD972.7C8E3CA2F856B4A907608B862206CE9C6BFC9D63&source=youtube&expire=1330387565&key=yt1&ipbits=8&factor=1.25&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [6]=>
  string(421) "url=http://o-o.preferred.ascc-tpe1.v9.lscache2.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=43&ip=140.0.0.0&signature=B9811AF3C187D1C938A3B7762CB563895A7179ED.7F50E525FCF19E50EC72C7BFA42F71F08F94D9E6&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [7]=>
  string(470) "url=http://o-o.preferred.ascc-tpe1.v22.lscache7.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Calgorithm%2Cburst%2Cfactor%2Ccp&fexp=912302%2C906429%2C913105&algorithm=throttle-factor&itag=34&ip=140.0.0.0&burst=40&sver=3&signature=C73DA387F4955ACAAE339AAE67677A62B631EC73.A066F4F997AA4C6D1C90BE3FAE005EF2DE18A753&source=youtube&expire=1330387565&key=yt1&ipbits=8&factor=1.25&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [8]=>
  string(421) "url=http://o-o.preferred.ascc-tpe1.v9.lscache7.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Cratebypass%2Ccp&fexp=912302%2C906429%2C913105&itag=18&ip=140.0.0.0&signature=4C1A34563C1B2A42B1C023A2C620C070AC7DEAB7.0CF6081EA6930AA4EC68FD025F6F98B00F902A11&sver=3&ratebypass=yes&source=youtube&expire=1330387565&key=yt1&ipbits=8&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
  [9]=>
  string(469) "url=http://o-o.preferred.ascc-tpe1.v12.lscache5.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Csource%2Calgorithm%2Cburst%2Cfactor%2Ccp&fexp=912302%2C906429%2C913105&algorithm=throttle-factor&itag=5&ip=140.0.0.0&burst=40&sver=3&signature=D4AB3700B913D6FA884D91AB5A27B7C219DE9912.CF9CB67707CAD08979DF1CFBED4724BC39C78E92&source=youtube&expire=1330387565&key=yt1&ipbits=8&factor=1.25&cp=U0hSRVNTVV9LT0NOMl9LTVlGOmhZR1cwOUZseVVa&id=e7bceb9ff3396c4f"
}

裡面有 ip 這個參數,基本上我試了一下,在 A 這個電腦產生的網址真的沒有辦法在 B 電腦下載(兩邊 IP 不同)

產生出來的連結裡面有個 expire 參數,帶的是 unix time 時間

網址後面帶有 itag 這個參數,這個數值可以提供影片的格式和畫素資訊,請直接看 wiki 的整理:
http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs

$ ffmpeg -i input_name -y -vn -f ogg output_name
$ ./youtube-dl.py --extract-audio --audio-format mp3 http://www.youtube.com/watch?v=57zrn_M5bE8
-y 輸出檔名相同的話直接覆蓋
-vn 只取出音源
-f 輸出格式

另外,上面的 php 程式碼部份,可以選擇取出目前 youtube 上面的影片 webm 格式

ffmpeg 我安裝 0.10 版本才有 webm 的 vp8 格式支援(Ubuntu10.04 server LTS)

sudo apt-get install libfaac-dev libmp3lame-dev

./configuration –enable-pthreads –enable-gpl –enable-libfaac –enable-libmp3lame –enable-nonfree

http://ffmpeg.org/releases/ffmpeg-0.10.tar.gz

試跑的過程中有時候成功有時候失敗,原因不明。
而且學網很慢= =a

<?php
//產生出來的連結不一定第一次點擊就可以使用
//所以網路上的下載方式有些會要求使用者貼上 info 資訊
//目的應該就是先產生第一次點擊
//保證使用者要下載的時候該連結一定可以生效
$file_contents = file_get_contents("http://www.youtube.com/get_video_info?video_id=57zrn_M5bE8");
$file_contents = urldecode(urldecode($file_contents));//至此,產生出來的 http link 可以使用了
preg_match_all('/url=(.+?)id=w{16}/', $file_contents, $p);//$p[0]:包含id ,$p[1]:不含id
$i = 0;
//echo '

preview image

'; foreach( $p[0] as $url ){ $itag = strstr($url, 'itag='); $url = substr($url, strlen("url=")) ; $itag = strstr($itag, '&', true); $itag = strstr($itag, '='); $itag = substr($itag, strlen("=")); $info[$i]["url"] = $url; $info[$i]["itag"] = $itag; $i++; } $max = $info[0]; foreach( $info as $i ){ if( $i["itag"] > $max["itag"] ){ $max = $i; } } //echo $max["itag"]."
n"; //echo $max["url"]."
n"; switch($max["itag"]){ case "46": echo '1080p WebM'; exec('curl "http://www.youtube.com/get_video_info?video_id=57zrn_M5bE8" > /tmp/youtube.tmp'); exec('curl "'.$max["url"].'" > a.webm'); break; case "45": echo '720p WebM'; break; case "44": echo '480p WebM'; break; case "43": echo '360p WebM'; break; case "38": echo '2304p MP4'; break; case "37": echo '1080p MP4'; break; case "22": echo '720p MP4'; break; case "18": echo '360p MP4'; break; case "102": echo '720p WebM 3D'; break; case "101": echo '480p WebM 3D'; break; case "100": echo '360p WebM 3D'; break; case "84": echo '720p MP4 3D'; break; case "85": echo '520p MP4 3D'; break; case "82": echo '360p MP4 3D'; break; case "83": echo '240p MP4 3D'; break; case "35": echo '480p FLV'; break; case "34": echo '360p FLV'; break; case "6": echo '270p FLV'; break; case "5": echo '224p FVL'; break; case "17": echo '3GP'; break; case "13": echo '3GP'; break; default: echo "未知的格式n"; break; } ?>

change php exec shell to bash

當我們用 php 的 exec 指令,想要叫電腦執行某些指令或者 shell script 時候

可能會遇到問題

因為 exce 使用 /bin/sh 作為執行的環境,而 linux 有可能使用 /bin/sh -> /bin/dash 當作 /bin/sh 來使用

而 dash 沒有 source 這種 shell command,bash 才有。

這是第一個問題

第二個問題:當我rm /bin/sh;sudo ln -s /bin/bash /bin/sh

看起來應該可以讓我的 php 的 exec() 使用 bash 作為執行環境了

但是為什麼動作的結果和我自己在登入電腦之後在 bash 環境下執行的結果不一樣?

例如 source .bashrc ,顯示 file not found

在 sh 的情況下是因為在 PATH 裡面搜尋不到檔案的話, sh 不會到當前目錄再進行搜尋

但是 bash 在 PATH 裡面搜尋不到檔案的話, bash 是會到當前目錄進行搜尋的

BUT,當我把 /bin/sh -> /bin/bash 之後,用 exec 呼叫,他似乎不是這樣運作…what the fuxx …

解法:

exec("/bin/bash -c"source .bashrc" ");

這樣,我解決了我的問題。但我依然不知道 exec 執行的時候用 bash 跟我帳號登入機器執行 bash 為什麼會不一樣!

php 傳遞 complextype 參數給 web service ,使用 nusoap lib

下面是我貼在 stackoverflow.com 發問的問題,後來我自己解掉了。

http://stackoverflow.com/questions/8737234/how-php-nusoap-client-transfer-complextype-to-net-soap-server

不想翻譯了…

總之,如果你有「使用 php 傳送 ComplexType 型態的參數到 web service 的需求」的話,那就花個半小時看一下這篇吧

I am trying to create a client soap call using php nusoap to an existing SOAP server build on .NET that contains complexTypes.

I want to call QueryTestCategory(see belows)

And it has param searchTag and Call_Result that are string

But param LGI is type of LoginInfo(struct LoginInfo { string User_Name; string Password; })

So,how do I setup the parameters for QueryTestCategory?

I perform a getTypes I receive the following

struct HelloWorld { }
struct HelloWorldResponse { string HelloWorldResult; }
struct QueryTestSuite { LoginInfo LGI; string searchTag; string Call_Result; }
struct LoginInfo { string User_Name; string Password; }
struct QueryTestSuiteResponse { ArrayOfSuiteInfo QueryTestSuiteResult; string Call_Result; }
struct ArrayOfSuiteInfo { SuiteInfo SuiteInfo; }
struct SuiteInfo { string Test_Suite_ID; string Test_Suite_Name; string Tag; string Owner; string Remark; }
struct QueryTestCategory { LoginInfo LGI; string searchTag; string Call_Result; }
struct QueryTestCategoryResponse { ArrayOfCategoryInfo QueryTestCategoryResult; string Call_Result; }
struct ArrayOfCategoryInfo { CategoryInfo CategoryInfo; }
struct CategoryInfo { string Test_Category_ID; string Test_Category_Name; string Tag; string Owner; string Remark; }
struct QueryTestCase { LoginInfo LGI; string searchTag; string Call_Result; }
struct QueryTestCaseResponse { ArrayOfTestCaseInfo QueryTestCaseResult; string Call_Result; }
struct ArrayOfTestCaseInfo { TestCaseInfo TestCaseInfo; }
struct TestCaseInfo { string Test_Case_ID; string Test_Case_Name; string Test_Case_Version; string Tag; string Entry_Point; string Test_Kit_Name; string Test_Kit_Version; string Extra_Parameter; string Estimate_Time; string Function_Team; string Remark; string Test_Log_Parser_Name; string Test_Log_Parser_Version; string Test_Log_Parser_Entry_Point; string Test_Log_Parser_Extra_Parameter; string Owner; }
struct QueryTestResult { LoginInfo LGI; string TaskID; string Call_Result; }
struct QueryTestResultResponse { string QueryTestResultResult; string Call_Result; }

I try this, but it fails

/*
 *  $Id: wsdlclient1.php,v 1.3 2007/11/06 14:48:48 snichol Exp $
 *
 *  WSDL client sample.
 *
 *  Service: WSDL
 *  Payload: document/literal
 *  Transport: http
 *  Authentication: none
 */
require_once('lib/nusoap.php');
$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
$client = new nusoap_client('http://www.example.com/Query.asmx?WSDL', 'wsdl',
                        $proxyhost, $proxyport, $proxyusername, $proxypassword);
$err = $client->getError();
if ($err) {
    echo "Constructor error";
}
// Doc/lit parameters get wrapped
$param = array('User_Name' => 'SSD_WS_01', 'Password' => 'SSD_WS_01', 'searchTag' => 'test', 'Call_Result' => '');
$result = $client->call('QueryTestCategory', array('parameter' => $param), '', '', false, true);
// Check for a fault
if ($client->fault) {

    print_r($result);

} else {
    // Check for errors
    $err = $client->getError();
    if ($err) {
        // Display the error
        echo 'Error;
    } else {
        // Display the result
        echo 'Result';
        print_r($result);

    }
}

I found ANSWER!
After reading this web page and many many other information

http://gznofeng.iteye.com/blog/951762

My finally code is like below

To sum up…

create $param1 = new stdClass,set parameter via $param1->varName = ‘something’

That all!

 23 // Doc/lit parameters get wrapped
 24 //$param1 = array('User_Name' => 'SSD_WS_01', 'Password' => 'SSD_WS_01');
 25 $param1 = new stdClass();
 26 $param1->User_Name = 'SSD_WS_01';
 27 $param1->Password = 'SSD_WS_01';
 28
 29 $result = $client->call('QueryTestCategory', array('LGI' => $param1, 'searchTag' => '' ), '', '', false, true);
 30 // Check for a fault
 31 if ($client->fault) {
 32     echo '

Fault

'; 33 print_r($result); 34 35 } else { 36 // Check for errors 37 $err = $client->getError(); 38 if ($err) { 39 // Display the error 40 echo '

Error

' . $err; 41 } else { 42 // Display the result 43 echo '

WoW,Result

'; 44 print_r($result); 45 46 } 47 }

補充傳遞 array 的方法,看起來似乎 nusoap 本身沒有支援 arrayType

所以要自己額外把下面這段代碼加入才能支援 arrayType

$server->wsdl->addComplexType("ArrayOfString",
                 "complexType",
                 "array",
                 "",
                 "SOAP-ENC:Array",
                 array(),
                 array(array("ref"=>"SOAP-ENC:arrayType","wsdl:arrayType"=>"xsd:string[]")),
                 "xsd:string");

REF: http://www.linuxquestions.org/questions/programming-9/php-soap-server-returns-array-using-nusoap-library-600470/

然後就可以用下面這樣的陣列了

array("return" => "tns:ArrayOfString"),

網路機器人(網路蜘蛛),使用 LIB_http.php

透過 HTMLtidy 和 php-Curl 寫成的 LIB_http.php 等函式的函式庫可以協助我們下載網頁到我們的電腦

並且將網頁檔案拉下來到我們電腦的資料作進一步的分析!

把這件事情加強加強再加強,就是 google 做的事情了!(加強:使你的網路機器人無論遇到多麼爛的網頁原始碼都能夠解讀其中關鍵資料)

LIB_http.php 函式可以在這個頁面下載到

http://www.schrenk.com/nostarch/webbots/DSP_download.php

經過實際使用,發現了一個可以加強的地方!

有些網頁的 a 超連結的 href 屬性寫成

href 後面使用單引號而非正規的雙引號,雖然這樣大部分的瀏覽器都可以解讀,但是 LIB_http 函式庫裡面的 LIB_parse.php 的 get_attribute 函式就無法正確讀出屬性了

所以我將 LIB_parse.php 做了修改:如果使用雙引號解讀出來的屬性是空字串,則嘗試使用單引號來解讀。

原本程式碼:

function get_attribute($tag, $attribute)
    {
    # Use Tidy library to 'clean' input
    $cleaned_html = tidy_html($tag);

    # Remove all line feeds from the string
    $cleaned_html = str_replace("r", "", $cleaned_html);
    $cleaned_html = str_replace("n", "", $cleaned_html);

    # Use return_between() to find the properly quoted value for the attribute
    return return_between($cleaned_html, strtoupper($attribute)."="", """, EXCL);
    }

修改後的程式碼:

function get_attribute($tag, $attribute)
    {
    # Use Tidy library to 'clean' input
    $cleaned_html = tidy_html($tag);

    # Remove all line feeds from the string
    $cleaned_html = str_replace("r", "", $cleaned_html);
    $cleaned_html = str_replace("n", "", $cleaned_html);

    # Use return_between() to find the properly quoted value for the attribute
    if( return_between($cleaned_html, strtoupper($attribute)."="", """, EXCL) == "" ){
        return return_between($cleaned_html, strtoupper($attribute)."='", "'", EXCL);
    }
    else{
        return return_between($cleaned_html, strtoupper($attribute)."="", """, EXCL);
    }
    }

針對判斷解讀出來的字串是否為空白字串的部份應該有更好的解法,不過那的重要性其次了…

php,播放資料夾裡面的音樂-2

懶的說明了。因為部落格資料庫有設定自動備份,就當作我把程式碼備份上來好了!

<?php
setlocale(LC_ALL, 'zh_TW.UTF8');
$path = $_GET['path'];
if( $path == NULL){
    $path = ".";
}
if( @ereg("..", $path) ){
    $path= ".";
}
SETCOOKIE("path", $path);
echo "n";
echo "path is $path
n"; // e.g. url:"page.php?upload=true" as handler property if(isset($_GET['upload']) && $_GET['upload'] === 'true'){ $headers = getallheaders(); if( // basic checks isset( $headers['Content-Type'], $headers['Content-Length'], $headers['X-File-Size'], $headers['X-File-Name'] ) && $headers['Content-Type'] === 'multipart/form-data' && $headers['Content-Length'] === $headers['X-File-Size'] ){ // create the object and assign property $file = new stdClass; $file->name = basename($headers['X-File-Name']); $file->size = $headers['X-File-Size']; $file->content = file_get_contents("php://input"); // if everything is ok, save the file somewhere if(file_put_contents($_COOKIE['path'].'/'.str_replace(""", "", $file->name), $file->content)) exit('OK.請重新載入頁面!'); } // if there is an error this will be the output instead of "OK" exit('Error'); } ?> 電音大帝國 Alpha /** basic Safari 4 multiple upload example * @author Andrea Giammarchi * @blog WebReflection [webreflection.blogspot.com] */ onload = function(){ function size(bytes){ // simple function to show a friendly size var i = 0; while(1023 < bytes){ bytes /= 1024; ++i; }; return i ? bytes.toFixed(2) + ["", " Kb", " Mb", " Gb", " Tb"][i] : bytes + " bytes"; }; // create elements var input = document.body.appendChild(document.createElement("input")), bar = document.body.appendChild(document.createElement("div")).appendChild(document.createElement("span")), div = document.body.appendChild(document.createElement("div")); // set input type as file input.setAttribute("type", "file"); // enable multiple selection (note: it does not work with direct input.multiple = true assignment) input.setAttribute("multiple", "true"); // auto upload on files change input.addEventListener("change", function(){ // disable the input input.setAttribute("disabled", "true"); sendMultipleFiles({ // list of files to upload files:input.files, // clear the container onloadstart:function(){ div.innerHTML = "Init upload ... "; bar.style.width = "0px"; }, // do something during upload ... onprogress:function(rpe){ div.innerHTML = [ "上傳檔案佇列: " + this.file.fileName, "目前檔案進度: " + size(rpe.loaded) + " of " + size(rpe.total), "總共檔案進度: " + size(this.sent + rpe.loaded) + " of " + size(this.total) ].join("
"); bar.style.width = (((this.sent + rpe.loaded) * 200 / this.total) >> 0) + "px"; }, // fired when last file has been uploaded onload:function(rpe, xhr){ div.innerHTML += ["", "Server Response: " + xhr.responseText ].join("
"); bar.style.width = "200px"; // enable the input again input.removeAttribute("disabled"); }, // if something is wrong ... (from native instance or because of size) onerror:function(){ div.innerHTML = "The file " + this.file.fileName + " is too big [" + size(this.file.fileSize) + "]"; // enable the input again input.removeAttribute("disabled"); } }); }, false); bar.parentNode.id = "progress"; }; function mkdir(){ var dirName = prompt("輸入資料夾名稱", "新資料夾"); var path = document.getElementById('path').innerHTML; window.location.replace("mkdir.php?path="+path+"&dirName="+dirName); } <?php if( @!chdir("$path") ){ echo "error when chdir to $path
n"; $path= "."; } exec("ls", $file); $end = strrpos($path, "/"); $upper_path = substr($path, 0, $end); echo "上一層n"; echo " | "; //echo "新增資料夾n"; echo "新增資料夾"; echo "
"; foreach( $file as $per_file ){ $string = filetype("$per_file"); if( $string == "file" && @ereg(".mp3",$per_file) ){ echo "$per_file"; echo " "; echo "移除
n"; } elseif( $string == "file" && @ereg(".MP3",$per_file) ){ echo "$per_file"; echo " "; echo "移除
n"; } elseif( $string == "file" && @ereg(".Mp3",$per_file) ){ echo "$per_file"; echo " "; echo "移除
n"; } elseif($string == "dir"){ echo "$per_filen"; echo "移除
n"; } } ?> 上傳檔案:



var r = confirm("這個資料夾內有檔案,你真要的刪掉?");
if( r == true ){
    window.location.replace(this.location+"&f=yes");
}else{
    window.location.replace(this.location+"&f=no");
}
//window.location.replace(this.location+"&back=1");

/** Basic upload manager for single or multiple files (Safari 4 Compatible)
 * @author  Andrea Giammarchi
 * @blog    WebReflection [webreflection.blogspot.com]
 * @license Mit Style License
 */

var sendFile = 10240000; // maximum allowed file size
                        // should be smaller or equal to the size accepted in the server for each file

// function to upload a single file via handler
sendFile = (function(toString, maxSize){
    var isFunction = function(Function){return  toString.call(Function) === "[object Function]";},
        split = "onabort.onerror.onloadstart.onprogress".split("."),
        length = split.length;
    return  function(handler){
        if(maxSize && maxSize < handler.file.fileSize){
            if(isFunction(handler.onerror))
                handler.onerror();
            return;
        };
        var xhr = new XMLHttpRequest,
            upload = xhr.upload;
        for(var
            xhr = new XMLHttpRequest,
            upload = xhr.upload,
            i = 0;
            i < length;
            i++
        )
            upload[split[i]] = (function(event){
                return  function(rpe){
                    if(isFunction(handler[event]))
                        handler[event].call(handler, rpe, xhr);
                };
            })(split[i]);
        upload.onload = function(rpe){
            if(handler.onreadystatechange === false){
                if(isFunction(handler.onload))
                    handler.onload(rpe, xhr);
            } else {
                setTimeout(function(){
                    if(xhr.readyState === 4){
                        if(isFunction(handler.onload))
                            handler.onload(rpe, xhr);
                    } else
                        setTimeout(arguments.callee, 15);
                }, 15);
            }
        };
        xhr.open("post", handler.url || "?upload=true", true);
        xhr.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
        xhr.setRequestHeader("Cache-Control", "no-cache");
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", handler.file.fileName);
        xhr.setRequestHeader("X-File-Size", handler.file.fileSize);
        xhr.setRequestHeader("Content-Type", "multipart/form-data");
        xhr.send(handler.file);
        return  handler;
    };
})(Object.prototype.toString, sendFile);

// function to upload multiple files via handler
function sendMultipleFiles(handler){
    var length = handler.files.length,
        i = 0,
        onload = handler.onload;
    handler.current = 0;
    handler.total = 0;
    handler.sent = 0;
    while(handler.current < length)
        handler.total += handler.files[handler.current++].fileSize;
    handler.current = 0;
    if(length){
        handler.file = handler.files[handler.current];
        sendFile(handler).onload = function(rpe, xhr){
            if(++handler.current < length){
                handler.sent += handler.files[handler.current - 1].fileSize;
                handler.file = handler.files[handler.current];
                sendFile(handler).onload = arguments.callee;
            } else if(onload) {
                handler.onload = onload;
                handler.onload(rpe, xhr);
            }
        };
    };
    return  handler;
};

/** basic server side example
 * @language    PHP
name = basename($headers['X-File-Name']);
        $file->size = $headers['X-File-Size'];
        $file->content = file_get_contents("php://input");

        // if everything is ok, save the file somewhere
        if(file_put_contents('files/'.$file->name, $file->content))
            exit('OK');
    }

    // if there is an error this will be the output instead of "OK"
    exit('Error');
}
?>
 */

使用 XMLHttpRequest 上傳檔案

參考自 webreflection.blogspot.com

http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html

name = basename($headers['X-File-Name']);
        $file->size = $headers['X-File-Size'];
        $file->content = file_get_contents("php://input");

        // if everything is ok, save the file somewhere
        if(file_put_contents($_COOKIE['path'].'/'.$file->name, $file->content))
        exit('OK.請重新載入頁面!');
    }

    // if there is an error this will be the output instead of "OK"
    exit('Error');
}
?>



電音大帝國 Alpha
        
        

        /** basic Safari 4 multiple upload example
         * @author  Andrea Giammarchi
         * @blog    WebReflection [webreflection.blogspot.com]
         */
        onload = function(){

            function size(bytes){   // simple function to show a friendly size
                var i = 0;
                while(1023 < bytes){
                    bytes /= 1024;
                    ++i;
                };
                return  i ? bytes.toFixed(2) + ["", " Kb", " Mb", " Gb", " Tb"][i] : bytes + " bytes";
            };

            // create elements
            var input = document.body.appendChild(document.createElement("input")),
                bar = document.body.appendChild(document.createElement("div")).appendChild(document.createElement("span")),
                div = document.body.appendChild(document.createElement("div"));

            // set input type as file
            input.setAttribute("type", "file");

            // enable multiple selection (note: it does not work with direct input.multiple = true assignment)
            input.setAttribute("multiple", "true");

            // auto upload on files change
            input.addEventListener("change", function(){

                // disable the input
                input.setAttribute("disabled", "true");

                sendMultipleFiles({

                    // list of files to upload
                    files:input.files,

                    // clear the container
                    onloadstart:function(){
                        div.innerHTML = "Init upload ... ";
                        bar.style.width = "0px";
                    },

                    // do something during upload ...
                    onprogress:function(rpe){
                        div.innerHTML = [
                            "上傳檔案佇列: " + this.file.fileName,
                            "目前檔案進度: " + size(rpe.loaded) + " of " + size(rpe.total),
                            "總共檔案進度: " + size(this.sent + rpe.loaded) + " of " + size(this.total)
                        ].join("
"); bar.style.width = (((this.sent + rpe.loaded) * 200 / this.total) >> 0) + "px"; }, // fired when last file has been uploaded onload:function(rpe, xhr){ div.innerHTML += ["", "Server Response: " + xhr.responseText ].join("
"); bar.style.width = "200px"; // enable the input again input.removeAttribute("disabled"); }, // if something is wrong ... (from native instance or because of size) onerror:function(){ div.innerHTML = "The file " + this.file.fileName + " is too big [" + size(this.file.fileSize) + "]"; // enable the input again input.removeAttribute("disabled"); } }); }, false); bar.parentNode.id = "progress"; }; <?php echo "
n"; echo "path is $path
n"; if( @!chdir("$path") ){ echo "error when chdir to $path
n"; $path= "."; } exec("ls", $file); $end = strrpos($path, "/"); $upper_path = substr($path, 0, $end); echo "上一層
n"; foreach( $file as $per_file ){ $string = filetype("$per_file"); if( $string == "file" && @ereg(".mp3",$per_file) ){ echo "$per_file
n"; } elseif( $string == "file" && @ereg(".MP3",$per_file) ){ echo "$per_file
n"; } elseif( $string == "file" && @ereg(".Mp3",$per_file) ){ echo "$per_file
n"; } elseif($string == "dir"){ echo "$per_file
n"; } } ?>
/** Basic upload manager for single or multiple files (Safari 4 Compatible)
 * @author  Andrea Giammarchi
 * @blog    WebReflection [webreflection.blogspot.com]
 * @license Mit Style License
 */

var sendFile = 10240000; // maximum allowed file size
                        // should be smaller or equal to the size accepted in the server for each file

// function to upload a single file via handler
sendFile = (function(toString, maxSize){
    var isFunction = function(Function){return  toString.call(Function) === "[object Function]";},
        split = "onabort.onerror.onloadstart.onprogress".split("."),
        length = split.length;
    return  function(handler){
        if(maxSize && maxSize < handler.file.fileSize){
            if(isFunction(handler.onerror))
                handler.onerror();
            return;
        };
        var xhr = new XMLHttpRequest,
            upload = xhr.upload;
        for(var
            xhr = new XMLHttpRequest,
            upload = xhr.upload,
            i = 0;
            i < length;
            i++
        )
            upload[split[i]] = (function(event){
                return  function(rpe){
                    if(isFunction(handler[event]))
                        handler[event].call(handler, rpe, xhr);
                };
            })(split[i]);
        upload.onload = function(rpe){
            if(handler.onreadystatechange === false){
                if(isFunction(handler.onload))
                    handler.onload(rpe, xhr);
            } else {
                setTimeout(function(){
                    if(xhr.readyState === 4){
                        if(isFunction(handler.onload))
                            handler.onload(rpe, xhr);
                    } else
                        setTimeout(arguments.callee, 15);
                }, 15);
            }
        };
        xhr.open("post", handler.url || "?upload=true", true);
        xhr.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
        xhr.setRequestHeader("Cache-Control", "no-cache");
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", handler.file.fileName);
        xhr.setRequestHeader("X-File-Size", handler.file.fileSize);
        xhr.setRequestHeader("Content-Type", "multipart/form-data");
        xhr.send(handler.file);
        return  handler;
    };
})(Object.prototype.toString, sendFile);

// function to upload multiple files via handler
function sendMultipleFiles(handler){
    var length = handler.files.length,
        i = 0,
        onload = handler.onload;
    handler.current = 0;
    handler.total = 0;
    handler.sent = 0;
    while(handler.current < length)
        handler.total += handler.files[handler.current++].fileSize;
    handler.current = 0;
    if(length){
        handler.file = handler.files[handler.current];
        sendFile(handler).onload = function(rpe, xhr){
            if(++handler.current < length){
                handler.sent += handler.files[handler.current - 1].fileSize;
                handler.file = handler.files[handler.current];
                sendFile(handler).onload = arguments.callee;
            } else if(onload) {
                handler.onload = onload;
                handler.onload(rpe, xhr);
            }
        };
    };
    return  handler;
};