Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

x

PHP 본문

공부/웹

PHP

minkmink 2017. 1. 26. 21:29

php 구문

<?php

// php codes

?>


주석

//, # : single-line comment

/**/ : multi-line comment


변수

$변수이름


변수 범위

global : php구문 어디서든지, 함수 안에선 안됨

local: 함수 안에서만, 함수 끝나면 사라짐

static : 함수가 사라져도 유지


함수안에서 global $x, $y; 치면 바깥의 x,y를 참조할 수 있다

$GLOBALS[index] : global 변수를 저장한다. index엔 변수 이름 들어감


echo

echo 안에는 HTML태그가 들어갈 수 있으며 그대로 적용된다.

따옴표 안에서 $x를 써도 x의 값이 출력 된다

인자를 여러개 받을 수 있다

no return value


print

echo와 거의 유사하나 인자를 1개만 받고 살짝 느리다

return value : 1


php 자료형

String : "" or '' 둘다 가능

Int

float

boolean

array : $cars = array("Volvo", "Hyundai" ,"Kia");  또는 array("a" => "red", "b" => "blue");  사실상 딕셔너리

Object : 클래스 객채

NULL


var_dump($x) : 변수의 자료형과 값을 반환


php String

strlen() : return length

str_word_count() : return number of words

strrev() : reverse string

strpos() : return  specific string position ( strpos("hello world", "hello");)

str_replace() : replace string ( str_replace("hello", "hi", "hello world");)


php 상수

define(상수이름 ,상수값)

global하다


php General Operator

C operator과 모두 같다


php String Operator - string concatenation 

$str1.$str2 = 이어붙인다

$str1 .= $str2 = $str1 = $str1.$str2


php Array Operator

+ : 합친다

== : 키/값이 같은지

=== : 완전히 동일한지

!=, <> : 다른지

!== : 완전히 다른지


php 반복문

c와 모두 똑같음

foreach($array as $value) : $array의 값이 순서대로 $value에 할당된다


php 함수

function FUCTIONNAME(){}


php Array

count() : return length of array

associative array loop : foreach($age as $x => $x_value)


php Array Sort

sort() : ascending

rsort() : descending

asort() : associative, ascending, value

ksort() : associative, ascending, key

arsort() :     ", descending

krsort() :     ", descending


php Superglobals

$GLOBALS[index] : stores all global variables

$_SERVER[index] : holds info about headers, paths, scripts

$_REQUEST[index] : HTML form에서 데이터를 수집할 때

$_POST : method="post"를 이용한 HTML form에서 데이터를 수집할 때

$_GET : method='get'를 이용한 HTML form에서 데이터를 수집할 때, url을 통해 보내진 데이터도 수집한다


$_SERVER['PHP_SELF']현재 실행되고 있는 스크립트의 파일명

$_SERVER['REQUESTED_METHOD'] : http request방식, "POST" 또는 "GET"



htmlspecialchars()

특정한 문자들을 html 엔터티로 바꿔준다

$_SERVER['PHP_SELF'] exploit을 방지하는데 쓰인다

http://medusa.kr/extra/phpFn/function/htmlspecialchars.html?PHPSESSID=3ff598481d19c76787cb5231bdfabeaf



PHP로 form data validate하기

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

trim : 불필요한 문자를 지워줌

stripslashes : 백슬래시를 지워줌



php multidimensional array

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );


php date & time

date(format, timestamp)

format = "Y/M/d", required

timestamp = optional, default is current time


php include & require

text/code/markup 을 복사해놓는다

include : file이 없어도 계속 진행

require : file이 없으면 fatal error

<div class="menu">
<?php include 'menu.php';?>
</div>



php file handling

readfiles(filename) : 파일을 읽고 연다

fopen(filename, mode) : 파일을 연다

fread(file object, size) : 파일을 size만큼 읽는다

fgets(file object) : 한 줄 읽는다

fgetc(file object) : 한 글자 읽는다

fwrite(file object, string) : string을 쓴다

fclose(file object) : 파일을 닫는다

feof(file object) : 끝에 도달하면 1반환, 아니면 0


php file upload

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


php cookie

setcookie(name, value, expire, path, domain, secure, httponly);

delete cookie : set expire date in the past


php session

session variable이란? 하나의 유저에 대한 정보를 가지고 모든 페이지에서 유효하다(브라우저가 종료될 때까지)

쿠키처럼 컴퓨터에 저장 되지는 않는다. 대신 하나의 유저에 대해 User-key를 세팅하고 다른 페이지에서 세션이 열리면 키를 비교하고 일치하면 기존의 세션, 일치하지 않으면 새로운 세션을 연다


<?php

session_start();

?>

모든 html태그 앞에 선언되어야 한다


session variable 은 $_SESSION['index']에 저장된다

session_unset() : 세션의 내용을 초기화한다

session_destroy() : 세션을 끈다


session과 cookie의 차이 => http://genesis8.tistory.com/220



php filter

validate : proper form인지 검증

sanitize : 불필요한 문자를 제거

filter_var($var, FILTER_VALIDATE_XXX or FILTER_SANITIZE_XXX, OPTION)

OPTION 에는 범위, 요구조건에 대한 정보가 들어감

filter ref : http://www.w3schools.com/php/php_ref_filter.asp



http 프로토콜

1. 클라이언트(내 컴퓨터)가 서버(naver.com, google.com 등)에 connect 한다

2. connect 되었다면 클라이언트가 html 문서를 서버에게 요청한다

3. 서버는 클라이언트에게 html 문서를 전송한다



URL(uniform resource locator)

네트워크 상에서 정보자원의 위치와 종류를 정의한다


http://yum2yum2.tistory.com/admin/entry/post/?id=13


1. http://. =>  http는 프로토콜, 프로토콜 뒤에 :, 뒤에 도메인이나 아이피 주소가 온다면 //

2. yum2yum2.tistory.com. =>  yum2yum2.tistory.com이라는 도메인을 가진 하나의 컴퓨터(서버)

3. /admin/entry/post/. =>  서버안의 디렉토리

4./자원  =>  자원이 생략되면 index.html 또는 default.html

5.?id=13. =>  ?뒤에는 매개변수가 온다 매개변수 끼리는 &으로 구별한다.



http Request

1.GET = url을 이용하여 요청 데이터에 대한 인수를 서버에 전달, 보안성 없음

2.POST = 헤더를 통해 전달하므로 다소 느리다 보안성을 갖추고 있음



GET : form 데이터를 url 끝에 붙여서 눈에 보이게 전송

POST : 내부적으로 헤더를 통해 전송



































'공부 > ' 카테고리의 다른 글

Javascript  (0) 2017.01.29
webhacking.kr 26 url encoding  (0) 2017.01.28
Webhacking.kr 24 쿠키값 변조  (0) 2017.01.28
HTML  (0) 2017.01.27
XSS (Cross site scripting)  (0) 2017.01.27
Comments