博客 (42)

程序设计规范:


  • 【推荐】上传的文件直接保存到文件存储服务(如阿里云 OSS),这样即使被上传了后门 shell,对网站服务器也不会有影响。

  • 否则必须通过文件头来确定文件类型,检查文件十六进制的文件头和文件尾是否合法,并检查文件流中是否包含 php、evel 等字符。

  • 不可直接使用客户端文件名来保存文件,特别是后缀名/扩展名。应生成随机文件名,并通过检验文件头来确定文件类型。必须由程序指定保存目录。

  • 使用 OSS 的应直接上传,不要在 ECS 上临时存放或备份。如必须存放的,应按上述规范操作。


服务器安全设置


CentOS + nginx + PHP:

  • 全站文件取消属性中的“执行”权限(chmod),因为这个“执行”与运行 PHP 无关。而需要上传文件的“目录”需要“执行”权限,原因是需要往该目录创建文件。

  • 仅需要写入的目录或文件设置“写入”权限。如上传图片目录、ThinkPHP 的 Runtime 目录。

  • 凡可写目录或文件均不允许运行 PHP / PY 等 除需要被直接访问的 PHP / PY 文件,其它动态文件均不允许被访问到,在 nginx 的配置文件中添加项,参:https://xoyozo.net/Blog/Details/nginx-location-if,若全站使用统一的入口文件访问,那么设置仅该文件允许运行 PHP 即可。通过 IO 方式被其它文件包含的文件,无需运行 PHP 权限。(“deny all”对 include 起作用,但对 IO 不起作用,因此 Runtime 目录可以继续为 ThinkPHP 提供缓存服务。)这一步非常有用。

  • 使用与 nginx 网站用户不同的用户来部署网站文件,如宝塔面板 PHP 使用 www 用户,那么就使用 root 或其它新用户来上传文件,否则将导致全站目录和文件可写。有条件的建议不同网站使用不同的用户,可防止一个网站被入侵后导致其它网站文件或磁盘上的其它文件被泄露的风险(2022年10月2日从宝塔官方社区获悉,宝塔面板暂不支持使用非 www 用户创建并运行网站)。


Windows Server + IIS + ASP.NET:

  • 配置每个磁盘的安全属性,拒绝“IIS_IUSRS”这个用户组的所有权限。只要设置驱动器即可,子文件夹和文件会自动继承。若运行 .NET Framework 项目,需要设置 C:\Windows\Microsoft.NET\Framework\v*.*.*****\Temporary ASP.NET Files\ 目录可修改写入权限,.NET Core 项目不需要此设置。

  • 为每个网站创建一个新用户,仅隶属于“IIS_IUSRS”。网站根目录安全属性添加该用户,权限选择“读取”。(已测取消“读取与执行”不影响 PHP,“列出文件夹内容”视业务需求开启,建议关闭)。仅需要上传文件的目录或文件设置“修改”、“写入”权限。(修改对应修改文件,写入对应上传文件)

  • IIS 网站中设置“物理路径凭据”以及应用程序池的“标识”。

  • IIS 中设置写入目录的“处理程序映射”无脚本

xoyozo 10 年前
5,862

最小化安装 CentOS 6.4,配置网络

一条一条执行:
yum -y update
yum -y install wget
yum -y install vim
yum -y install screen
screen -S lnmp

安装 LNMP:http://lnmp.org/install.html
下载安装一条龙

不要升级各软件,以防不测

PHP 防跨站:执行一段命令,替换 vhost.sh 文件,以后添加网站就会自动添加 HOST 防跨站、跨目录的配置

更改数据库路径(/home/mysql/var)
http://bbs.vpser.net/thread-1558-1-1.html 第20条
端口(为了 pureftpd 能安装成功,还是不要改端口了)

防火墙加端口
vim /etc/sysconfig/iptables
service iptables restart

FreeTDS:使 php 支持 mssql

