Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, June 8, 2017

Content-Type & MIME types


Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that provides the description about what are you sending to the browser.
MIME is an internet standard that is used for extending the limited capabilities of email by allowing the insertion of sounds, images and text in a message.
The features provided by MIME to the email services are as given below:
  • It supports the non-ASCII characters
  • It supports the multiple attachments in a single message
  • It supports the attachment which contains executable audio, images and video files etc.
  • It supports the unlimited message length.
@reference_1_javatpoint
Content Type
@reference_2_developer.mozilla.org
Content-Type
@reference_3_developer.mozilla.org
MIME types

What is a MIME type?

MIME stands for "Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format. For example, using the "Content-type" header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

What is an Internet Media Type?

"Internet Media Type" is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

What is a Content-Type?

A "Content-type" is simply a header defined in many protocols, such as HTTP, that makes use of MIME types to specify the nature of the file currently being handled.

What does a MIME type look like?

A MIME type is a string identifier composed of two parts: a "type" and a "subtype". The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category. "subtypes" are specific to one file type within the "type".
For example, the MIME value "application/xml" is used for XML documents and specifies that the "xml" subtype belongs in the "application" type.

Why are some MIME subtypes prefixed with "x-"?

The "x-" prefix of a MIME subtype simply means that it's non-standard, i.e. not registered with the "Internet Assigned Numbers Authority" (IANA).

Why are some MIME subtypes prefixed with "vnd"?

The "vnd" prefix means that the MIME value is vendor specific.

How can I set the Content-type header of my files?

It depends on the programming language you are using. Note that most language have a default "Content-type" of "text/html".
  • Setting the Content-type in Java:

    // Response is of type javax.servlet.ServletReponse
    response.setContentType("text/plain");
  • Setting the Content-type in PHP:

    <?php header('Content-type: text/html');?>
 @reference_4_freeformatter
MIME Types List
@reference_5_stackoverflow
What are all the possible values for HTTP “Content-Type” header?

Wednesday, May 17, 2017

Cross-Site HTTP Requests

Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
The following line, in our PHP examples, has been added to allow cross-site access.

header("Access-Control-Allow-Origin: *");

Include Cross Domains

By default, the ng-include directive does not allow you to include files from other domains.
To include files from another domain, you can add a whitelist of legal files and/or domains in the config function of your application:
 
<body ng-app="myApp">

<div ng-include="'https://tryit.w3schools.com/angular_include.php'"></div>

<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'https://tryit.w3schools.com/**'
    ]);
});
</script>

</body>
Be sure that the server on the destination allows cross domain file access.

@reference_2_w3schools

Monday, November 28, 2016

SQL injection

SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The original purpose of the code was to create an SQL statement to select a user with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can enter some "smart" input like this: UserId:

Server Result: SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always true.

A smart hacker might get access to user names and passwords in a database by simply inserting " or ""=" into the user name or password text box:
User Name:

Password:

The code at the server will create a valid SQL statement like this:
 SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since  
WHERE ""="" is always true.

 SQL Injection Based on Batched SQL Statements 
The following input:
User id:

The code at the server would create a valid SQL statement like this:
 SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers

Parameters for Protection

