分类 ‘PHP’ 的归档

PHP 开发工具

五月 18, 2009

编程工具

phpdesigner, Komodo IDE, PhpEdit, Netbeans, Eclipse PDT, ZendStudio,Emacs、KVIM、Arachnophilia、Bluefish、NEdit、Gedit、Kate、Quanta Plus

调试工具

zend debugger, xdebugger

Profiling 工具

Kcachegrind

ubuntu中安装PHP,Apache,MySQL

五月 18, 2009

1、安装Apache服务
sudo apt-get install apache2

然后按照提示即完成apahce的安装了。这里 可以打开http://127.0.0.1,即可看于是It works

首先我直接用apt-get安装了apache2,php5,pear以及mysql5, 为了方便后续的安装,还加上了make和libmysqlclient

sudo apt-get install apache2-mpm-prefork
sudo apt-get install php5 ,php-xml-parser php-fpdf php-image-graph

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl php5-xmlrpc

sudo apt-get install php-soap

sudo apt-get install php5-dev
sudo apt-get install php5-pear
sudo apt-get install mysql-server-5.0
sudo apt-get install make
sudo apt-get install libmysqlclient15-dev
pdo在ubuntu的apt里头似乎还找不到安装源,所以通过pecl来安装这个扩展,非常简单 —- 如果海底光纤能连通的话:

pecl install pdo

增加一行:

extension=pdo.so

到文件:

/etc/php/apache2/php.ini
/etc/php/cli/php.ini

接下来安装pdo_mysql碰到一些问题, 直接跑pecl install pecl_mysql会出现一些错误,搜索了一下发现是pecl本身的问题,下面是个比较简单的解决办法:

wgethttp://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
tar xzvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2

注释掉configure里头判断是否已经安装pdo扩展的代码片段,继续跑:

phpize
./configure
make
make install

然后再次添加下面一行到前面提到的两个php.ini

extension=pdo_mysql.so

重启apache之后, php5 + pdo_mysql就在ubuntu上安装好了, documentroot是/var/www

后记
更简单的解决办法是运行:

PHP_PDO_SHARED=1 pecl install pdo_mysql

2、安装php5
sudo apt-get install php5 php5-gd php-pear

#apt-get install curl php5-url php5-mcrypt
sudo apt-get install libapache2-mod-php5

sudo /etc/init.d/apache2 restart

OK之后,我们来查看一下是否生效了。
gksudo gedit /var/www/testphp.php

入探针
保存运行
http://127.0.0.1/testphp.php

3、安装mysql
sudo apt-get install mysql-server

安装完成按提示设置root密

4、让apache、php支持mysql
sudo apt-get install libapache2-mod-auth-mysql
sudo apt-get install php5-mysqlsudo /etc/init.d/apache2 restart

至此apache2+php 5.2.4.2+mysql5.0.51的环境就完成了。

1.Ubuntu 8.04下安装LAMP
系统->系统管理->新立得软件包管理器, 打开新立得,编辑 –> 使用任务分组标记软件包 –> 勾选 LAMP Server。

安装过程中会提示设置mysql的root用户的密码。

配置文件在/etc/apache2目录

在/etc/apache2/httpd.conf加入一行:ServerName 127.0.0.1

2.Ubuntu 8.04下安装phpmyadmin
sudo apt-get install phpmyadmin

安装后在/etc/apache2/conf.d目录自动创建虚拟目录配置文件phpmyadmin.conf

安装后直接输入http://localhost/phpmyadmin登录,创建一个wpmu数据库

3.启动mod_rewrite模块
sudo a2enmod rewrite

4.Ubuntu 8.04下安装WPMU
(1)从官方主页下载WPMU,解压到~/blog目录(/home//blog)

(2)修改目录属性:chmod 755 /home//blog /home//blog/wp-content

(3)配置WPMU虚拟目录。修改/etc/apache2/httpd.conf或者在/etc/apache2/conf.d创建wpmu.conf文件,加入如下内容:

Alias /blog /home//blog
/blog>
Options Indexes FollowSymLinks
DirectoryIndex index.php
AllowOverride FileInfo Options
(4)修改/etc/hosts文件(因为wpmu必须采用域名格式)

修改127.0.0.1 localhost
127.0.0.1 www.my.com my.com localhost

(5)在firefox输入:http://my.com/blog。安装WPMU

OK。
(UMELINK原创)

Ubuntu php 环境简单配置备忘(二/成功)

一、安装apache2+php5+mysql
sudo apt-get install apache2 php5-mysql libapache2-mod-php5 mysql-server
二、设置mysql密码
mysqladmin -u root password 新密码

三、安装phpmyadmin
sudo apt-get install phpmyadmin
测试:http://localhost/phpmyadmin/

Installation in ubuntu 8.04 phpmyadmin

1)apt-get install phpmyadmin

2)sudo gedit /etc/apache2/apache2.conf

3)Add the following line of code inside apache2.conf:
Include /etc/phpmyadmin/apache.conf