安装 PureFTPd
添加FTP用户时,UID和GID必须>1000,譬如添加一个xWeb组和用户:
groupadd -g 2000 xWeb
useradd -u 2000 -g xWeb -s /sbin/nologin -M userDefault
useradd -u 2001 -g xWeb -s /sbin/nologin -M userFang
useradd -u 2002 -g xWeb -s /sbin/nologin -M user2
useradd -u 2003 -g xWeb -s /sbin/nologin -M user3
然后 chown xUser:xWeb -R /home/wwwroot/网站目录
这样PHP木马就不能上传。非www用户每站一个,防止跨站
要写入的目录chown为www用户,这样PHP能创建目录及上传文件,允许公共写入,使FTP能操作写入(未验证PHP创建的新目录FTP有没有写入权限,即继承),所有要写入的目录必须 deny all

chown userFang:xWeb -R /home/wwwroot/fang.eyuyao.com/
chown www:www -R /home/wwwroot/fang.eyuyao.com/uploads/
chown www:www -R /home/wwwroot/fang.eyuyao.com/eyy/src/
chown www:www -R /home/wwwroot/fang.eyuyao.com/index/Runtime/
chown www:www -R /home/wwwroot/fang.eyuyao.com/admin/Runtime/
—————————————————————————————————
#设置目录不允许执行PHP(其实是使符合正则的路径不可读)
#找到网站的 .conf 配置文件,在 location ~ .*\.(php|php5)?$ 的上面插入:
location ~ /upload/.*\.(php|php5)?$
    {
        deny    all;
    }

#支持 ThinkPHP(使用 rewrite)
location ~ /index\.php/.*$
    {
        if (!-e $request_filename) { 
            rewrite  ^/index\.php(/.*)$  /index.php?s=$1  last;
            break;
        }
    }
—————————————————————————————————
重启 LNMP    /root/lnmp restart
重启 MySQL    /etc/init.d/mysql restart
重启 PureFTPd    /root/pureftpd restart
查看 Nginx 版本    nginx -V
查看 MySQL 版本    mysql -V
查看 PNP 版本    php -v
查看 Apache 版本    httpd -v
查内存        cat /proc/meminfo
php.ini        vim /usr/local/php/etc/php.ini
iptables 路径    /etc/sysconfig/iptables
MySQL 配置文件    vim /etc/my.cnf
添加网站        /root/vhost.sh
添加ProFTPd用户    /root/proftpd_vhost.sh
—————————————————————————————————
遇到问题:
中文URL问题解决方案,FTP用强制UTF-8,单个文件传。否则在win下打包的zip在linux下解压后,编码不是utf-8,导致打开URL 404
能用记事本打开的文件若包含中文,应另存为 utf-8 编码。

