Wednesday, November 30, 2016

Poe's law

Poe's law is an Internet adage that states that, without a clear indicator of the author's intent, it is impossible to create a parody of extreme views so obviously exaggerated that it cannot be mistaken by some readers or viewers as a sincere expression of the parodied views.

The original statement of the adage, by Nathan Poe, was:
Without a winking smiley or other blatant display of humor, it is uttrerly impossible to parody a Creationist in such a way that someone won't mistake for the genuine article.

@reference_0

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

外键约束 Foreign Key Constraints

@reference_1   @reference_2

Sunday, November 27, 2016

insert values (` !== ", ` !== ')

INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES (`qqqqq`, `3bad6af0fa4b8b330d162e19938ee981`, `qqqq`, `qqqq`)
报错:  #1054 - Unknown column 'qqqqq' in 'field list'


 INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES ("qqqqq", "3bad6af0fa4b8b330d162e19938ee981", "qqqq", "qqqq")
或者
INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES ('qqqqq', '3bad6af0fa4b8b330d162e19938ee981', 'qqqq', 'qqqq')
执行成功

总结:插入值引号用"或',不能用` 。(` !== ", ` !== ')

Saturday, November 26, 2016

Tips - CSS Layout

*{margin: 0px;} // 去缝隙
header_t_l{... float:left;} // 对齐方式
header_t_r{... float:left;} // 用display:inline?
header_b{... float:left;}  // (?)<div>是block级别的
@reference_1

The Old Way - using {float: left;}{clear: left;}
The New Way - using {display: inline-block;}
@reference_2

...CSS box model中,width/height不算入padding和border...
@reference_3

img{vertical-align:middle;} //图片和input输入框水平对齐

Thursday, November 24, 2016

:nth-child & :nth-of-type

.first span:nth-child(2n+1),
.second span:nth-child(2n+1), 
.third span:nth-of-type(2n+1) { 
background-color: lime; 
}
--------------------
Responsive Table
A responsive table will display a horizontal scroll bar if the screen is too small to display the full content.
Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:
<div style="overflow-x:auto;">
<table>
... table content ...
</table>
</div>
------------------------
display: block;
display: inline;
display: none;
visibility: hidden;
@reference_2

position: static;
position: relative;
position: fixed;
position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Note: A "positioned" element is one whose position is anything except static.
@reference_3

Wednesday, November 23, 2016

javascript Currying

function accumulator() {
    if (arguments.length > 0) {
        var arr = Array.prototype.slice.call(arguments, 0);
        var sum = Array.prototype.reduce.call(arr, function (a, b) { return a + b; });
        return sum;
        }
        else return 0;
}

function curryIt(fn) {
    if (arguments.length === 0 || typeof fn !== 'function') return 0;
    var args = Array.prototype.slice.call(arguments, 1);
    var newa = [];
    return function () {
         newa = Array.prototype.slice.call(arguments, 0);
         if (!newa.length) {
             return fn.apply(this, args);
         }
         else {
               args = args.concat(newa);
               return arguments.callee;
         }
   };
}
----------------------------------------
keywords: Closure, partially applied function / 闭包, 偏(应用)函数
@reference_1 @reference_2  @reference_3  @reference_4
@reference_5

Tuesday, November 22, 2016

Counting instances of values in an object

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function(allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
@source_0 

Javascript 'in' operator

The in operator returns true if the specified property is in the specified object.
 // Arrays
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false
"bay" in trees    // returns false (you must specify the 
                  // index number, not the value at that index)
"length" in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES6+)

// Predefined objects
"PI" in Math          // returns true

// Custom objects
var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar  // returns true
"model" in mycar // returns true
 @source_1
-------------------------
var point = {x:1,y:1};
"x" in point //true
"z" in point //false
"toString" in point //true
var ary = [1,2,3];
"0" in ary; //true,ary含有索引0("0"回转换为0);
1 in ary;  //true,ary含有索引1
3 in ary;  //false
@source_2
 


javascript '||'、'&&'

由于javascript是弱类型语言,所以在javascript中这两个表达式可能跟其他语言(比如java)中不太一样。
在javascript中,“&&”运算符运算法则如下:
如果&&左侧表达式的值为真值,则返回右侧表达式的值;否则返回左侧表达式的值。
||”运算符的运算法则如下:
如果||左侧表达式的值为真值,则返回左侧表达式的值;否则返回右侧表达式的值。

Source@0

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();
Or for setting default values:
var name = otherName || "default";
JavaScript has a ternary operator for conditional expressions:
var allowed = (age > 18) ? "yes" : "no";

@reference_1_mozilla

Tricky use case of map

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.
// Consider:
['1', '2', '3'].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN]

// parseInt is often used with one argument, but takes two.
// The first is an expression and the second is the radix.
// To the callback function, Array.prototype.map passes 3 arguments: 
// the element, the index, the array
// The third argument is ignored by parseInt, but not the second one,
// hence the possible confusion. See the blog post for more details

function returnInt(element) {
  return parseInt(element, 10);
}

['1', '2', '3'].map(returnInt); // [1, 2, 3]
// Actual result is an array of numbers (as expected)

// A simpler way to achieve the above, while avoiding the "gotcha":
['1', '2', '3'].map(Number); // [1, 2, 3] 
@Soure

why Array.prototype.map.call instead of Array.map.call

Array is a constructor function to create arrays.

If you type Array in browser console you will get a function definition, something like

function Array() { [native code] }

While if you type Array.prototype in browser console you will get an empty array i.e [ ] i.e. an Array object.

Consider this excerpt
function a(){
console.log('hi');
function b(){console.log('b');}
function c(){console.log('c');}
return {b:b,c:c,d:this}
}

When you type d = new a();
Then d is an object having two properties which are functions i.e. b and c and you can call

>> d.b() //logs b
>> d.c() //logs c

But you cannot call

a.b() or a.c() // since function b and c is not property of a.

So just as function b and c are defined in function a. Similarly function map is defined in function Array.

So you cannot call Array.map() but you have to get an object of Array and call map function on it.
Array.prototype gives us an Array object
Therefore they are using Array.prototype.map.call(a,func)

http://stackoverflow.com/questions/20153455/why-array-prototype-map-call-instead-of-array-map-call 

Using map to reverse a string

var str = '12345';
Array.prototype.map.call(str, function(x) {
  return x;
}).reverse().join(''); 

// Output: '54321'
// Bonus: use '===' to test if original string was a palindrome
 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 

Monday, November 21, 2016

Array.prototype.slice.call()

Array.prototype.slice.call()能将具有length属性的对象转成数组
Array.prototype.slice.call(arguments)能够将arguments转成数组,那么就是 arguments.toArray().slice();
是不是就可以说Array.prototype.slice.call(arguments)的过程就是先将传入进来的第一个参数转为数组,再调用slice?

1 var a={length:2,0:'first',1:'second'};
2 Array.prototype.slice.call(a);//  ["first", "second"]
3  
4 var a={length:2};
5 Array.prototype.slice.call(a);//  [undefined, undefined]

http://www.cnblogs.com/littledu/archive/2012/05/19/2508672.html 
Array.prototype.slice.call(arguments,0);
Array.prototype.slice.call("abcd",0);
http://blog.chinaunix.net/uid-26672038-id-3336525.html 

(slice有两个用法,一个是String.slice,一个是Array.slice,
第一个返回的是字符串,第二个返回的是数组,这里我们看第2个。) 

Array toString() & String split()

<p>The toString() method returns an array as a comma separated string.</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
// result: Banana,Orange,Apple,Mango
-------------------------------
<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[0];
}
</script>
// result: a
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters.

Invoking a Function with call() and apply()

call() and apply() are predefined JavaScript function methods. Both methods can be used to invoke a function, and both methods must have the owner object as first parameter.

function myFunction(a, b) {
    return a * b;
}
myObject = myFunction.call(myObject, 10, 2);     // Will return 20 
 
function myFunction(a, b) {
    return a * b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray);  // Will also return 20 
 
The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array. In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object.
In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.
With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.
 http://www.w3schools.com/js/js_function_invocation.asp

Sunday, November 20, 2016

JavaScript Closures

 function add() {

    var counter = 0;
    counter += 1;
}

add();
add();
add();
// the counter should now be 3, but it does not work !
-------------------------------
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();
// the counter is now 3 

Adding Methods to a Prototype

Using the prototype Property
The JavaScript prototype property allows you to add new properties to an existing prototype:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English"
 Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
}; 
 Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
-------------------------------------------------------------------- 
就是调用对象是一个Array,对Array类型增加了一个原型写法的函数,一般写一些扩展时经常用。比如判断一个元素是否在数组中之类的
Array.prototype.inArray=function(value){
   for(var i=0;i<this.length;i++){
       if (this[i] == value){
       return true;
       }
   }
return false
};
var arr=["1","2","3"];
//以下同调用方式,在inArray函数中,使用this即可得到arr
arr.inArray("1");

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

Currying in Functional JavaScript

https://www.google.com/webhp?source=lnms&sa=X&ved=0ahUKEwj41rSypLbQAhUFUrwKHcbtC7YQ_AUIBygA&biw=1229&bih=568&dpr=1.56&gws_rd=cr&ei=fgsxWKojw_LxBcvkiZgJ&fg=1#q=currying+javascript

https://www.sitepoint.com/currying-in-functional-javascript/

https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%87%BD%E6%95%B0%20%E6%9F%AF%E9%87%8C%E5%8C%96%20javascript&oq=curryIt(fn)(1)(2)(%26lt%3B)&rsv_pq=cc56d59e00015d38&rsv_t=5b2084xPjsVRYi5ZMrv3EfkTSwP5svVe5kWgmeZeXBojTScJsHILdAOWXoU&rqlang=cn&rsv_enter=0&inputT=5970&rsv_sug3=41&rsv_sug1=10&rsv_sug7=100&rsv_sug2=0&rsv_sug4=12848

http://www.cnblogs.com/zztt/p/4142891.html

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

http://blog.csdn.net/zdy0_2004/article/details/51079812

arguments js
https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=0&rsv_idx=1&tn=baidu&wd=arguments%20js&rsv_pq=b9bc32e100039474&rsv_t=0a648%2BPYhDgmuXYHRKiwNnxJk34WBLYXmGM49jfT4R0RqnCkYDkWFvFFS8g&rqlang=cn&rsv_enter=1&rsv_sug3=1&rsv_sug1=1&rsv_sug7=100&rsv_sug2=1&prefixsug=arguments&rsp=0

http://www.360doc.com/content/13/0815/15/9671833_307346675.shtml

array.prototype.slice.call
https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=1&tn=baidu&wd=array.prototype.slice.call&oq=Array.prototype.slice&rsv_pq=ac6bd38700032221&rsv_t=8180ueBoipGX%2BJ7%2FMmBR29%2BErgYLRwqhEDInlOiG2Kqq3lpNG9ZT88m3axM&rqlang=cn&rsv_enter=1&rsv_sug3=3&rsv_sug1=3&rsv_sug7=100&rsv_sug2=1&prefixsug=Array.prototype.slice&rsp=0&rsv_sug4=1016

http://blog.chinaunix.net/uid-26672038-id-3336525.html

http://www.cnblogs.com/littledu/archive/2012/05/19/2508672.html

arguments.callee
Polyfill

Saturday, November 19, 2016

JavaScript Array reduce() Method

array.reduce(function(total,currentValue,currentIndex,arr),initialValue)
Returns the accumulated result from the last call of the callback function

<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
    return total + Math.round(num);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum,0);
}
</script>

http://www.w3schools.com/jsref/jsref_reduce.asp
http://www.tuicool.com/articles/6ziqmu2

attr("value")和val() 取值差异?

attr("value")=原来的默认值 ,而val()=用户所填的值?

http://bbs.csdn.net/topics/390406471

Pin Code Refreshing

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

JQuery:
$("#refresh").on("click",function(){$("#refresh").attr('src','pin.php?tm='+Math.random());});

Friday, November 18, 2016

src="js/jquery-3.1.1.js"

<script src="js/jquery-3.1.1.js"></script>
<script>
  function my() {
   alert("Hello!");
   return false;
  }
  $(document).ready(function () {
     $("#demo").html("Hello, JQuery!");
     $("form").on("submit", my);
   });
  });
</script>

以上用了两个<script>标签,如果把第二个标签内的代码放入第一个标签便无法执行,也就是说用src="js/jquery-3.1.1.js"调入其它js文件需单独声明,必须和执行代码的标签分开。
http://www.w3schools.com/jquery/event_on.asp

Tuesday, November 15, 2016

browser window's height and width

A practical JavaScript solution (covering all browsers):
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
--------------------------------------------------
The example displays the browser window's height and width: (NOT including toolbars/scrollbars)

 http://www.w3schools.com/js/js_window.asp

Monday, November 14, 2016

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
Constraint validation HTML Input Attributes
Constraint validation CSS Pseudo Selectors
Constraint validation DOM Properties and Methods
Pseudo-class
http://www.w3schools.com/js/js_validation.asp

Sunday, November 13, 2016

Crap Game

Last night, I was playing 'Civilization V Brave New world'. It's a single game, and I play it with the computer programs, there are 6 civiliazations in the map which contains 2 continents separated by ocean, each continent have 3 civilizations. There are also 10 city states distributed in the map randomly. My civilization is Chinese, the other five are random civilizations operated by the computer program. Initially, all players belong to 6 different teams, I changed the setting and put one computer civilization in my team, thinking that it would be easier to have someone assist you to play against the other 4 independent programs.  But it turned out that I was wrong. In the sceen, it just displayed that the state of your partner is 'friendly'. At some stage, I launched a war against another country, I was trying to deploy my armies to cut off the connection of two cities, so the city I attacked had no backup from the other one. When I thought I was gonna win the battle, suddenly I was made peace with the opponent without my command, it was my 'friend' country who did it! It was the computer program in my team that decided to make peace with the country I was fighting with when my side was dominant. It happened at the time when big ships hadn't been invented to cross the ocean to make any physical contact with the other 3 civilizations. My teammate was on the other continent! After that, it happened several times, there was no coordination or cooperation in the team, it didn't ask for my opinion, in fact, it didn't need my approval or consent to stop the war, my side was forced to make peace in the middle of war. What a crap, who designed the program?!

Saturday, November 12, 2016

DEV C++

同一个项目(project)下的C源文件,不需要#include“xxxx.c"声明,即可直接调用不同文件的函数和变量(变量需用extern声明,函数不需要extern声明)。如果用了#include“xxxx.c"声明,则编译会报错。但是,宏定义不包括在内,调用不同文件的宏仍需#include“xxxx.c"声明。

没有新建项目,直接打开的 C源文件调用不同文件的函数和变量,需要#include“xxxx.c"声明,否则编译会报错。

Friday, November 11, 2016

javascript: Sorting an Array in Random Order

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()}); 
 
 http://www.w3schools.com/js/js_array_sort.asp

Thursday, November 10, 2016

javascript: Avoid new Array(), Use [] instead.

var points = new Array(); // Bad
var points = []; // Good
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!

http://www.w3schools.com/js/js_arrays.asp

How to Recognize an Array?
The typeof operator returns object because a JavaScript array is an object.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits; // returns object

Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
Solution 2:function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
it returns true if the object prototype contains the word "Array".
Solution 3:The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array // returns true

Wednesday, November 9, 2016

Global Methods

JavaScript global methods can be used on all JavaScript data types.
 Number()      Returns a number, converted from its argument.
parseFloat()    Parses its argument and returns a floating point number
parseInt()       Parses its argument and returns an integer

x = true;
Number(x);        // returns 1


parseInt("10.33");      // returns 10


parseFloat("10.33");     // returns 10.33
 
If the number cannot be converted, NaN (Not a Number) is returned.

http://www.w3schools.com/js/js_number_methods.asp

Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a function.

myFunction();

// code here can use carName
function myFunction() {
    carName = "Volvo";
}
 
Do NOT create global variables unless you intend to.
In "Strict Mode" automatically global variables will fail.


With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object. All global variables belong to the window object.

 http://www.w3schools.com/js/js_scope.asp

OO in JavaScript

A method is actually a function definition stored as a property value.
If you access the fullName method, without (), it will return the function definition:

 http://www.w3schools.com/js/js_objects.asp
 
在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称"实例")共有的属性和方法。Javascript语言不支持"类",但是可以用一些变通的方法,模拟出"类"。 Javascipt语法不支持"类"(class).

 http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html
  
JavaScript objects cannot be compared.

var x = "John";           
var y = new String("John");
// (x === y) is false because x and y have different types (string and object) 
 
var x = new String("John");           
var y = new String("John");

// (x == y) is false because x and y are different objects// (x == x) is true because both are the same object

http://www.w3schools.com/js/js_strings.asp


Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
The length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
 
 http://www.w3schools.com/js/js_string_methods.asp

JavaScript types

JavaScript has dynamic types. This means that the same variable can be used as different types:
Example
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.

in JavaScript, an array is actually a special kind of object.

http://www.w3schools.com/js

JavaScript中的数组并不像我们在C或java等语言中遇到的常规数组,在js中数组并不是起始地址+长度构成的一片连续的地址空间。
javascript中数组其实就是个对象,只不过会自动管理一些"数字"属性和length属性罢了。
说的更直接一点,JavaScript中的数组根本没有索引,因为索引应该是数字,而JavaScript中数组的索引其实是字符串。
arr[1]其实就是arr["1"],给arr["1000"] = 1,arr.length也会自动变为1001。
这些表现的根本原因就是:JavaScript中的对象就是字符串到任意值的键值对。
虽然稀疏数组和密集数组差别不大,javascript也没有语法强制数组是稀疏的还是密集的,这不过是概念上的区分。

这行代码等同于var  dense =  Array(undefined, undefined, undefined) 看代码:
//稀疏数组
 var array = new Array(3); 
 array[2] = "name";
 
 for(var a in array) 
 {
    console.log("index=" + a + ",value=" + array[a]);
 }
 
 // 密集数组
 var dense = Array.apply(null, Array(3)); 
 dense[2] = "name";
 for(var a in dense) 
 {
    console.log("index=" + a + ",value=" + dense[a]);
 }

http://www.tuicool.com/articles/AfYnEf

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)