4)Now restart Apache:
sudo /etc/init.d/apache2 restart

四、其它操作:
编辑测试页:()
sudo gedit /var/www/testphp.php

启动Apache
$ sudo /usr/sbin/apache2ctl start
停止Apache
$ sudo /usr/sbin/apache2ctl stop
重启Apache
$ sudo /etc/init.d/apache2 restart

如果只是用于本地开发,加强安全性,设置如下:
$ gksudo “gedit /etc/apache2/ports.conf”
$ password:
更改ports.conf
Listen 127.0.0.1:80
保存文件之后,并重启apache。这时,只有通过127.0.0.1才能访问Apache。

安装包

/etc/apt/sources.list file.

deb http://packages.dotdeb.org stable all
deb-src http://packages.dotdeb.org stable all
# apt-get update

install MySQL4

# apt-get install mysql-server-4.1 mysql-client-4.1 libmysqlclient14-dev

install MySQL5

# apt-get install mysql-server-5.0 mysql-client-5.0 libmysqlclient15-dev

Set a root MySQL password like this:

# mysqladmin -u root password yourrootsqlpassword

Debian provides a fastcgi enabled version of PHP.

# apt-get install php4-cgi
# apt-get install php5-cgi

Other php5 package

php5-curl php5-gd php5-imap php5-mhash, php5-xdebug
php5-pear php5-dev php5-ming php5-common
php5-cli php5-pspell php5-odbc php5-mcrypt
php5-tidy php5-ldap php5-gmp php5-snmp
php5-sybase php5-mysql php5-mysqli php5-pgsql
# apt-get install php5-cgi libgdmg1 php5-curl php5-gd

php.ini

Add cgi.fix_pathinfo = 1

Php Xdebug extension

五月 15, 2009

The Xdebug extension helps you debugging your script by providing a lot of valuable debug information. The debug information that Xdebug can provide includes the following:

  • stack traces and function traces in error messages with:
    • full parameter display for user defined functions
    • function name, file name and line indications
    • support for member functions
  • memory allocation
  • protection for infinite recursions

Xdebug also provides:

PECL Installation

As of Xdebug 0.9.0 you can install Xdebug through PEAR/PECL. This only works with with PEAR version 0.9.1-dev or higher and some UNIX.

Installing with PEAR/PECL is as easy as:

# pecl install xdebug

but you still need to add the correct line to your php.ini: (don’t forget to change the path and filename to the correct one — but make sure you use the full path)

zend_extension="/usr/local/php/modules/xdebug.so"Xdebug is incompatible with the Zend Optimizer and Zend Studio   Debugger extensions. If these extensions are enabled in   php.ini, they will not be imported into the copy created   by Komodo for debugging. When configuring Remote PHP Debugging, these extensions   should be manually commented out in php.ini.

Ubuntu ZendOptimizer安装

五月 6, 2009

ZendChina官方:Zend Optimizer 是一个免费软件,它的主要功能是加速PHP脚本文件的运行。用Zend Encode编译好的二进制代码可以被Zend Optimizer透明读取,客户只要在他的服务器上安装Zend Optimizer就可以执行由Zend Encode编译好的PHP程序。编译程序中包含有Zend Optimizer的部分代码,所以编译过程中对程序代码进一步作了优化处理,这即意味着脚本的执行效率提高了。

一般情况下,执行使用Zend Optimizer的PHP程序比不使用的要快40%到100%。并且降低了程序对系统资源的耗用。这意味着网站的访问者可以更快的浏览网页,从而完成更 多的事务,创造更好的客户满意度。更快的反应同时也意味着可以节省硬件投资,并增强网站所提供的服务。

访问 http://www.zend.com/store/products/zend-optimizer.php 下载 Zend Optimizer 的最新版本。下面我来详细介绍一下Zend Optimizer在各种系统下的安装方式:

[WINDOWS下]

  • 保证PHP已经调试通过。
  • 复制ZendOptimizer.dll文件到你的机器,通常放在:C:\Program Files\Zend\lib下
  • 在php.ini文件中加入如下两行,不要包含任何空格:
    zend_optimizer.optimization_level=7
    zend_extension_ts=”C:\Program Files\Zend\lib\ZendOptimizer.dll”
  • 如果需要的话,重新启动WEB服务器

[LINUX下]

  • 在编译php4时加上下列参数
    –disable-debug (这个参数在现在的php版本应该是缺省的)
  • 解压缩你下载的文件包,
    tar zxvf <package name>
    并把 ZendOptimizer.so 文件拷贝到
    /usr/local/Zend/lib
  • 把下列行加入php.ini,不要加入任何空格和tab符
    zend_optimizer.optimization_level=15
    zend_extension=”/usr/local/Zend/lib/ZendOptimizer.so”
  • 如果你运行apache,重新启动它
    /apachebindir/apachectl stop
    /apachebindir/apachectl start