How to build parameterized queries in some common web languages?INSERT INTO STATEMENT IN PHP:
$stmt = $dbh->prepare("INSERT INTO Customers (CustomerName,Address,City)
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();
-------------------------------------------------
@reference_0

Sunday, November 20, 2016

php path & dirname(__FILE__)

 上一层目录相对路径:
ImageTTFText($image, 16, mt_rand(-6, 6), 5, 25, $textColor, "../font/arial.ttf", $rand);
--------------------------------------
<?php
echo __FILE__ ; // 取得当前文件的绝对地址,结果:D:\www\test.php
echo dirname(__FILE__); // 取得当前文件所在的绝对目录,结果:D:\www\
echo dirname(dirname(__FILE__)); //取得当前文件的上一层目录名,结果:D:\
?>

 使用方法提示,
dirname(__FILE__) 取到的是当前文件的绝对路径,也就是说,比起相对路径,查找速度是最快的。
如果重复一次可以把目录往上提升一个层次:
比如:$d = dirname(dirname(__FILE__));
其实就是把一个目录给dirname()做参数了.因为dirname()返回最后的目录不带\\或者是/
所以重复使用的时候可以认为 dirname() 把最下层的目录当成文件名来处理了.照常返回
当前目录的上级目录.这样重复就得到了它的上一级的目录.

包含得到上一级目录的文件
include(dirname(__FILE__).'/../filename.php');

__FILE__的路径是当前代码所在文件

dirname(dirname(__FILE__));得到的是文件上一层目录名

dirname(__FILE__);得到的是文件所在层目录名

http://www.jb51.net/article/27521.htm

Wednesday, November 9, 2016

onclick=""

<img src="pin.php" id = "refresh" align="absmiddle" onclick="javascript:this.src='pin.php?tm='+Math.random()">

浏览器对图片,JS等文件会进行缓存
当浏览器访问图片的时候,浏览器会查看缓存中是否有这张图片
如果有则使用缓存图片,没有则对服务器重新发起访问
而浏览器判断是否存在缓存文件是通过文件的url进行识别的
如果url不同,浏览器就会对服务器发起新的请求
所有加上一个随机参数就能实现验证码图片的刷新
因为随机数不同,所以url就不同,所以每次浏览器都会对验证码图片发起新的访问,达到刷新验证码的功能
无论是img.src = "imgcode.php?"+Math.random();
还是imgcode.php?tm="+Math.random();
都是为了不要使用浏览器中图片缓存
其中tm没有任何意思,你可以随便取你想要的名字
甚至就像第一种情况不用给名字

http://wenwen.sogou.com/z/q251179201.htm

explode(,)

$_SESSION['pincode'] = md5($rand) . ',' . time();
...
$vcode = explode(',', $_SESSION['pincode']);
if ((time() - $vcode[1]) > self::$timer) {
return 'Verification Code Time out! '.(time() - $vcode[1]);
} elseif ($vcode[0] == md5($value)) {
return 'PASS';
} else {
return "Verification Code doesn't match!";
}
...

Tuesday, November 8, 2016

'Access Denied!'

if (!defined('IS_INITPHP')) exit('Access Denied!');
defined('THINK_PATH') or exit('Access Denied!');
---------------------------------------------------------------------
 if(!isset($_SESSION['pin_permit']) || $_SESSION['pin_permit'] !== 'OK'){
    exit('Access Denied!');
}

http://blog.csdn.net/liuxinmingcode/article/details/8055431

Monday, November 7, 2016

Validate Form Data

Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

http://www.w3schools.com/php/php_form_validation.asp
 -------------------------------------------------
 Sanitize a String
The following example uses the filter_var() function to remove all HTML tags from a string:
 ...
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
...
<?php
$url = "http://www.w3schools.com";
// Remove all illegal characters from a url$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate urlif (!filter_var($url, FILTER_VALIDATE_URL) === false) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");
}
?>
 http://www.w3schools.com/php/php_filter.asp
 ------------------------------------
 int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
http://www.regexr.com/
http://php.net/manual/en/function.preg-match.php
 

The $_SERVER["PHP_SELF"] variable can be used by hackers!


If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users.
Assume we have the following form in a page named "test_form.php":
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Now, if a user enters the normal URL in the address bar like "http://www.example.com/test_form.php", the above code will be translated to:
<form method="post" action="test_form.php">
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
In this case, the above code will be translated to:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example.


How To Avoid $_SERVER["PHP_SELF"] Exploits?

$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
The form code should look like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">
The exploit attempt fails, and no harm is done!

 http://www.w3schools.com/php/php_form_validation.asp

Sunday, November 6, 2016

session机制

session机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。 当程序需要为某个客户端的请求创建一个session时,服务器首先检查这个客户端的请求里是否已包含了一个session标识(称为session id),如果已包含则说明以前已经为此客户端创建过session,服务器就按照session id把这个session检索出来使用(检索不到,会新建一个),如果客户端请求不包含session id,则为此客户端创建一个session并且生成一个与此session相关联的session id,session id的值应该是一个既不会重复,又不容易被找到规律以仿造的字符串,这个session id将被在本次响应中返回给客户端保存。保存这个session id的方式可以采用cookie,这样在交互过程中浏览器可以自动的按照规则把这个标识发送给服务器。一般这个cookie的名字都是类似于SEEESIONID。但cookie可以被人为的禁止,则必须有其他机制以便在cookie被禁止时仍然能够把session id传递回服务器。经常被使用的一种技术叫做URL重写,就是把session id直接附加在URL路径的后面。还有一种技术叫做表单隐藏字段。就是服务器会自动修改表单,添加一个隐藏字段,以便在表单提交时能够把session id传递回服务器。比如:
<form name="testform" action="/xxx">
<input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764">
<input type="text">
</form>
实际上这种技术可以简单的用对action应用URL重写来代替。
cookie 和session 的区别:
1、cookie数据存放在客户的浏览器上,session数据放在服务器上。
2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗, 考虑到安全应当使用session。
3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能,考虑到减轻服务器性能方面,应当使用COOKIE。
4、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