ThinkPHP 项目修改配置文件后,必须删除 /index/Runtime/* 缓存文件!!!

xoyozo 12 年前
5,259

升级“微信登录 1.1.6”插件后,发现微社区发帖提示“抱歉,您的请求来路不正确或表单验证串不符,无法提交”,查看更新日记发现微社区域名更换为 wsq.discuz.com,导致表单验证不通过的原因就是它了。

解决方法是打开:\source\class\helper\helper_form.php

找到:'http://wsq.discuz.qq.com', 24

或:'http://wsq.discuz.qq.com/', 25

替换为:'http://wsq.discuz.com/', 22

然后清空目录:\data\cache\qrcode\

至于帖子分享给朋友或朋友圈的标题和图片不正常的问题,目前还没有办法解决,听说是该插件要收费的节奏,具体可以参与官方讨论:

http://www.discuz.net/forum-2-1.html

另外,如果发现微社区里的用户头像或表情不能正常显示,一般是由于做了防盗链引起的,只要在白名单里加上 *.discuz.com 就行了

xoyozo 9 年前
5,571

在 ASP.NET Core 或 ASP.NET 5 中部署百度编辑器请跳转此文


本文记录百度编辑器 ASP.NET 版的部署过程,对其它语言版本也有一定的参考价值。

【2020.02.21 重新整理】


下载

从 GitHub 下载最新发布版本:https://github.com/fex-team/ueditor/releases

按编码分有 gbk 和 utf8 两种版本,按服务端编程语言分有 asp、jsp、net、php 四种版本,按需下载。


目录介绍

以 v1.4.3.3 utf8-net 为例,

ueditor 目录结构.png


客户端部署

本例将上述所有目录和文件拷贝到网站目录 /libs/ueditor/ 下。

当然也可以引用 CDN 静态资源,但会遇到诸多跨域问题,不建议。

在内容编辑页面引入:

<script src="/libs/ueditor/ueditor.config.js"></script>
<script src="/libs/ueditor/ueditor.all.min.js"></script>

在内容显示页面引入:

<script src="/libs/ueditor/ueditor.parse.min.js"></script>

如需修改编辑器资源文件根路径,参 ueditor.config.js 文件内顶部文件。(一般不需要单独设置)

如果使用 CDN,那么在初始化 UE 实例的时候应配置 serverUrl 值(即 controller.ashx 所在路径)。


客户端配置

初始化 UE 实例:

var ue = UE.getEditor('tb_content', {
    // serverUrl: '/libs/ueditor/net/controller.ashx', // 指定服务端接收文件路径
    initialFrameWidth: '100%'
});

其它参数见官方文档,或 ueditor.config.js 文件。


服务端部署

net 目录是 ASP.NET 版的服务端程序,用来实现接收上传的文件等功能。

本例中在网站中的位置是 /libs/ueditor/net/。如果改动了位置,那么在初始化 UE 的时候也应该配置 serverUrl 值。

这是一个完整的 VS 项目,可以单独部署为一个网站。其中:

net/config.json  服务端配置文件
net/controller.ashx  文件上传入口
net/App_Code/CrawlerHandler.cs  远程抓图动作
net/App_Code/ListFileManager.cs  文件管理动作
net/App_Code/UploadHandler.cs  上传动作

该目录不需要转换为应用程序。


服务端配置

根据 config.json 中 *PathFormat 的默认配置,一般地,上传的图片会保存在 controller.ashx 文件所在目录(即本例中的 /libs/ueditor/)的 upload 目录中:
/libs/ueditor/upload/image/
原因是 UploadHandler.cs 中 Server.MapPath 的参数是由 *PathFormat 决定的。

修改 config.json 中的 imagePathFormat 为例:

原值:"imagePathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"

改为:"imagePathFormat": "/upload/ueditor/{yyyy}{mm}{dd}/{time}{rand:6}"

以“/”开始的路径在 Server.MapPath 时会定位到网站根目录。

此处不能以“~/”开始,因为最终在客户端显示的图片路径是 imageUrlPrefiximagePathFormat,若其中包含符号“~”就无法正确显示。

在该配置文件中查找所有 PathFormat,按相同的规则修改。


说到客户端的图片路径,我们只要将

原值:"imageUrlPrefix": "/ueditor/net/"

改为:"imageUrlPrefix": ""

即可返回客户端正确的 URL。

当然也要同步修改 scrawlUrlPrefix、snapscreenUrlPrefix、catcherUrlPrefix、videoUrlPrefix、fileUrlPrefix。


特殊情况,在复制包含图片的网页内容的操作中,若图片地址带“?”等符号,会出现无法保存到磁盘的情况,需要修改以下代码:

打开  CrawlerHandler.cs 文件,找到

ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat"));

替换成:

ServerUrl = PathFormatter.Format(Path.GetFileName(SourceUrl.Contains("?") ? SourceUrl.Substring(0, SourceUrl.IndexOf("?")) : SourceUrl), Config.GetString("catcherPathFormat"));


如果你将图片保存到第三方图库,那么 imageUrlPrefix 值设为相应的域名即可,如:

改为:"imageUrlPrefix": "//cdn.***.com"

然后在 UploadHandler.cs 文件(用于文件上传)中找到

File.WriteAllBytes(localPath, uploadFileBytes);

在其下方插入上传到第三方图库的代码,以阿里云 OSS 为例:

// 上传到 OSS
client.PutObject(bucketName, savePath.Substring(1), localPath);

在 CrawlerHandler.cs 文件(无程抓图上传)中找到

File.WriteAllBytes(savePath, bytes);

在其下方插入上传到第三方图库的代码,以阿里云 OSS 为例:

// 上传到 OSS
client.PutObject(bucketName, ServerUrl.Substring(1), savePath);


最后有还有两个以 UrlPrefix 结尾的参数名 imageManagerUrlPrefix 和 fileManagerUrlPrefix 分别是用来列出上传目录中的图片和文件的,

对应的操作是在编辑器上的“多图上传”功能的“在线管理”,和“附件”功能的“在线附件”。

最终列出的图片路径是由 imageManagerUrlPrefiximageManagerListPath + 图片 URL 组成的,那么:

"imageManagerListPath": "/upload/ueditor/image",

"imageManagerUrlPrefix": "",

以及:

"fileManagerListPath": "/upload/ueditor/file",

"fileManagerUrlPrefix": "",

即可。

如果是上传到第三方图库的,且图库上的文件与本地副本是一致的,那么将 imageManagerUrlPrefix 和 fileManagerUrlPrefix 设置为图库域名,

服务端仍然以 imageManagerListPath 指定的路径来查找本地文件(非图库),但客户端显示图库的文件 URL。

因此,如果文件仅存放在图库上,本地没有副本的情况就无法使用该功能了。

综上,所有的 *UrlPrefix 应该设为一致。


另外记得配置不希望被远程抓图的域名,参数 catcherLocalDomain


服务端授权

现在来判断一下只有登录用户才允许上传。

首先打开服务端的统一入口文件 controller.ashx

继承类“IHttpHandler”改为“IHttpHandler, System.Web.SessionState.IRequiresSessionState”,即同时继承两个类,以便可使用 Session,
找到“switch”,其上插入:

if (用户未登录) { throw new System.Exception("请登录后再试"); }

即用户已登录或 action 为获取 config 才进入 switch。然后,

else
{
    action = new NotAllowedHandler(context);
}

这里的 NotAllowedHandler 是参照 NotSupportedHandler 创建的,提示语 state 可以是“登录后才能进行此操作。


上传目录权限设置

上传目录(即本例中的 /upload/ueditor/ 目录)应设置允许写入和禁止执行。


基本用法

设置内容:

ue.setContent("Hello world.");

获取内容:

var a = ue.getContent();

更多用法见官方文档:http://fex.baidu.com/ueditor/#api-common


其它事宜

配置上传附件的文件格式

找到文件:config.json,更改“上传文件配置”的 fileAllowFiles 项,

同时在 Web 服务器上允许这些格式的文件可访问权限。以 IIS 为例,在“MIME 类型”模块中添加扩展名。


遇到从客户端(......)中检测到有潜在危险的 Request.Form 值。参考此文


另外,对于不支持上传 .webp 类型的图片的问题,可以作以下修改:
config.json 中搜索“".bmp"”,替换为“".bmp", ".webp"
IIS 中选中对应网站或直接选中服务器名,打开“MIME 类型”,添加,文件扩展名为“.webp”,MIME 类型为“image/webp


最后,为了在内容展示页面看到跟编辑器中相同的效果,请参照官方文档引用 uParse

若有插入代码,再引用:
<link href="/lib/ueditor/utf8-net/third-party/SyntaxHighlighter/shCoreDefault.css" rel="stylesheet" />
<script src="/lib/ueditor/utf8-net/third-party/SyntaxHighlighter/shCore.js"></script>

其它插件雷同。


若对编辑器的尺寸有要求,在初始化时设置即可:

var ue = UE.getEditor('tb_content', {

  initialFrameWidth: '100%',
  initialFrameHeight: 320
});


图片等附件上传到阿里云 OSS 参考此文

xoyozo 9 年前
7,209

关于wdcp后台要用mysql root用户密码的说明,可以看这里
http://www.wdlinux.cn/bbs/thread-932-1-1.html

要在wdcp后台里创建数据库及数据库用户,那就必须要让wdcp里有root用户密码,否则,就无法创建

所以,有些用户说,在phpmyadmin修改了root用户密码后,就无法创建了,那是肯定的,因为你改了root的密码,但wdcp不知道,也不知道新密码是什么,那还能创建吗?答案是 肯定是不能的

那要怎样正确地修改root用户的密码呢?难道就不难修改了吗,当然不是

只要在wdcp的后台里修改就可以了,所以也强烈建议在wdcp后台里修改,如下图
wdcp1055.jpg wdcp1056.jpg 

那如果已经修改了或在其它地方修改了还有办法吗
有,可以上面那个连接的说明

又或者用这个工具修改,wdcp2.2版本开始提供
用ssh登录到服务器上运行
sh /www/wdlinux/tools/mysql_root_chg.sh
就可以了

这个工具修改,还可以用在忘记root用户密码的时候修改,是强制修改

注:这里说的root用户,是mysql数据库里的root用户,不是Linux系统的root用户,有区别的

w
转自 wdlinux 13 年前
3,987

最近有服务器不时出现的CPU使用率超高,内存几乎被吃光,系统甚至自动kill掉一些进程,如sshd,vsftpd等。用top查看,PHP-CGI进程高挂不下,如下是解决方案:
一、进程跟踪
# top //找出CPU使用率高的进程PID
# strace -p PID //跟踪进程
# ll /proc/PID/fd //查看该进程在处理哪些文件
将有可疑的PHP代码修改之,如:file_get_contents没有设置超时时间。
二、内存分配
如果进程跟踪无法找到问题所在,再从系统方面找原因,会不会有可能内存不够用?据说一个较为干净的PHP-CGI打开大概20M-30M左右的内存,决定于PHP模块开启多少。
通过pmap指令查看PHP-CGI进程的内存使用情况
# pmap $(pgrep php-cgi |head -1)
按输出的结果,结合系统的内存大小,配置PHP-CGI的进程数(max_children)。
三、监控
最后,还可以通过监控与自动恢复的脚本保证服务的正常运转。下面是我用到的一些脚本:
只要一个php-cgi进程占用的内存超过 %1 就把它kill掉
#!/bin/sh
PIDS=`ps aux|grep php-cgi|grep -v grep|awk’{if($4>=1)print $2}’`
for PID in $PIDS
do
echo `date +%F….%T`>>/data/logs/phpkill.log
echo $PID >> /data/logs/phpkill.log
kill -9 $PID
done


检测php-fpm进程
#!/bin/bash
netstat -tnlp | grep “php-cgi” >> /dev/null #2&> /data/logs/php_fasle.log
if [ "$?" -eq "1" ];then #&& [ `netstat -tnlp | grep 9000 | awk '{ print $4}' | awk -F ":" '{print $2}'` -eq "1" ];then
/usr/local/webserver/php/sbin/php-fpm start
echo `date +%F….%T` “System memory OOM.Kill php-cgi. php-fpm service start. ” >> /data/logs/php_monitor.log
fi

通过http检测php执行
#!/bin/bash
status=`curl -s –head “http://127.0.0.1:8080/chk.php” | awk ‘/HTTP/ {print $2}’`
if [ $status != "200" -a $status != "304" ]; then
/usr/local/webserver/php/sbin/php-fpm restart
echo `date +%F….%T` “php-fpm service restart” >> /data/logs/php_monitor.log
fi

l
转自 lgh_2002 13 年前
4,567

默认安装,PHP里只是安装了一些常用或基本的模块,其它的要用时再添加就可以的
这里模块分两种
一种是php自带的模块,也就是源码里就有,不用下载
一种是要另外下载的安装模块,如
http://www.wdlinux.cn/bbs/thread-4-1-1.html

这里只介绍,在PHP自带的模块
比如SOAP

首先,确定之前有下载的一键包,如果没有,先下载(也可以单独下载PHP软件包)
wget http://dl.wdlinux.cn:5180/lanmp_last.tar.gz
tar zxvf lanmp_last.tar.gz
cd lanmp
tar zxvf php-5.2.17.tar.gz
cd php-5.2.17
cd ext/soap
/www/wdlinux/php/bin/phpize

./configure --with-php-config=/www/wdlinux/php/bin/php-config
make
make install


echo 'extension=soap.so' >> /www/wdlinux/etc/php.ini

然后重起下服务
service httpd restart
or
service nginxd restart

其它所有的模块,参考这两个例子即可完成安装

w
转自 wdlinux 13 年前
3,786

PHP如何获取表单的POST数据呢?本文介绍3种获取POST数据的方法,并将代码附上,希望可以帮助到你。

一、PHP获取POST数据的几种方法

方法1、最常见的方法是:$_POST['fieldname'];

说明:只能接收Content-Type: application/x-www-form-urlencoded提交的数据
解释:也就是表单POST过来的数据
 

方法2、file_get_contents(“php://input”);

说明:

允许读取 POST 的原始数据。
和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。
php://input 不能用于 enctype=”multipart/form-data”。

解释:

对于未指定 Content-Type 的POST数据,则可以使用file_get_contents(“php://input”);来获取原始数据。
事实上,用PHP接收POST的任何数据都可以使用本方法。而不用考虑Content-Type,包括二进制文件流也可以。
所以用方法二是最保险的方法。
 

方法3、$GLOBALS['HTTP_RAW_POST_DATA'];

说明:

总是产生 $HTTP_RAW_POST_DATA  变量包含有原始的 POST 数据。
此变量仅在碰到未识别 MIME 类型的数据时产生。
$HTTP_RAW_POST_DATA  对于 enctype=”multipart/form-data”  表单数据不可用
如果post过来的数据不是PHP能够识别的,可以用 $GLOBALS['HTTP_RAW_POST_DATA']来接收,
比如 text/xml 或者 soap 等等

解释:

$GLOBALS['HTTP_RAW_POST_DATA']存放的是POST过来的原始数据。
$_POST或$_REQUEST存放的是 PHP以key=>value的形式格式化以后的数据。
但$GLOBALS['HTTP_RAW_POST_DATA']中是否保存POST过来的数据取决于centent-Type的设置,即POST数据时 必须显式示指明Content-Type: application/x-www-form-urlencoded,POST的数据才会存放到 $GLOBALS['HTTP_RAW_POST_DATA']中。
 

二、演示

1、PHP 如何获取POST过来的XML数据和解析XML数据

比如我们在开发微信企业号时,如何处理用户回复过来的数据呢?
文档:http://qydev.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E6%94%B6%E6%99%AE%E9%80%9A%E6%B6%88%E6%81%AF
首先查阅文档,可知道:启用开发模式后,当用户给应用回复信息时,微信服务端会POST一串XML数据到已验证的回调URL

假设该URL为 http://www.xxx.com
Http请求方式: POST
http://www.xxx.com/?msg_signature=ASDFQWEXZCVAQFASDFASDFSS×tamp=13500001234&nonce=123412323

POST的XML内容为:

<xml>
   <ToUserName><![CDATA[toUser]]></ToUserName>
   <FromUserName><![CDATA[fromUser]]></FromUserName> 
   <CreateTime>1348831860</CreateTime>
   <MsgType><![CDATA[text]]></MsgType>
   <Content><![CDATA[this is a test]]></Content>
   <MsgId>1234567890123456</MsgId>
   <AgentID>1</AgentID>
</xml>

那么怎么接收这段内容呃?

这时就可以用到:方法2(file_get_contents(“php://input”))、方法3($GLOBALS['HTTP_RAW_POST_DATA'])

方法2(file_get_contents(“php://input”)):

$input = file_get_contents("php://input"); //接收POST数据
$xml = simplexml_load_string($input); //提取POST数据为simplexml对象
var_dump($xml);

方法3($GLOBALS['HTTP_RAW_POST_DATA'])

$input = $GLOBALS['HTTP_RAW_POST_DATA'];
libxml_disable_entity_loader(true);
$xml = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
var_dump($xml);

PHP获取POST数据的3种方法及其代码分析,希望可以帮到你。

P
转自 PHP100 10 年前
4,548

Apple’s newest devices feature the Retina Display, a screen that packs double as many pixels into the same space as older devices. For designers this immediately brings up the question, “What can I do to make my content look outstanding on these new iPads and iPhones?”. First there are a few tough questions to consider, but then this guide will help you get started making your websites and web apps look amazingly sharp with Retina images!

retina image comparison

Things to Consider When Adding Retina Images

The main issue with adding retina images is that the images are double as large and will take up extra bandwidth (this won’t be an issue for actual iOS apps, but this guide is covering web sites & web apps only). If your site is mostly used on-the-go over a 3G network it may not be wise to make all your graphics high-definition, but maybe choose only a select few important images. If you’re creating something that will be used more often on a WI-FI connection or have an application that is deserving of the extra wait for hi-res graphics these steps below will help you target only hi-res capable devices.

Simple Retina Images

The basic concept of a Retina image is that your taking a larger image, with double the amount of pixels that your image will be displayed at (e.g 200 x 200 pixels), and setting the image to fill half of that space (100 x 100 pixels). This can be done manually by setting the height and width in HTML to half the size of your image file.

<img src="my200x200image.jpg" width="100" height="100">

If you’d like to do something more advanced keep reading below for how you can apply this technique using scripting.

Creating Retina Icons for Your Website

When users add your website or web app to their homescreen it will be represented by an icon. These sizes for regular and Retina icons (from Apple) are as follows:
ios icon samples

iPhone 57 x 57
Retina iPhone 114 x 114
iPad 72 x 72
Retina iPad 144 x 144

For each of these images you create you can link them in the head of your document like this (if you want the device to add the round corners remove -precomposed):

<link href="touch-icon-iphone.png" rel="apple-touch-icon-precomposed" />
<link href="touch-icon-ipad.png" rel="apple-touch-icon-precomposed" sizes="72x72" />
<link href="touch-icon-iphone4.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
<link href="touch-icon-ipad3.png" rel="apple-touch-icon-precomposed" sizes="144x144" />

If the correct size isn’t specified the device will use the smallest icon that is larger than the recommended size (i.e. if you left out the 114px the iPhone 4 would use the 144px icon).

Retina Background Images

Background images that are specified in your CSS can be swapped out using media queries. You’ll first want to generate two versions of each image. For example ‘bgPattern.png’ at 100px x 100px and ‘bgPattern@2x.png’ at 200px x 200px. It will be useful to have a standard naming convention such as adding @2x for these retina images. To add the new @2x image to your site simply add in the media query below (You can add any additional styles that have background images within the braces of the same media query):

.repeatingPattern {
     background: url(../images/bgPattern.png) repeat;
     background-size: 100px 100px;
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
     .repeatingPattern {
          background: url(../images/bgPattern@2x.png) repeat;
     }
}

JavaScript for Retina Image Replacement

For your retina images that aren’t backgrounds the best option seems to be either creating graphics with CSS, using SVG, or replacing your images with JavaScript. Just like the background images, you’ll want to create a normal image and one ‘@2x’ image. Then with JavaScript you can detect if the pixel ratio of the browser is 2x, just like you did with the media query:

if (window.devicePixelRatio == 2) {

//Replace your img src with the new retina image

}

If you’re using jQuery you could quickly replace all your images like this very basic example below. It’s a good idea to add a class to identify the images with hi-res versions so you don’t replace any others by mistake. I’ve added a class=”hires” for this example. Also make sure you have the standard (non-retina) image height and width set in the HTML:

<img class="hires" alt="" src="search.png" width="100" height="100" />
<script type="text/javascript">
$(function () {

	if (window.devicePixelRatio == 2) {

          var images = $("img.hires");

          // loop through the images and make them hi-res
          for(var i = 0; i < images.length; i++) {

            // create new image name
            var imageType = images[i].src.substr(-4);
            var imageName = images[i].src.substr(0, images[i].src.length - 4);
            imageName += "@2x" + imageType;

            //rename image
            images[i].src = imageName;
          }
     }

});
</script>

Server-Side Retina Images

If you’d like to implement a server-side retina image solution, I recommend checking out Jeremy Worboys’ Retina Images (which he also posted in the comments below). His solution uses PHP code to determine which image should be served. The benefit of this solution is that it doesn’t have to replace the small image with the retina one so you’re using less bandwidth, especially if you have lots of images that you’re replacing.

Website Optimization for Retina Displays

If you’re looking for additional information on creating Retina images, I’ve recently had a short book published called Website Optimization for Retina Displays that covers a range of related topics. It contains some of what is above, but also includes samples for many different situations for adding Retina images. It explains the basics of creating Retina images, backgrounds, sprites, and borders. Then it talks about using media queries, creating graphics with CSS, embedding fonts, creating app icons, and more tips for creating Retina websites.

K
转自 Kyle Larson 13 年前
4,697

 

日期 時間 課程名稱 講師 類型 初學者參加
2004/08/09 ~ 2004/08/13 上午 9:30 ~ 12:00 網頁基礎設計 陳劍恒 入門 可以,免基礎
2004/08/09 ~ 2004/08/13 下午 13:30 ~ 16:30 FreeBSD入門教學 黃世銘 入門 可以,免基礎
2004/08/16 ~ 2004/08/20 上午 09:30 ~ 12:00 一周學會PHP接案 孫仲岳 入門 可以,免基礎
2004/08/16 ~ 2004/08/20 下午 13:30 ~ 16:30 網路概論 陳威任 入門 可以,免基礎
2004/08/30 ~ 2004/09/03 上午 09:30 ~ 12:00 JSP網頁設計入門 歐陽芳泉 入門 可以,免基礎
2004/08/30 ~ 2004/09/03 下午 13:30 ~ 16:30 Linux架站入門 林炫百 入門 可以,免基礎
2004/09/06 ~ 2004/09/10 上午 9:30 ~ 12:00 Java程式設計入門 歐陽芳泉 入門 可以,免基礎
2004/09/06 ~ 2004/09/10 下午 13:30 ~ 16:30 PHP 專案實戰講座 孫仲岳 進階 簡單的 PHP基礎
2004/09/23 ~ 2004/09/24 下午 19:00 ~ 21:30 PHP 新手上路講座 孫仲岳 入門 可以,免基礎
2005/01/24 ~ 2005/01/28 上午 9:00 ~ 12:00 Linux 入門教學 陳威任 入門 可以,免基礎
2005/01/24 ~ 2005/01/28 下午 2:00 ~ 5:00 一週學會 PHP 接案 孫仲岳 入門 可以,免基礎
2005/01/31 ~ 2005/02/04 上午 9:00 ~ 12:00 網路概論 曾全佑 入門 可以,免基礎
2005/01/31 ~ 2005/02/04 下午 2:00 ~ 5:00 FreeBSD 入門教學 邱秉誠 入門 可以,免基礎
6,346