检查安装是否成功
写一个脚本并运行它
<?php
phpinfo();
?>
如果你能在输出的Zend部分找到象下面的输出,那就是成功了。
This program makes use of the Zend scripting language engine:
Zend Engine v1.0.4, Copyright (c) 1998-2000 Zend Technologies
with Zend Optimizer v1.0.0, Copyright (c) 1998-2000, by Zend Technologies

当用惯了Fedora,重新返回到Ubuntu就会有些许“不适”,比如httpd。 Fedora下,启动http服务是在/etc/rc.d/init.d/httpd start,而到了Ubuntu下却不见了踪影。好吧,它不在那里!在Ubuntu的世界里,它改头换面,重新做“人”了,于是我在/etc/init.d/下找到了改名换姓的apache2。 更奇怪的是httpd在Ubuntu下的大本营,/etc/apache2/下的httpd.conf竟然是空的,啥没有。好家伙,把我看得一愣一愣的。不过有了前次的经验,再不上当了,因为这里还有个.conf文件:apache2.conf。至于为啥Ubuntu为何如此对待httpd,据说是因为Debian认为httpd.conf一般都很臃肿,所以便以身作则,率先将配置文件给distribute到其他文件中。而且挺彻底,在httpd.conf中一字不留,害得我找服务器的用户组和用户找了半天。而且,别想在配置文件中找到环境参数了,因为它们都在/etc/apache2/下的envvars文件里,比如服务器的用户组和用户:www-data。

Easy way to create XLS file from PHP

十一月 27, 2008

Everybody knows phpMyAdmin can export file to Excel format but phpMyAdmin just export .csv file,not real Excel file format. If you are interest in PHP programming and need to export to the real Excel format please check it out !

Example PHP export to XLS file format.

1. Create Function for XLS

function xlsBOF() {
echo
pack(“ssssss”, 0×809, 0×8, 0×0, 0×10, 0×0, 0×0);
return;
}

function xlsEOF() {
echo
pack(“ss”, 0×0A, 0×00);
return;
}

function xlsWriteNumber($Row, $Col, $Value) {
echo
pack(“sssss”, 0×203, 14, $Row, $Col, 0×0);
echo
pack(“d”, $Value);
return;
}

function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo
pack(“ssssss”, 0×204, 8 + $L, $Row, $Col, 0×0, $L);
echo
$Value;
return;
}

2. Send Header to Browser in download format.

// Query Database
$result=mysql_db_query($dbname,“select id,prename,name,sname,grade from appdata where course=’$courseid’ and sec=’$section’”)

// Send Header
header(“Pragma: public”);
header(“Expires: 0″);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0″);
header(“Content-Type: application/force-download”);
header(“Content-Type: application/octet-stream”);
header(“Content-Type: application/download”);;
header(“Content-Disposition: attachment;filename=$courseid-$sec.xls ); // แล้วนี่ก็ชื่อไฟล์
header(“Content-Transfer-Encoding: binary “);

// XLS Data Cell

xlsBOF();
xlsWriteLabel(1,0,“Student Register $semester/$year”);
xlsWriteLabel(2,0,“COURSENO : “);
xlsWriteLabel(2,1,“$courseid”);
xlsWriteLabel(3,0,“TITLE : “);
xlsWriteLabel(3,1,“$title”);
xlsWriteLabel(4,0,“SETION : “);
xlsWriteLabel(4,1,“$sec”);
xlsWriteLabel(6,0,“NO”);
xlsWriteLabel(6,1,“ID”);
xlsWriteLabel(6,2,“Gender”);
xlsWriteLabel(6,3,“Name”);
xlsWriteLabel(6,4,“Lastname”);
$xlsRow = 7;
while(list(
$id,$prename,$name,$sname,$grade)=mysql_fetch_row($result)) {
++
$i;
xlsWriteNumber($xlsRow,0,“$i”);
xlsWriteNumber($xlsRow,1,“$id”);
xlsWriteLabel($xlsRow,2,“$prename”);
xlsWriteLabel($xlsRow,3,“$name”);
xlsWriteLabel($xlsRow,4,“$sname”);
$xlsRow++;
}
xlsEOF();
exit();

PHP: Exporting Data to Excel

十一月 27, 2008

After you’ve put all that effort into importing your data into and SQL database and connecting it to your website, how do you get it back out and into Excel in order to keep your off-line and on-line systems synchronised?

The following article presents a simple method for downloading any data from PHP into an Excel spreadsheet – or at least something that looks like one.

1. Preparing the data

Using the data from the article on Sorting Arrays of Arrays which is defined as follows:

$data = array( array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25), array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18), array("firstname" => "James", "lastname" => "Brown", "age" => 31), array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7), array("firstname" => "Michael", "lastname" => "Davis", "age" => 43), array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24), array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27) );

Note: Further down this page you can find an example on creating an export from an SQL query.

The first step is to output the data in a tab-delimited format (CSV can also be used but is slightly more complicated). To achieve this we use the following code:

