1. PHP의 데이터 타입
: 타입이란 프로그램에서 다룰 수 있는 값의 종류를 의미한다.
1) 정수(integer)
: 정수는 부호를 가지는 소수부가 없는 수를 의미한다.
PHP에서 정수의 표현범위는 운영체제에 따라 달라지며,
64비트 운영체제를 기준으로 -2,147,483,648 ~ + 2,147,483,647 사이의 값을 가진다.
2) 실수(float)
: 실수는 소수부나 지수부를 가지는 수를 의미하며, 정수보다 더 넓은 표현 범위를 가진다.
3) 불리언(boolean)
: 불리언은 참(true)과 거짓(false)을 표현한다.
PHP에서 불리언은 상수인 true, false를 사용해 나타내며, 대소문자를 구분하지 않는다.
따라서 true, false 값들 이외에 모든 값을 true로 인식하고 0은 false로 인식된다.
4) 문자열(string)
: 문자열은 일련의 연속된 문자(character)들의 집합을 의미한다.
PHP에서 문자열 리터럴은 큰따옴표(" ")나 작은따옴표(' ')로 감싸서 표현한다.
** var_dump() : 변수의 정보를 출력
** 8_datatype.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>자료형</title>
</head>
<body>
<h2>자료형</h2>
<?php
var_dump((bool)false);
echo "<br>";
var_dump((int)1);
echo "<br>";
var_dump("안녕하세요"); // php에서는 한글 3byte
echo "<br>";
$num = 10;
var_dump($num);
?>
</body>
</html>
2. PHP의 연산자
1) 산술 연산자 : +(덧셈), -(뺄셈), *(곱셈), /(나눗셈), %(나머지), **(제곱)
2) 대입 연산자 : =, +=, -=, *=, /=, %=, .=(연결)
3) 증감 연산자 : ++, --
4) 비교 연산자 : ==, ===, !=, !==, <, >, <=, >=
5) 논리 연산자 : &&, ||, !
6) 비트 연산자 : &, |, ^, ~, <<, >>
7) 삼항 연산자
조건식 ? 반환값1 : 반환값2;
조건식이 true면 반환값1, false면 반환값2
8) 문자열 연산자 : PHP에서는 문자열을 연결할 경우 .(점)을 사용한다.
** 1_student.php, 1_student_ok.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>학생 성적 프로그램</title>
</head>
<body>
<h2>학생 성적 프로그램</h2>
<form method="post" action="1_student_ok.php">
<p><label>학번 : <input type="text" name="hakbun"></label></p>
<p><label>이름 : <input type="text" name="name"></label></p>
<p><label>국어점수 : <input type="text" name="kor"></label></p>
<p><label>수학점수 : <input type="text" name="math"></label></p>
<p><label>영어점수 : <input type="text" name="eng"></label></p>
<p><input type="submit" value="확인"></p>
</form>
</body>
</html>
<?php
$hakbun = $_POST['hakbun'];
$name = $_POST['name'];
$kor = $_POST['kor'];
$math = $_POST['math'];
$eng = $_POST['eng'];
$tot = $kor + $math + $eng; // 총점
$avg = $tot / 3; // 평균
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>학생 성적 프로그램</title>
</head>
<body>
<h2><?php
echo "<h3>".$name."님의 성적표</h3>";
?></h2>
<p>학번 : <?=$hakbun?></p>
<p>이름 : <?=$name?></p>
<p>국어 : <?=$kor?>점</p>
<p>수학 : <?=$math?>점</p>
<p>영어 : <?=$eng?>점</p>
<p>총점 : <?=$tot?>점</p>
<p>평균 : <?=$avg?>점</p>
</body>
</html>
3. 제어문
1) 조건문
① if문 : if문, if else문, if else if문
** 2_student.php, 2_student_ok.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>학생 성적 프로그램</title>
</head>
<body>
<h2>학생 성적 프로그램</h2>
<form method="post" action="2_student_ok.php">
<p><label>학번 : <input type="text" name="hakbun"></label></p>
<p><label>이름 : <input type="text" name="name"></label></p>
<p><label>국어점수 : <input type="text" name="kor"></label></p>
<p><label>수학점수 : <input type="text" name="math"></label></p>
<p><label>영어점수 : <input type="text" name="eng"></label></p>
<p><input type="submit" value="확인"></p>
</form>
</body>
</html>
<?php
$hakbun = $_POST['hakbun'];
$name = $_POST['name'];
$kor = $_POST['kor'];
$math = $_POST['math'];
$eng = $_POST['eng'];
$tot = $kor + $math + $eng; // 총점
$avg = $tot / 3; // 평균
$hak = "";
if($avg >= 90) {
$hak = "A학점";
} else if($avg >= 80) {
$hak = "B학점";
} else if($avg >= 70) {
$hak = "C학점";
} else if($avg >= 60) {
$hak = "D학점";
} else {
$hak = "F학점";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>학생 성적 프로그램</title>
</head>
<body>
<h2><?php
echo "<h3>".$name."님의 성적표</h3>";
?></h2>
<p>학번 : <?=$hakbun?></p>
<p>이름 : <?=$name?></p>
<p>국어 : <?=$kor?>점</p>
<p>수학 : <?=$math?>점</p>
<p>영어 : <?=$eng?>점</p>
<p>총점 : <?=$tot?>점</p>
<p>평균 : <?=$avg?>점</p>
<p>학점 : <?=$hak?></p>
</body>
</html>
[문제1]
3_login.php 파일에서 아이디, 비밀번호를 입력받아 로그인 테스트 프로그램을 만들어보자!
(단, 아이디는 "admin", 비밀번호는 "1234"이면 로그인, 아니면 로그인 실패를 출력)
** [내코드] 3_login.php, 3_login_ok.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
</head>
<body>
<h2>로그인</h2>
<form method="post" action="3_login_ok.php">
<p><label>아이디 : <input type="text" name="userid"></label></p>
<p><label>비밀번호 : <input type="password" name="userpw"></label></p>
<p><input type="submit" value="로그인"></p>
</form>
</body>
</html>
<?php
$userid = $_POST['userid'];
$userpw = $_POST['userpw'];
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
</head>
<body>
<?php
if($userid == 'admin' && $userpw == '1234') {
echo "<p>로그인 성공<p><p><b>".$userid."</b> 님 환영합니다.<p>";
} else {
echo "<p>로그인 실패<br>아이디 또는 비밀번호를 확인하세요<p>"
."<script>alert('다시 3_login.php로 돌아갑니다.');location.href='./3_login.php';</script>";
}
?>
<p></p>
</body>
</html>
** [강사님 코드] 3_login_teacher.php, 3_login_ok_teacher.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
</head>
<body>
<h2>로그인</h2>
<form method="post" action="3_login_ok_teacher.php">
<p><label>아이디 : <input type="text" name="userid"></label></p>
<p><label>비밀번호 : <input type="password" name="userpw"></label></p>
<p><input type="submit" value="로그인"></p>
</form>
</body>
</html>
<?php
$userid = $_POST['userid'];
$userpw = $_POST['userpw'];
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
</head>
<body>
<?php
if($userid == "admin" && $userpw == "1234") {
?>
<h2>로그인 성공!</h2>
<p><?=$userid?>님 환경합니다.</p>
<?php
} else {
?>
<script>
alert("로그인 실패!\n아이디 또는 비밀번호를 확인하세요.");
history.back();
</script>
<?php
}
?>
</body>
</html>
② switch문
2) 반복문
① while문, do ~ while문
** 4_maketable.php, 4_maketable_ok.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>테이블 만들기</title>
</head>
<body>
<h2>테이블 만들기</h2>
<p>몇 개의 테이블을 만들까요?</p>
<form method="get" action="./4_maketable_ok.php">
<p><input type="number" name="count" value="1" min="1" max="100">개</p>
<p><input type="submit" value="확인"></p>
</form>
</body>
</html>
<?php
$count = $_GET['count'];
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>테이블 만들기</title>
<style>
table { border: 3px solid red; }
td { text-align: center; width: 300px; border: 3px solid gold; }
</style>
</head>
<body>
<h2>테이블 만들기</h2>
<table>
<?php
$i = 1;
while($i <= $count) {
?>
<tr>
<td><?=$i?>번째 셀</td>
</tr>
<?php
$i++;
}
?>
</table>
</body>
</html>
② for문
4. 배열
1) 배열 만들기
$배열명 = array(요소1, 요소2, ... );
[예] $arr = array("김사과", "반하나", "오렌지");
2) 배열에 데이터 넣기
$배열명[인덱스] = 값;
[예] $arr[0] = "이메론";
3) 배열 순회하기
foreach(배열명 as 변수) {
배열의 요소의 개수만큼 반복할 문장;
}
** 5_array.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>배열</title>
</head>
<body>
<h2>배열</h2>
<?php
$arr = array("김사과", "오렌지", "이메론", "반하나");
foreach($arr as $name) {
echo "배열의 현재 값은 {$name}입니다.<br>";
}
?>
</body>
</html>
5. 함수
: 하나의 특별한 목적의 작업을 수행하도록 설계된 독립적인 블록을 의미한다.
function 함수명(매개변수1, 매개변수2, ... ) {
함수가 호출 되었을 때 실행할 코드;
}
** 6_function.php
<?php
function print_string() {
echo "<p>안녕하세요. PHP!</p>";
}
function print_sum($x, $y) {
echo "<p>{$x} + {$y} = ".($x + $y)."</p>";
}
function get_sum($x, $y) {
return $x + $y;
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>함수</title>
</head>
<body>
<h2>함수</h2>
<?php
print_string();
print_sum(10, 3);
$result = get_sum(10, 5);
echo "10 + 5 = {$result}";
?>
</body>
</html>
6. 내장함수(문자열 함수)
strlen() : 전달 받은 문자열의 길이를 반환한다.
strcmp() : 전달 받은 두 개의 문자열을 서로 비교한다.
첫번째 인수의 문자열이 두번째 인수의 문자열보다 크면 양수를, 작으면 음수를 반환한다.
또한 두 문자열이 같으면 0을 반환한다.
strstr() : 해당 문자열에서 전달 받은 문자열과 처음으로 일치하는 부분을 찾는다.
일치하는 부분이 존재하면 처음으로 일치하는 부분을 포함한 이후 모든 문자를 반환한다.
strpos() : 해당 문자열에서 전달 받은 문자열과 처음으로 일치하는 부분을 시작 인덱스를 반환한다.
substr() : 해당 문자열에서 특정 인덱스부터 전달받은 길이만큼의 일부분을 추출하여 반환한다.
전달받은 인덱스가 양수인 경우에는 해당 문자열의 끝까지를 반환한다.
만약 전달받은 인덱스가 음수라면 해당 문자열 끝부터 전달받은 음수의 절댓값만큼의 문자열을 반환한다.
strtolower() : 전달받은 문자열의 모든 문자를 소문자로 바꿔준다.
strtoupper() : 전달받은 문자열의 모든 문자를 대문자로 바꿔준다.
explode() : 특정 문자를 기준으로 전달 받은 문자열을 나눠서 하나의 배열로 반환한다.
str_replace() : 해당 문자열에서 전달 받은 문자열을 모두 찾은 후에, 찾은 문자열을 대체 문자열로 교체한다.
substr_replace() : 해당 문자열에서 특정 위치의 문자들을 대체 문자열로 교체한다.
** 7_stringfunction.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>문자열 함수</title>
</head>
<body>
<h2>문자열 함수</h2>
<?php
$str1 = "abcd1234";
$str2 = "한글로 표현한 문자열";
echo "strlen(str) : ".strlen($str1)."<br>"; // 8 : 영문자, 숫자, 특수문자 1byte
echo "strlen(str) : ".strlen($str2)."<br>"; // 29 : 한글 3byte
echo "<br>";
echo strcmp("abc", "ABC")."<br>"; // 1
echo strcmp("2", "10")."<br>"; // 1
echo strcmp("10", "10")."<br>"; // 0
echo "<br>";
echo strstr($str1, "cd")."<br>";
echo strpos($str1, "abc")."<br>"; // 0
echo strpos($str1, "12")."<br>"; // 4
echo "<br>";
echo substr($str1, 3)."<br>"; // d1234
echo substr($str1, -3)."<br>"; // 234
echo substr($str1, 1, 5)."<br>"; // bcd12
echo substr($str1, 1, -3)."<br>"; // bcd1
echo "<br>";
echo strtolower("Hello, Php!")."<br>";
echo strtoupper("Hello, Php!")."<br>";
echo "<br>";
$str3 = "Hello, PHP, Hello, World!";
$arr = explode(",", $str3); // "Hello"->$arr[0], "PHP"->$arr[1], "Hello"->$arr[2], "World!"->$arr[3]
foreach($arr as $word) {
echo $word."<br>";
}
echo "<br>";
echo str_replace("o", "*", $str3)."<br>";
echo substr_replace($str3, "*", 2)."<br>";
echo substr_replace($str3, "*", -2)."<br>";
echo substr_replace($str3, "*", 2, 4)."<br>";
?>
</body>
</html>
7. 쿠키
: 웹 사이트에 접속할 때 서버에 의해 사용자의 컴퓨터에 저장되는 정보를 의미한다.
웹 사이트는 저장된 사용자의 정보를 클라이언트 측의 컴퓨터에 남겨서 필요할 때마다 재사용한다.
쿠키의 데이터 형태는 key와 value로 구성되고 string으로만 이루어져 있다.
4KB이상 저장할 수 없다.
1) 쿠키를 생성하는 방법
setcookie(쿠키이름, 값, 만료시간, 저장위치, 도메인정보, 프로토콜);
2) 쿠키를 읽어오는 방법
변수이름 = $_COOKIE[쿠키이름];
3) 쿠키를 삭제하는 방법
쿠키 만료시간을 0 또는 과거시간으로 변경해주면 삭제된다.
** time() : 현재 시간을 반환한다.
** isset() : 데이터가 존재하는지 여부(true, false)를 판단한다.
** 8_cookie1.php
<?php
setcookie("userid", "apple", time() + (60 * 3), "/"); // 3분 후 만료되는 쿠키 생성
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>쿠키 - 1</title>
</head>
<body>
<h2>쿠키 - 1</h2>
</body>
</html>
** 9_cookie2.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>쿠키 - 2</title>
</head>
<body>
<h2>쿠키 - 2</h2>
<?php
if(!isset($_COOKIE['userid'])) { // 쿠키가 존재하지 않을때
echo "<p>쿠키가 존재하지 않습니다.</p>";
} else { // 쿠키가 존재할때
echo "<p>쿠키가 존재합니다.</p>";
echo "<p>저장된 쿠키의 값 : ".$_COOKIE['userid']."</p>";
}
?>
</body>
</html>
** 10_login.php, 10_login_ok.php, 10_logout.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
</head>
<body>
<?php
if(!isset($_COOKIE['id'])) { // 쿠키가 존재하지 않는지 확인
?>
<!-- 쿠키가 존재하지 않는다면 -->
<h2>로그인</h2>
<form method="post" action="./10_login_ok.php">
<p><label>아이디 : <input type="text" name="userid"></label></p>
<p><label>비밀번호 : <input type="password" name="userpw"></label></p>
<p><input type="submit" value="로그인"></p>
</form>
<?php
} else {
?>
<!-- 쿠키가 존재한다면 -->
<h2>로그인</h2>
<h3><?=$_COOKIE['id']?>님 환영합니다.</h3>
<p><a href="./10_logout.php">로그아웃</a></p>
<?php
}
?>
</body>
</html>
<?php
$userid = $_POST['userid'];
$userpw = $_POST['userpw'];
if($userid == "admin" && $userpw == "1234") {
setcookie("id", $userid, time() + (60 * 60 * 24), "/");
// location.href : 캐시가 남아있지 않음
echo "<script>alert('로그인 되었습니다.');location.href='10_login.php';</script>";
} else {
// history.back() : 캐시가 남음
echo "<script>alert('아이디 또는 비밀번호를 확인하세요.');history.back();</script>";
}
?>
<?php
setcookie("id", "", time()-10, "/");
?>
<script>
alert('로그아웃 되었습니다.');
location.href="./10_login.php";
</script>
'웹_프론트_백엔드 > 프론트엔드' 카테고리의 다른 글
2021.01.24 (0) | 2021.01.27 |
---|---|
2021.01.23 (0) | 2021.01.23 |
2021.01.16 (0) | 2021.01.16 |
2021.01.10 (0) | 2021.01.11 |
2020.09.27 (0) | 2020.09.29 |