[翻译]PHP安全小建议(上)
近日比较关注PHP的安全问题,国内的许多开发者,特别是PHP初学者,很多时候仅满足功能是否实现,对安全的探讨浅尝辄止甚至漠不关心。这样的后果很严重,比如泛滥的SQL注入,甚至还有直接被下载数据库连接文件的……此文译自Cal Evans发表DevZone的系列专题:PHP Security Tip (安全建议/小窍门) 虽然不是最新文章,但提到的许多原则性的东西和经典的做法仍然是值得重视的,绝对是值得一读的好文章,借此抛砖引玉,希望能给大家一点帮助,建立良好的安全意识,了解必要的防范措施。 文中加入本人的理解和注释的地方已经注明,首次翻译,不当之处欢迎指出。谢谢
,原书共21个建议,这是翻译的上部。
PHP Security Tip #1
Cal Evans (editor) 2 comments Thursday, March 1, 2007
Looking for the security silver bullet? I’ve got bad news for you, there isn’t one. Security take an ongoing effort and a lot of little things instead of one big one. This month we are kicking off a new feature on DevZone, “Security Tip of the Week”. To kick this off right we will post one a day during March. Some of these tips will be specific things you can do, some will be general concepts you need to be aware of, all of them will be brief. So without further comment, here’s the first “Security Tip of the Week”.
Comment
MAILING LIST
1:17PM UTC · Rob [unregistered]
It can often be a good idea to join the relevant mailing list. You can find the announcement list for new releases of PHP below.
http://www.php.net/mailing-lists.php
------------------------------------------------------------------------------
PHP安全小建议1
如果你在寻找安全方面的银弹(在西方基督教的传说中,只有银弹击中心脏,才可以杀死恶魔(吸血鬼? 狼人)。在Fred Brooks关于软件工程的著名书籍《人月神话里》和《没有银弹》中,把规模越来越大的软件开发项目比作无法控制的怪物,即希望有一样技术,能够像银弹彻底杀死恶魔那样,彻底解决这个问题。译者注),我有一个坏消息要告诉你,没有银弹。安全问题需要持续不断的努力和大量琐碎的工作而不是作为单一的大问题来解决,这个月我们将在DevZone开始一个新的专题,"一周安全小建议", 作为开始,在三月期间,我们将每天发布一个建议。有些建议将是一些你可以动手做的具体的事情,另一些则是你需要注意的一般概念,所有的建议都很简短,好了,闲话少说,下面开始我们第一个"一周安全小建议"。
评论:
邮件列表
参与相关的邮件列表是一个好主意,你可以在下列地址找到最新的PHP发布新闻的公告列表!
http://www.php.net/mailing-lists.php
------------------------------------------------------------------------------
PHP Security Tip #2
Cal Evans (editor) 3 comments Friday, March 2, 2007
Security by obscurity is no security at all. On the other hand you don't want to give away information about your site either. Today's tip is a simple one but one that is often overlooked in production environments.
Make sure you do not display errors and potentially leak information about your site.
Simply setting display_errors = Off in your php.ini of your production server will prevent you from leaking information that may give intruders hints to the structure of your system. By default, display_errors = On.
You can find more information and error reporting options in the manual's Error Handling and Logging Functions Introduction section.
------------------------------------------------------------------------------
PHP安全建议#2
使用隐藏信息来保证安全不能从根本上起到安全作用(Security by obscurity is no security at all.),但另一方面你也不想泄露你的站点信息。
今天的建议很简单,但在生产环境下却经常被忽视。
务必不要显示错误信息和站点的潜在泄密信息
只要简单地在生产服务器的php.ini 设置display_errors = Off ,就可以防止泄露系统结构信息,让入侵者有机可乘。默认的设置是:display_errors = On.
在手册的错误处理和日志函数介绍一节,你可以找到更多信息和错误报告选项。
------------------------------------------------------------------------------
PHP Security Tip #3
Cal Evans (editor) 1 comment Monday, March 5, 2007
Being Security conscious is a good thing but that alone won’t solve the problem. Developers have to be vigilant when it comes to security. Even then you can’t do it alone. Today’s Security tip reminds you of this.
Since your application may be harboring security vulnerabilities that you have not been exposed to, third-party security software or services should be considered to help bring a fresh perspective and find overlooked weaknesses.
As a developer you should have tools in your toolbox that will help you find security vulnerabilities in your applications. Tools like Chorizo will help you by performing automated scans of your code. Programs like PHPSecInfo will help you ensure that your environment is configured properly.
Using tools like these and other scanning tools should not be the only thing you do to ensure security. They are however, an important part of the mix. Let trusted projects and vendors help you build and maintain secure applications.
------------------------------------------------------------------------------
PHP安全建议#3
有安全意识是一件好事,但其本身不能解决问题,在安全问题上时开发者必须时刻保持警惕,尽管那样还是不足够的,今天的安全建议给你提 个醒:
由于你的应用程序可能存在很多你未曾发现的安全隐患,使用第三方安全软件或服务可以帮助你对应用程序做一个清晰的透视,发现被忽视的不足之处。
作为开发者,你的工具箱应该有能帮助检测应用程序安全隐患方面的工具。像Chorizo那样的工具, 它能自动扫描你的代码来发现问题,而像PHPSecInfo这样的程序可以确保环境的正确配置。
为了安全的保证,仅仅是使用这些工具或者其他扫描工具还是不够的,然而它们是各种组合措施里很重要的一部分。值得依赖的项目和供应商将有助你建立和维护安全的应用程序。
------------------------------------------------------------------------------
PHP Security Tip #4
Cal Evans (editor) 7 comments Tuesday, March 6, 2007
“Security through obscurity is no security at all.” so the adage goes. However, the flip side of that coin is, obscurity, when used as part of an overall strategy, is a good thing. There’s no sense in making things any easier for those with malicious intent. That brings us to our security tip for the day.
Give files and folders with critical information non-default names.
Don’t rely on obscure names to keep your application safe. You should always check permissions, test for vulnerabilities with testing tools and keep an eye on your log files for suspicious activity. When designing your applications and web sites though, don’t make it easy for bad people to do bad things. Don’t use default or common names for your files and directories.
Do you have a security tip you would like to share? A nugget of security truth you have gleaned through research or life’s school of hard knocks? Log-in and click the contribute button in the upper right hand corner.
------------------------------------------------------------------------------
PHP安全建议#4
正如谚语所说," 使用隐藏信息来保证安全不能从根本上起到安全作用(Security through obscurity is no security at all.)",然而在另一方面,隐藏信息,作为安全整体战略的一部分却是一件好事,为那些怀有不轨之心的家伙把事情变得简单毫无意义,从这里引申出我们今天的安全小建议。
不要企图依赖晦涩的命名来保持应用程序的安全,你应该经常检查权限,使用测试工具检查隐患,留心可疑活动的日志文件。尽管如此,在设计应用和网站时,也不要为有不轨之心的人做坏事提供简便的机会。文件或目录不要使用默认的或者通用的命名。
你是不是也有想要分享的安全小建议呢? 通过研究得到的黄金信条,还是现实生活里碰钉子后的经验教训? 欢迎登录后点击右上角的贡献按钮和我们分享。
------------------------------------------------------------------------------
PHP Security Tip #5
Cal Evans (editor) 1 comment Wednesday, March 7, 2007
PHP security is an ongoing mission requiring the programmer to think outside of the parameters of the application. It’s not enough these days to say in your mind “Does this do what I want it to do?” you also have to take into consideration “What else can people use it for and do I want to allow that?” Today’s Security tip is a proverb that all programmers should have to recite daily.
Never trust the user.
It’s a sad fact of life but users are evil. Users want nothing more than to find a way to exploit your application. As soon as you let your guard down and start thinking “I’m only selling small stuffed animals so how evil can my users really be?” you’ve lost the battle.
Ok, maybe it’s not quite that dire but you do have to keep a wary eye on some of your users. That’s where the second proverb that all programmers should recite daily comes in.
Filter Input, Escape Output
Yes, FIEO (ok, it’s not as cool sounding as GIGO) is one of the mantras that all security minded programmers have live by.
------------------------------------------------------------------------------
PHP安全建议#5
PHP安全是一个持续的任务,它要求程序员思考应用程序参数外面的情况,现在,光是想着“它(应用程序)做了我想让它做的事吗?”你必须同时考虑到"人们还能用它来干什么和我允许他们这样做吗?"今天的安全建议是一个所有程序员必须每天背诵的格言:
永远不要相信用户。(Never trust the user)
用户是邪恶的,尽管就现实生活来说是很悲哀的事情,他们千方百计就为了破解你的应用程序,只要你掉以轻心然后这样想着:“我不过是兜售一点喂饱了的小动物而已(开发应用程序的一个比喻,译者注),我的用户真的能这么邪恶?”,那么你已经输掉了这声战斗。
好吧,也许事情还没这么恐怖的地步,但你仍然需要对一部分用户保持警惕之心。第二个所有程序员必须每天背诵的格言出现了
过滤输入,编码输出(Filter Input, Escape Output)
是的,FIFO(好吧,它的发音不像GIGO那么酷) ,它却是所有具有安全意识的程序员赖以生存的魔咒之一。
------------------------------------------------------------------------------
PHP Security Tip #6
Cal Evans (editor) 5 comments Thursday, March 8, 2007
The topic of writing secure applications in PHP covers more than just writing good PHP code. Most applications make use of a database of some kind. Many times, vulnerabilities that affect the entire application, are introduced when building the SQL code. Today's Tip of the Day deals with one easy solution developers can implement.
When dealing with numbers in a SQL query, always cast.
Even if you are filtering your input, a good and easy to implement safety measure is to cast all numeric values in the SQL statement. Take for example the following code.
$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT);
$sql = 'SELECT * FROM table WHERE id = '.$myId;
Even though you are applying the native PHP filters built into PHP 5.2, there is something additional you can do. Try this instead.
$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT );
$sql = 'SELECT * FROM table WHERE id = '.(int)$myId;
This final cast of the variable to an int removes any doubt about what will be passed to MySQL. The example above is purposefully simplified. In real-life situations, the code would be more complex and the chance for error much greater. By applying the final cast to in building the select statement, you are adding one more level of safety into your application.
------------------------------------------------------------------------------
PHP安全建议#6
编写安全的PHP应用程序的话题远不止编写良好的PHP代码,大部分的应用都会这样或那样地用到数据库,很多时候,在建立SQL代码的过程中,影响整个应用的安全隐患也钻了进来。
在SQL查询中处理数字时,务必进行投射(cast)
即使在过滤输入,一个简单而好用的安全措施是在SQL语句中投射所有的数字类型值。如下列代码所示
$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT);
$sql = 'SELECT * FROM table WHERE id = '.$myId;
即便你使用PHP5.2内置的原生PHP过滤器(请参考最新PHP手册【某些旧的中文版本的PHP手册没有这个章节】Data Filtering一节,译者注),你还可以做一些其他的事情。试试换成下面的语句:
$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT );
$sql = 'SELECT * FROM table WHERE id = '.(int)$myId;
最终模型(final cast)里变量被投射成了整型(int) ,移除了全部到底向Mysql传递了什么的疑惑,以上例子有意地进行了简化,在现实情况下,代码会更复杂,出错的机会也会更多,依赖最终模型来建立select语句,你的代码多了一级安全保护。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7