header("Content-Type: text/plain"); $flag = false; foreach($data as $row) { if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n"; $flag = true; } echo implode("\t", array_values($row)) . "\n"; }

We set the content type to text/plain so that the output can more easily be viewed in the browser. Otherwise, because there is no HTML formatting, the output would appear as a single line of text.

The first line of output will be the column headings (in this case the field names are used). Values are separated with a tab \t and rows with a line break \n. The output should look something like the following:

firstname lastname age Mary Johnson 25 Amanda Miller 18 James Brown 31 Patricia Williams 7 Michael Davis 43 Sarah Miller 24 Patrick Miller 27

There’s already a weakness in this code that may not be immediately obvious. What if one of the fields to be ouput already contains one or more tab characters, or worse, a newline? That’s going to throw the whole process out as we rely on those characters to indicate column- and line-breaks.

The solution is to ‘escape’ the tab characters. In this case we’re going to replace tabs with a literal \t and line breaks with a literal \n so they don’t affect the formatting:

function cleanData(&$str)

{ $str = preg_replace("/\t/", "\\t", $str);

$str = preg_replace("/\n/", "\\n", $str); }

header("Content-Type: text/plain");

$flag = false;

foreach($data as $row)

{ if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n"; $flag = true; } array_walk($row, 'cleanData'); echo implode("\t", array_values($row)) . "\n"; }

Note: This represents the simplest case. You might also want to consider different line break characters and other special characters that may need encoding.

Now, before each row is echoed any tab characters are replaced “\t” so that our columns aren’t broken up. Also any line breaks within the data are replaced with “\n”. Now, how to set this up as a download…

2. Triggering a download

What many programmers don’t realise is that you don’t have to create a file, even a temporary one, in order for one to be downloaded. It’s sufficient to ‘mimic’ a download by passing the equivalent HTTP headers followed by the data.

If we create a PHP file with the following code then when it’s called a file will be downloaded that can be opened directly using Excel.

function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\n/", "\\n", $str); } # file name for download $filename = "website_data_" . date('Ymd') . ".xls"; header("Content-Disposition: attachment; filename=\"$filename\""); header("Content-Type: application/vnd.ms-excel"); $flag = false; foreach($data as $row) { if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n"; $flag = true; } array_walk($row, 'cleanData'); echo implode("\t", array_values($row)) . "\n"; } exit;

[Click to trigger the download]

This should result in a file being downloaded and saved to your computer. If all goes well then the filename will be “website_data_20081127.xls”.

How does it work? Setting the headers tells the browser to expect a file with a given name and type. The data is then echoed, but instead of appearing on the page it becomes the downloaded file.

Because of the .xls extension and the ms-excel file type, most computers will associate it with Excel and double-clicking will cause that program to open. You could also modify the file name and mime type to indicate a different spreadsheet package or database application.

If for some reason you want to create ‘real’ Excel files, follow the link under References below.

A similar technique can be used to allow users to download files that have been uploaded previously using PHP and stored with different names. More on that later…

3. Exporting from an SQL database

If your goal is to allow data to be exported from a query result then the changes are relatively simple:

# Original PHP code by Chirp Internet: www.chirp.com.au # Please acknowledge use of this code by including this header. function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\n/", "\\n", $str); } # file name for download $filename = "website_data_" . date('Ymd') . ".xls"; header("Content-Disposition: attachment; filename=\"$filename\""); header("Content-Type: application/vnd.ms-excel"); $flag = false; $result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!'); while(false !== ($row = pg_fetch_assoc($result))) { if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n"; $flag = true; } array_walk($row, 'cleanData'); echo implode("\t", array_values($row)) . "\n"; }

The database functions need to match the database you’re using. MySQL users for example would use mysql_query and mysql_fetch_assoc in place of the PostgreSQL functions.

If you’re having trouble at this stage, remove the Content-Disposition header and change the Content-Type back to text/plain. This makes debugging a lot easier as you can see the output in your browser rather than having to download and open the generated file every time you edit the script.

4. References

关于Content-Type的一张表

十一月 27, 2008

http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html

Description of Data Content Typical Filename Extensions MIME type/subtype
Text and Text-Related Types
HTML text data (RFC 1866) html htm text/html
Plain text: documents; program listings txt c c++ pl cc h text/plain
Richtext (obsolete – replaced by text/enriched) text/richtext
Structure enhanced text (etx?) text/x-setext
Enriched text markup (RFC 1896) text/enriched
Tab-separated values (tabular) (tsv?) text/tab-separated-values
SGML documents (RFC 1874) text/sgml
Speech synthesis data (MVP Solutions) talk text/x-speech
Document Stylesheet Types
Cascading Stylesheets css text/css
DSSSL-online stylesheets application/dsssl (proposed)
Image Types
GIF gif image/gif
X-Windows bitmap (b/w) xbm image/x-xbitmap
X-Windows pixelmap (8-bit color) xpm image/x-xpixmap
Portable Network Graphics png image/x-png
Image Exchange Format (RFC 1314) ief image/ief
JPEG jpeg jpg jpe image/jpeg
TIFF tiff tif image/tiff
RGB rgb image/rgb
image/x-rgb
Group III Fax (RFC 1494) g3f image/g3fax
X Windowdump format xwd image/x-xwindowdump
Macintosh PICT format pict image/x-pict
PPM (UNIX PPM package) ppm image/x-portable-pixmap
PGM (UNIX PPM package) pgm image/x-portable-graymap
PBM (UNIX PPM package) pbm image/x-portable-bitmap
PNM (UNIX PPM package) pnm image/x-portable-anymap
Microsoft Windows bitmap bmp image/x-ms-bmp
CMU raster ras image/x-cmu-raster
Kodak Photo-CD pcd image/x-photo-cd
Computer Graphics Metafile cgm image/cgm
North Am. Presentation Layer Protocol image/naplps
CALS Type 1 or 2 mil cal image/x-cals
Fractal Image Format (Iterated Systems) fif image/fif
QuickSilver active image (Micrografx) dsf image/x-mgx-dsf
CMX vector image (Corel) cmx image/x-cmx
Wavelet-compressed (Summus) wi image/wavelet
AutoCad Drawing (SoftSource) dwg image/vnd.dwg
image/x-dwg
AutoCad DXF file (SoftSource) dxf image/vnd.dxf
image/x-dxf
Simple Vector Format (SoftSource) svf image/vnd.svf
also vector/x-svf
Audio/Voice/Music Related Types
“basic”audio – 8-bit u-law PCM au snd audio/basic
Macintosh audio format (AIpple) aif aiff aifc audio/x-aiff
Microsoft audio wav audio/x-wav
MPEG audio mpa abs mpega audio/x-mpeg
MPEG-2 audio mp2a mpa2 audio/x-mpeg-2
compressed speech (Echo Speech Corp.) es audio/echospeech
Toolvox speech audio (Voxware) vox audio/voxware
RapidTransit compressed audio (Fast Man) lcc application/fastman
Realaudio (Progressive Networks) ra ram application/x-pn-realaudio
NIFF music notation data format application/vnd.music-niff
MIDI music data mmid x-music/x-midi
Koan music data (SSeyo) skp application/vnd.koan
application/x-koan
Speech synthesis data (MVP Solutions) talk text/x-speech
Video Types
MPEG video mpeg mpg mpe video/mpeg
MPEG-2 video mpv2 mp2v video/mpeg-2
Macintosh Quicktime qt mov video/quicktime
Microsoft video avi video/x-msvideo
SGI Movie format movie video/x-sgi-movie
VDOlive streaming video (VDOnet) vdo video/vdo
Vivo streaming video (Vivo software) viv video/vnd.vivo
video/vivo
Special HTTP/Web Application Types
Proxy autoconfiguration (Netscape browsers) pac application/x-ns-proxy-autoconfig
See Chapter 6 application/x-www-form-urlencoded
See Chapter 9 application/x-www-local-exec
See Chapter 9 (Netscape extension) multipart/x-mixed-replace
See Chapter 9 and Appendix B multipart/form-data
Netscape Cooltalk chat data (Netscape) ice x-conference/x-cooltalk
Interactive chat (Ichat) application/x-chat
Application Types
Text-Related
PostScript ai eps ps application/postscript
Microsoft Rich Text Format rtf application/rtf
Adobe Acrobat PDF pdf application/pdf
application/x-pdf
Maker Interchange Format (FrameMaker) mif application/vnd.mif
application/x-mif
Troff document t tr roff application/x-troff
Troff document with MAN macros man application/x-troff-man
Troff document with ME macros me application/x-troff-me
Troff document with MS macros ms application/x-troff-ms
LaTeX document latex application/x-latex
Tex/LateX document tex application/x-tex
GNU TexInfo document texinfo texi application/x-texinfo
TeX dvi format dvi application/x-dvi
MacWrite document ?? application/macwriteii
MS word document ?? application/msword
WordPerfect 5.1 document ?? application/wordperfect5.1
SGML application (RFC 1874) application/sgml
Office Document Architecture oda application/oda
Envoy Document evy application/envoy
Wang Info. Tranfer Format (Wang) application/wita
DEC Document Transfer Format (DEC) application/dec-dx
IBM Document Content Architecture (IBM) application/dca-rft
CommonGround Digital Paper (No Hands Software) application/commonground
FrameMaker Documents (Frame) doc fm frm frame application/vnd.framemaker
application/x-framemaker
Remote printing at arbitrary printers (RFC 1486) application/remote-printing
Archive/Compressed Archives
Gnu tar format gtar application/x-gtar
4.3BSD tar format tar application/x-tar
POSIX tar format ustar application/x-ustar
Old CPIO format bcpio application/x-bcpio
POSIX CPIO format cpio application/x-cpio
UNIX sh shell archive shar application/x-shar
DOS/PC – Pkzipped archive zip application/zip
Macintosh Binhexed archive hqx application/mac-binhex40
Macintosh Stuffit Archive sit sea application/x-stuffit
Fractal Image Format fif application/fractals
Binary, UUencoded bin uu application/octet-stream
PC executable exe application/octet-stream
WAIS “sources” src wsrc application/x-wais-source
NCSA HDF data format hdf application/hdf
Downloadable Program/Scripts
Javascript program js ls mocha text/javascript
application/x-javascript
VBScript program text/vbscript
UNIX bourne shell program sh application/x-sh
UNIX c-shell program csh application/x-csh
Perl program pl application/x-perl
Tcl (Tool Control Language) program tcl application/x-tcl
Atomicmail program scripts (obsolete) application/atomicmail
Slate documents – executable enclosures (BBN) application/slate
Undefined binary data (often executable progs) application/octet-stream
RISC OS Executable programs (ANT Limited) application/riscos
Animation/Multimedia
Andrew Toolkit inset application/andrew-inset
FutureSplash vector animation (FutureWave) spl application/futuresplash
mBED multimedia data (mBED) mbd application/mbedlet
Macromedia Shockwave (Macromedia) application/x-director
Sizzler real-time video/animation application/x-sprite
PowerMedia multimedia (RadMedia) rad application/x-rad-powermedia
Presentation
PowerPoint presentation (Microsoft) ppz application/mspowerpoint
PointPlus presentation data (Net Scene) css application/x-pointplus
ASAP WordPower (Software Publishing Corp.) asp application/x-asap
Astound Web Player multimedia data (GoldDisk) asn application/astound
Special Embedded Object
OLE script e.g. Visual Basic (Ncompass) axs application/x-olescript
OLE Object (Microsoft/NCompass) ods application/x-oleobject
OpenScape OLE/OCX objects (Business@Web) opp x-form/x-openscape
Visual Basic objects (Amara) wba application/x-webbasic
Specialized data entry forms (Alpha Software) frm application/x-alpha-form
client-server objects (Wayfarer Communications) wfx x-script/x-wfxclient
General Applications
Undefined binary data (often executable progs) application/octet-stream
CALS (U.S. D.O.D data format – RFC 1895) application/cals-1840
Pointcast news data (Pointcast) pcn application/x-pcn
Excel spreadsheet (Microsoft) application/vnd.ms-excel
application/x-msexcel
application/ms-excel
PowerPoint (Microsoft) ppt application/vnd.ms-powerpoint
application/ms-powerpoint
Microsoft Project (Microsoft) application/vnd.ms-project
Works data (Microsoft) application/vnd.ms-works
MAPI data (Microsoft) application/vnd.ms-tnef
Artgallery data (Microsoft) application/vnd.artgalry
SourceView document (Dataware Electronics) svd application/vnd.svd
Truedoc (Bitstream) application/vnd.truedoc
Net Install – software install (20/20 Software) ins application/x-net-install
Carbon Copy – remote control/access (Microcom) ccv application/ccv
Spreadsheets (Visual Components) vts workbook/formulaone
Cybercash digital money (Cybercash) application/cybercash
Format for sending generic Macintosh files application/applefile
Active message — connect to active mail app. application/activemessage
X.400 mail message body part (RFC 1494) application/x400-bp
USENET news message id (RFC 1036) application/news-message-id
USENET news message (RFC 1036) application/news-transmission
Multipart Types (mostly email)
Messages with multiple parts multipart/mixed
Messages with multiple, alternative parts multipart/alternative
Message with multiple, related parts multipart/related
Multiple parts are digests multipart/digest
For reporting of email status (admin.) multipart/report
Order of parts does not matter multipart/parallel
Macintosh file data multipart/appledouble
Aggregate messages; descriptor as header multipart/header-set
Container for voice-mail multipart/voice-message
HTML FORM data (see Ch. 9 and App. B) multipart/form-data
Infinite multiparts – See Chapter 9 (Netscape) multipart/x-mixed-replace
Message Types (mostly email)
MIME message message/rfc822
Partial message message/partial
Message containing external references message/external-body
Message containing USENET news message/news
HTTP message message/http
2D/3D Data/Virtual Reality Types
VRML data file wrl vrml x-world/x-vrml (changing to model/vrml)
WIRL – VRML data (VREAM) vrw x-world/x-vream
Play3D 3d scene data (Play3D) p3d application/x-p3d
Viscape Interactive 3d world data (Superscape) svr x-world/x-svr
WebActive 3d data (Plastic Thought) wvr x-world/x-wvr
QuickDraw3D scene data (Apple) 3dmf x-world/x-3dmf
Scientific/Math/CAD Types
Chemical types — to communicate information about chemical models chemical/* (several subtypes)
Mathematica notebook ma application/mathematica
Computational meshes for numerical simulations msh x-model/x-mesh(evolving to model/mesh)
Vis5D 5-dimensional data v5d application/vis5d
IGES models — CAD/CAM (CGM) data igs application/iges(evolving to model/iges?)
Autocad WHIP vector drawings dwf drawing/x-dwf
Largely Platform-Specific Types
Silicon Graphics Specific Types
Showcase Presentations showcase slides sc sho show application/x-showcase
Insight Manual pages ins insight application/x-insight
Iris Annotator data ano application/x-annotator
Directory Viewer dir application/x-dirview
Software License lic application/x-enterlicense
Fax manager file faxmgr application/x-fax-manager
Fax job data file faxmgrjob application/x-fax-manager-job
IconBook data icnbk application/x-iconbook
? wb application/x-inpview
Installable software in ‘inst’ format inst application/x-install
Mail folder mail application/x-mailfolder
? pp ppages application/x-ppages
Data for printer (via lpr) sgi-lpr application/x-sgi-lpr
Software in ‘tardist’ format tardist application/x-tardist
Software in compressed ‘tardist’ format ztardist application/x-ztardist
WingZ spreadsheet wkz application/x-wingz
Open Inventor 3-D scenes iv graphics/x-inventor

HTTP Response Header 的 Content-Disposition

十一月 27, 2008

因为听到有同事讨论JSP输出Excel文件的,就是在页面上有一个【导出】按钮,能够将查询结果导出到Excel文件让用户下载。有人说要用 POI在后台生成临时的Excel文件,然后通过读取FileStream写入到OutputStream来解决。其实这个功能不需要这么重型的武器的, 虽然很多人讨厌MS,但是不得不承认MS绝对不是乱盖的,IE和Office产品的几近完美的结合就是一个列子。页面里面的Table很容易就可以导出到 Excel文件,而且格式都能够完好的保存,所以如果要将查询结果导出到Excel,只需将页面的Context-Type修改一下就可以了:

<%@ page language=”java” contentType=”application/vnd.ms-excel”%>

然后请求这个页面的时候,就会出现这样的IE窗口:

image

看到上面的菜单了么?出了IE的,还有Excel的。而且在点击“文件”->“另存为”的时候,如果选择“Excel工作簿”,那么保存的文件就是真正的转换到Excel文件的存储格式了。

不过,有一个问题是,如果我不希望直接在IE里面打开Excel文件,我希望能够提供那个打开/保存的对话框,应该如何做?

模模糊糊记得很久很久以前用过一个参数,于是乎,google一下吧,找到了,就是这个Content-Disposition参数,HTTP Response Header的一个参数。但是这个不是标准参数,查看一下HTTP/1.1的规范文档,对于这个参数的解释大意如下:

Content-Disposition参数本来是为了在客户端另存文件时提供一个建议的文件名,但是考虑到安全的原因,就从规范中去掉了这个参数。但是由于很多浏览器已经能够支持这个参数,所以只是在规范文档中列出,但是要注意这个不是HTTP/1.1的标准参数。

于是,在页面加入一行代码:

<%
response.addHeader(“Content-Disposition”, “attachment;filename=test.xls”);
%>

能够看到“文件下载”的对话框了:

image

测试了一下,其实IE是根据Content-Disposition中filename这个段中文件名的后缀来识别这个文件类型的,所以,如果有很多种文件类型的时候,可以将Content-Type设置为二进制模式的:

<%@ page language=”java” contentType=”application/octet-stream”%>

附Content-Disposition的解释:

19.5.1 Content-Disposition The Content-Disposition response-header field has been proposed as a means for the origin server to suggest a default filename if the user requests that the content is saved to a file. This usage is derived from the definition of Content-Disposition in RFC 1806 [35].

content-disposition = “Content-Disposition” “:” disposition-type *( “;” disposition-parm )
disposition-type = “attachment” | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = “filename” “=” quoted-string
disp-extension-token = token
disp-extension-parm = token “=” ( token | quoted-string )

An example is
Content-Disposition: attachment; filename=”fname.ext”

The receiving user agent SHOULD NOT respect any directory path information present in the filename-parm parameter, which is the only parameter believed to apply to HTTP implementations at this time. The filename SHOULD be treated as a terminal component only.

If this header is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as…’ dialog.

How to easily export data to an excel sheet (CSV) and also a solution for UTF-8 export.

十一月 27, 2008

from http://www.weberdev.com/get_example-3701.html

So you want to allow your users to get some data directly into their excel…. no problem.

All you need to do it organize your data in rows where each data field is delimited by a comma or
some other acceptable delimiter and send the correct header to the browser.

Suppose you want to send something like :

Car Type Car Model Number of Cars
Mazda 323 5
Mazda 6 4
Mazda MPV 6

all you need to do is :

<?php
header
(“Content-type: application/csv\nContent-Disposition: \”inline; filename=Report.csv\”");
Echo
“Car Type,Car Model,Number of Cars\n”;
Echo
“Mazda,323,5\n”;
Echo
“Mazda,6,4\n”;
Echo
“Mazda,MPV,6\n”;
?>

Tip : It always helps to put a nice excel logo where you offer to export your data to excel format.
You can get such a logo here:

http://www.weberdev.com/images/excel.gif

When your data is in UTF-8 you can’t simply export it into excel since Excel does not support UTF-8. It took me some time to find but finally i found an example by peter kehl which you can see bellow :

UTF-16LE solution for CSV for Excel by Eugene Murai works well:

<?php
$unicode_str_for_Excel
= chr(255).chr(254).mb_convert_encoding( $utf8_str, ‘UTF-16LE’, ‘UTF-8′);
?>

However, then Excel on Mac OS X and also some windows doesn’t identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB “\t” character as the CSV delimiter rather than comma or colon.

You may also want to use HTTP encoding header, such as

<?php
header
( “Content-type: application/vnd.ms-excel; charset=UTF-16LE” );
?>

20 Great PHP frameworks for developers

十一月 24, 2008
A good PHP framework can help you develope a PHP application quickly, with more simplicity and with a vision “best-practices-oriented”.

Take a look at this list with 20 great PHP frameworks and suggest that you prefer or a new link to a framework not included into this list.

1. CodeIgniter
CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications.
Read more…

2. CakePHP
CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications.
Read more…

3. Symfony
Symfony is a full-stack framework, a library of cohesive classes written in PHP5. It provides an architecture, components and tools for developers to build complex web applications faster. Choosing symfony allows you to release your applications earlier, host and scale them without problem, and maintain them over time with no surprise.
Read more…

4. Prado
PRADOTM is a component-based and event-driven programming framework for developing Web applications in PHP 5. PRADO stands for PHP Rapid Application Development Object-oriented.
Read more…

5. Qcodo
It is a completely object-oriented framework that takes the best of PHP and provides a truly rapid application development platform. Initial prototypes roll out in minutes instead of hours. Iterations come around in hours instead of days (or even weeks). As projects iterate into more cohesive solutions, the framework allows developers to take prototypes to the next level by providing the capability of bringing the application maturity.
Read more…

6. Zend Framework
Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and cataloguers like StrikeIron and ProgrammableWeb.
Read more…

7. Akelos
The Akelos PHP Framework is a web application development platform based on the MVC (Model View Controller) design pattern. Based on good practices, it allows you to:
Write views using Ajax easily, Control requests and responses through a controller, Manage internationalized applications, Communicate models and the database using simple conventions.
Read more…

8. Maintainable
The Maintainable PHP Framework was originally built only for our own projects, then released to open source at the request of our customers. Like any framework, it’s certainly not appropriate for every application. It’s designed primarily for use with small- to mid- sized applications.
Read more…

9. evoCore
evoCore is the framework at the heart of the b2evolution blogging application. It is freely available for anyone to use. It is dual licensed so you can choose to use it either under the GNU GPL or the Mozilla MPL license. (b2evo for example is using it under the GPL).
Read more…

10. Stratos
The Stratos Framework is an open-source, object-oriented web application framework that facilitates the rapid development of well-organized, secure, and maintainable PHP web applications. Stratos frees you from working on tedious, routine tasks, and allows you to focus on specific software requirements.
Read more…

11. Seagull
Seagull is a mature OOP framework for building web, command line and GUI applications. Licensed under BSD, the project allows PHP developers to easily integrate and manage code resources, and build complex applications quickly.
Read more…

12. Zoop
The Zoop Framework is inclusive, cooperating with and containing components integrated from some existing projects including Smarty, the Prototype JS Framework, and a number of Pear Modules.
Read more…

13. php.MVC
php.MVC implements the Model-View-Controller (MVC) design pattern, and encourages application design based on the Model 2 paradigm. This design model allows the Web page or other contents (View) to be mostly separated from the internal application code (Controller/Model), making it easier for designers and programmers to focus on their respective areas of expertise.
Read more…

14. AjaxAC
AjaxAC is an open-source framework written in PHP, used to develop/create/generate AJAX applications. The fundamental idea behind AJAX (Asynchronous JavaScript And XML) is to use the XMLHttpRequest object to change a web page state using background HTTP sub-requests without reloading the entire page. It is released under the terms of the Apache License v2.0.
Read More…

15. xAjax
xAjax is an open source PHP class library that allows to create quickly Ajax applications using HTML, CSS, JavaScript, and PHP.
Read more…

16. PHOCOA
PHOCOA (pronounced faux-ko) is PHP framework for developing web applications. PHOCOA’s primary intent is to make web application development in PHP easier, faster, and higher-quality.
Read more…

17. Kohana
Kohana is a PHP 5 framework that uses the model view controller architectural pattern. It aims to be secure, lightweight, and easy to use.
Read more…

18. Limb
Limb is an OpenSource(LGPL) PHP framework mostly aimed for rapid web application prototyping and development. The current actively developed branch of framework is Limb3(there is also Limb2 but it’s not maintained anymore).
Read more…

19. Solar
Solar is a PHP 5 framework for rapid application development. It is fully name-spaced and uses enterprise application design patterns, with built-in support for localization and configuration at all levels.
Read more…

20. BlueShoes
BlueShoes is a comprehensive application framework and content management system. It is written in the widely used web-scripting language PHP. BlueShoes offers excellent support for the popular MySQL database as well as support for Oracle and MSSQL.
Read more…