https://zhidao.baidu.com/question/176300050773899604.html

Verification Image

<?php
session_start();

$alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// generate the verication code
$rand = substr(str_shuffle($alphanum), 0, 5);
// choose one of four background images
$bgNum = rand(1, 4);

$image = imagecreatefromjpeg("background$bgNum.jpg");
$textColor = imagecolorallocate ($image, 0, 0, 0);
// write the code on the background image
imagestring ($image, 5, 5, 8, $rand, $textColor);
// ... no changes after this point
?>

 http://www.php-mysql-tutorial.com/wikis/php-tutorial/user-authentication-with-image-verification.aspx
 http://www.cnblogs.com/chenbjin/p/3409934.html
---------------------------

语法: array ImageTTFText(int im, int size, int angle, int x, int y, int col, string fontfile, string text);

本函数将 TTF (TrueType Fonts) 字型文字写入图片。参数 size 为字形的尺寸;angle 为字型的角度,顺时针计算,0 度为水平,也就是三点钟的方向 (由左到右),90 度则为由下到上的文字;x,y 二参数为文字的坐标值 (原点为左上角);参数 col 为字的颜色;fontfile 为字型文件名称,亦可是远端的文件;text 当然就是字符串内容了。返回值为数组,包括了八个元素,头二个分别为左下的 x、y 坐标,第三、四个为右下角的 x、y 坐标,第五、六及七、八二组分别为右上及左上的 x、y 坐标。治募注意的是欲使用本函数,系统要装妥 GD 及 Freetype 二个函数库。

本例建立一个 400x30 pixel 大小的黑底图,并用 Arial 向量字体写出 I am NUMBER ONE !! 的白字。

<?php
Header
("Content-type: image/gif");$im imagecreate(400,30);$black ImageColorAllocate($im0,0,0);$white ImageColorAllocate($im255,255,255);ImageTTFText($im2001020$white"/somewhere/arial.ttf""I am NUMBER ONE !!");ImageGif($im);ImageDestroy($im);?>


 http://www.t086.com/code/php/function.php-ImageTTFText.php
http://blog.csdn.net/liuxinmingcode/article/details/8055431

ImageTTFText($image, 15, -7, 10, 30, $textColor, "font/arial.ttf", $rand);




Saturday, November 5, 2016

php OO - 1

访问控制

访问控制通过关键字publicprotectedprivate来实现。
  • 被定义为公有的类成员(public)可以在任何地方被访问。
  • 被定义为受保护的类成员(protected)则可以被其自身以及其子类和父类访问。
  • 被定义为私有的类成员(private)则只能被其定义所在的类访问。
  • 类属性必须定义为公有、受保护、私有之一。
  • 为兼容PHP5以前的版本,如果采用 var 定义,则被视为公有。
  • 类中的方法可以被定义为公有、私有或受保护。
  • 如果没有设置这些关键字,则该方法默认为公有:
  • 如果构造函数定义成了私有方法,则不允许直接实例化对象了,这时候一般通过静态方法进行实例化,在设计模式中会经常使用这样的方法来控制对象的创建,比如单例模式只允许有一个全局唯一的对象:
<?php

    class Car {
        // 显然这是一个私有的构造函数
        private function __construct() {
            echo 'object create';
        }
        // 这是一个私有的属性
        private static $_object = null;
        // 这是一个公共方法
        public static function getInstance() {
            if (empty(self::$_object)) {
                self::$_object = new Car(); // 内部方法可以调用私有方法,因此这里可以创建对象
            }
            return self::$_object;
        }
    }
    // $car = new Car(); // 这里不允许直接实例化对象
    $car = Car::getInstance(); // 通过静态方法来获得一个实例

?>

对象继承
继承是面向对象程序设计中常用的一个特性,汽车是一个比较大的类,我们也可以称之为基类,除此之外,汽车还分为卡车、轿车、东风、宝马等,因为这些子类具有很多相同的属性和方法,可以采用继承汽车类来共享这些属性与方法,实现代码的复用。
在代码中,实际上就是类的继承,ClassA extends ClassB,就是这么简单,但是这为我们开发提供了一个对象的重用性的特质,使得我们在开发上得到更好便利。
对象(我的理解就是类)的继承,就是函数方法调用的通道和数据接口的使用,实际使用就是这么的一个体验。(这仅仅是我的观点,欢迎大家指正我的观点,同时欢迎大家发表你的观点。)

重载
PHP中的重载指的是动态的创建属性与方法,是通过魔术方法来实现的。
属性的重载通过__set,__get,__isset,__unset来分别实现对不存在属性的赋值、读取、判断属性是否设置、销毁属性。
关于重载,有以下这个案例可以看一下:
<?php

    class Car {
        // 显然这是一个私有属性
        private $ary = array();
        // 魔法方法 __set
        public function __set($key, $val) {
            $this->ary[$key] = $val;
        }
        //  魔法方法__get
        public function __get($key) {
            if (isset($this->ary[$key])) {
                return $this->ary[$key];
            }
            return null;
        }
        //  魔法方法__isset
        public function __isset($key) {
            if (isset($this->ary[$key])) {
                return true;
            }
            return false;
        }
        //  魔法方法__unset
        public function __unset($key) {
            unset($this->ary[$key]);
        }
    }
    $car = new Car();
    $car->name = '汽车';  //name属性动态创建并赋值
    echo $car->name;

?>
方法的重载通过__call来实现,当调用不存在的方法的时候,将会转为参数调用__call方法,当调用不存在的静态方法时会使用__callStatic重载。

<?php

    class Car {
        public $speed = 0;
        // 显然这是一个魔法方法__call(),实现方法的重载
        public function __call($name, $args) {
            if ($name == 'speedUp') {
                $this->speed += 10;
            }
        }
    }
    $car = new Car();
    $car->speedUp(); // 调用不存在的方法会使用重载
    echo $car->speed;

?>
对象复制,在一些特殊情况下,可以通过关键字clone来复制一个对象,这时__clone()方法会被调用,通过这个魔术方法来设置属性的值。

<?php

    class Car {
        public $name = 'car';
        // 这是一个魔法方法__clone()方法
        public function __clone() {
            $obj = new Car();
            $obj->name = $this->name;
        }
    }
    $a = new Car();
    $a->name = 'new car';
    // 通过关键字clone来复制一个对象
    $b = clone $a;
    var_dump($b);

?>
Source: https://segmentfault.com/a/1190000004067581



MIME Type

https://zhidao.baidu.com/question/306468835963644404.html
http://blog.csdn.net/gulianchao/article/details/19963955
http://www.dreamdu.com/xhtml/mime_type/

if($conn instanceof mysqli)

is_object($conn);  
is_a($conn, 'mysqli');  
if($conn instanceof mysqli){...}    

http://php.net/manual/en/function.is-a.php

Friday, November 4, 2016

UPDATE table


UPDATE `t_users` SET `t_logintimes`=`t_logintimes`+1,`t_lastip`='127.0.0.1',`t_lasttime`=NOW() WHERE `t_username` = 'user0'

>>>>` != '<<<<

connect to my via php OO

$conn = new mysqli($server, $db_username, $db_password, $dbname);
$result = $conn->query($sql);
if ($result->num_rows > 0) {...}
is_array($row = $result -> fetch_assoc());
$conn->close();

https://zhidao.baidu.com/question/2201572985022619508.html


upload a file




<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<input type="hidden" name="MAX_FILE_SIZE" value="32768" />

<input type="file" id="screenshot" name="screenshot" />


built-in PHP superglobal variable named $_FILES, which is similar to the $_POST superglobal we’ve used to access form data. Like $_POST, $_FILES is an array, and within it is not only the name of the uploaded file, but also some other information about the file that might prove useful.
$_FILES['screenshot']['type']

move_uploaded_file($_FILES['screenshot']['tmp_name'], $target);

@unlink($_FILES['screenshot']['tmp_name']);
The unlink() function deletes a file from the web server. We suppress its error reporting with @ in case the file upload didn't actually succeed.

(from: Head First PHP and MySQL P237/277)

Thursday, November 3, 2016

square brackets

echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]">';The square brackets result in the creation of an array within $_POST that stores the contents of the value attribute of every checked checkbox in the form. 
 The square brackets at the end of the checkbox name automatically put the
checkbox values in an array we've named “todelete[]”.


(from: Head First PHP and MySQL P215/255)

ALTER TABLE

ALTER TABLE email_list ADD id INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (id)


  (from: Head First PHP and MySQL P211/251)