티스토리 뷰

php

내가 보려고 만든 php 정리

2023. 4. 26. 19:02

클라이언트 기본 틀

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=0.9">
  <title>제목</title>

  <!--  미리보기 -->
  <meta property="og:title" content="제목">
  <meta property="og:url" content="http://www.naver.com">
  <meta property="og:type" content="website">
  <meta property="og:image" content="http://ex.co.kr/img/ex.png" />
  <meta property="og:description" content="설명">

  <!-- jquery 받아오자 -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <!-- js 받아오자 -->
  <script src="aaa.js"></script>
  <!-- css 받아오자 -->
  <link rel="stylesheet" href="aaa.css">
  <!-- Lottie 받아오자 -->
  <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
</head>

<body>

  <h1>My first PHP page</h1>

  <?php
  echo "Hello World!";
  ?>

</body>

</html>

 
서버 기본 틀

<?php
$connect = mysqli_connect("127.0.0.1", "root", "비번", "디비명");
mysqli_query($connect, "utf8mb4");  // 데이터타입 이모지 나오게

if (!$connect) {
  die("Connection failed: " . mysqli_connect_error());    // 메시지를 출력하고 프로그램 종료
}

$text = mysqli_real_escape_string($connect, $_POST['text']);

$sql = "INSERT INTO my_table (c1, c2) VALUES ('$v1', '$v2')";
$sql = "DELETE FROM my_table WHERE c1 = '$v1'";
$sql = "UPDATE my_table SET c1 = 0, c2 = '$v2' WHERE c3 = '$v3' AND c4 > 10";

if (mysqli_query($dbconn, $sql)) {   // 쿼리 실행하고 조건문
  echo "true";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($dbconn);
}

$sql = "SELECT c1, c2 FROM my_table WHERE c1 = '$v1' AND c2 = '$v2' ORDER BY c1 DESC";
$result = mysqli_query($dbconn, $sql);

$array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $array[] = $row;
}
$jsonData = json_encode($array, JSON_UNESCAPED_UNICODE);
echo $jsonData;

mysqli_close($connect); // DB 연결 끊기

 
오류일때 인셉션 발생시키기

throw new Exception("시그니쳐 오류");   // 오류일때 인셉션 발생시키기

 
다른 php파일 불러오기

require("../server/login.php"); // 다른 php파일 불러오기
//Include : 다른 PHP파일을 불러올때 사용 실패시 경고만 하고 실행
//include_once : 파일을 불러올때 1번만 로드하게 됨
//require :다른 PHP파일을 불러올때 사용 에러시 더 염격하게 처리 실패시 중단
//require_once : 파일을 불러올때 1번만 로드하게 됨

 
구문

<?php
// PHP code goes here
?>

 
대소문자 구분 안함(변수는 구분함)

ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";

 
코멘트(주석)

// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;	// 10

 
변수 생성

$txt = "Hello world!";
$x = 5;
$y = 10.5;

변수는 짧은 이름(예: x 및 y) 또는 더 설명적인 이름(age, carname, total_volume)을 가질 수 있습니다.
PHP 변수에 대한 규칙:

  • 변수는 부호로 시작 $하고 뒤에 변수 이름이 옵니다.
  • 변수 이름은 문자 또는 밑줄 문자로 시작해야 합니다.
  • 변수 이름은 숫자로 시작할 수 없습니다.
  • 변수 이름에는 영숫자와 밑줄(Az, 0-9 및 _ )만 포함할 수 있습니다.
  • 변수 이름은 대소문자를 구분합니다( $age및 $AGE두 개의 다른 변수임).

 
변수 출력

$txt = "W3Schools.com";
echo "I love $txt!";	// I love W3Schools.com!
$txt = "W3Schools.com";
echo "I love " . $txt . "!";	// I love W3Schools.com!

 
변수 합

$x = 5;
$y = 4;
echo $x + $y;	// 9

 
변수 범위

  • local
  • global
  • static

뭐 없이 사용하기

$x = 5; // global scope
function myTest() {
  // using x inside this function will generate an error
  echo "x: $x";	// x:
} 
myTest();
echo "x: $x";	// x: 5
function myTest() {
  $x = 5; // local scope
  echo "x: $x";
} 
myTest();
// using x outside the function will generate an error
echo "x: $x";

 
global 사용하기

$x = 5;
$y = 10;
function myTest() {
  global $x, $y;
  $y = $x + $y;
}
myTest();
echo $y;	// 15
$x = 5;
$y = 10;
function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;	// 15

 
static 사용하기

function myTest() {
  static $x = 0;
  echo $x;
  $x++;
}
myTest();	// 0
myTest();	// 1
myTest();	// 2

 
echo(출력)

echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";

 
변수 출력

$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";	// Learn PHP
echo "Study PHP at " . $txt2 . "<br>";	// Study PHP at W3Schools.com
echo $x + $y;	// 9

 
데이터 타입

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

String 문자열 출력

$x = "Hello world!";
echo $x;	// Hello world!

 
Integer 정수 출력

$x = 5985;
var_dump($x);	// int(5985)

 
Float 실수 출력

$x = 10.365;
var_dump($x);	// float(10.365)

 
Boolean 참 거짓

$x = true;
$y = false;

 
Array 배열

$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
//array(3) {
//  [0]=>
//  string(5) "Volvo"
//  [1]=>
//  string(3) "BMW"
//  [2]=>
//  string(6) "Toyota"
//}

 
Object 개체

class Car {
  public $color;
  public $model;
  public function __construct($color, $model) {
    $this->color = $color;
    $this->model = $model;
  }
  public function message() {
    return "My car is a " . $this->color . " " . $this->model . "!";
  }
}

$myCar = new Car("black", "Volvo");
echo $myCar -> message();	// My car is a black Volvo!
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();	// My car is a red Toyota!

 
null

$x = null;
var_dump($x);	// NULL

 
문자열 길이

echo strlen("Hello world!");	// 12

 
문자열의 단어 개수 세기

echo str_word_count("Hello world!");	// 2  영어만 세줌

 
문자열 반전

echo strrev("Hello world!");	// !dlrow olleH

 
문자열 내에서 텍스트 검색

echo strpos("Hello world!", "world");	// 6

 
문자열 내의 텍스트 바꾸기

echo str_replace("world", "Dolly", "Hello world!");	// Hello Dolly!

 
데이터 유형이 정수인지 확인

$x = 5985;
var_dump(is_int($x));	// bool(true)

$x = 59.85;
var_dump(is_int($x));	// bool(false)

 
데이터 유형이 실수인지 확인

$x = 10.365;
var_dump(is_float($x));	// bool(true)

 
변수가 숫자인지 확인

$x = 5985;
var_dump(is_numeric($x));	// bool(true)

echo "<br>";

$x = "5985";
var_dump(is_numeric($x));	// bool(true)

echo "<br>";

$x = "59.85" + 100;
var_dump(is_numeric($x));	// bool(true)

echo "<br>";

$x = "Hello";
var_dump(is_numeric($x));	// bool(false)

 
문자열과 실수를 정수로 변환

// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;	// 23465

echo "<br>";

// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;	// 23465

 
파이

echo(pi());	// 3.1415926535898

 
인수 목록에서 가장 높거나 낮은 수 찾기

echo(min(0, 150, 30, 20, -8, -200));  // -200
echo(max(0, 150, 30, 20, -8, -200));  // 150

 
절대 값

echo(abs(-6.7));	// 6.7

 
제곱근

echo(sqrt(64));  // 8

 
반올림

echo(round(0.60));  // 1
echo(round(0.49));  // 0

 
난수(랜덤)

echo(rand(10, 100));	// 10~100에서 랜덤

 
대문자를 구분하는 상수 (변수와 달리 변하지 않는 값)

define("KEY", "value");
echo KEY;	// value

 
대문자를 구분하지 않는 상수

define("KEY", "value", true);
echo key;	// value

 
상수 배열

define("cars", [
  "Alfa Romeo",
  "BMW",
  "Toyota"
]);
echo cars[0];	// Alfa Romeo

 
상수는 전역적

define("KEY", "value");
function myTest() {
  echo KEY;
}
myTest();	// value

 
산술 연산자

$x = 10;  
$y = 6;
echo $x + $y;	// 16
$x = 10;  
$y = 6;
echo $x - $y;	// 4
$x = 10;  
$y = 6;
echo $x * $y;	// 60
$x = 10;  
$y = 6;
echo $x / $y;	// 1.6666666666667
$x = 10;  
$y = 6;
echo $x % $y;	// 4
$x = 10;  
$y = 3;
echo $x ** $y;	// 1000

 
할당 연산자(나머지도 아래처럼)

$x = 20;  
$x += 100;
echo $x;	// 120

 
조건부 할당 연산자

// if empty($user) = TRUE, set $status = "anonymous"
echo $status = (empty($user)) ? "anonymous" : "logged in";	// anonymous
echo("<br>");

$user = "John Doe";
// if empty($user) = FALSE, set $status = "logged in"
echo $status = (empty($user)) ? "anonymous" : "logged in";	// logged in
// variable $user is the value of $_GET['user']
// and 'anonymous' if it does not exist
echo $user = $_GET["user"] ?? "anonymous";	// anonymous
echo("<br>");
  
// variable $color is "red" if $color does not exist or is null
echo $color = $color ?? "red";	// red

 
조건문 if

$t = date("H");

if ($t < "10") {
  echo "Have a good morning!";
} elseif ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}

 
스위치 switch

$favcolor = "red";

switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";	// 출력됨
    break;
  case "blue":
    echo "Your favorite color is blue!";
    break;
  case "green":
    echo "Your favorite color is green!";
    break;
  default:
    echo "Your favorite color is neither red, blue, nor green!";
}

 
반복문 while

$x = 1;

while($x <= 5) {
  echo "The number is: $x <br>";
  $x++;
}	// 1~5까지 출력

 
반복문 do while

$x = 6;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);	// 6만 출력 조건이 안 돼도 1회는 실행

 
반복문 for

for ($x = 0; $x <= 10; $x++) {
  echo "The number is: $x <br>";
}	// 0~10

 
반복문 foreach

$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
  echo "$value <br>";
}	// 하나씩 출력됨
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {
  echo "$x = $val<br>";
}
// Peter = 35
// Ben = 37
// Joe = 43

 
반복문 중단, 계속

break;	// 중단
continue;	// 이번만 중단하고 다음 거 이어서 함

 
함수

function writeMsg() {
  echo "Hello world!";
}
writeMsg(); // call the function

 
함수 인수(매개변수)

function familyName($fname, $year) {
  echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");

 
php는 느슨한 언어

function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");	// 10

 
느슨하지 않게 하기 (첫줄에 추가)

declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");

 
기본 인수 값

declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
  echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);

 
값 반환

function sum(int $x, int $y) {
  $z = $x + $y;
  return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);

 
반환 유형 선언

function addNumbers(float $a, float $b) : float {
  return $a + $b;
}
echo addNumbers(1.2, 5.2);

 
참조로 인수 전달

function add_five(&$value) {
  $value += 5;
}

$num = 2;
add_five($num);
echo $num;	// 7

 
배열

$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
// I like Volvo, BMW and Toyota.

 
배열의 길이 얻기

$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);	// 3

 
인덱스 배열을 통한 루프

$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {
  echo $cars[$x];
  echo "<br>";
}

 
연관 배열

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";	// Peter is 35 years old.

 
연관 배열을 통한 루프

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
}
// Key=Peter, Value=35
// Key=Ben, Value=37
// Key=Joe, Value=43

 
2차원 배열

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);
  
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
// Volvo: In stock: 22, sold: 18.
// BMW: In stock: 15, sold: 13.
// Saab: In stock: 5, sold: 2.
// Land Rover: In stock: 17, sold: 15.

 
2차원 배열 for문으로 출력하기

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);
    
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}

 
배열에 대한 정렬 함수

  • sort()- 배열을 오름차순으로 정렬
  • rsort()- 배열을 내림차순으로 정렬
  • asort()- 값에 따라 연관 배열을 오름차순으로 정렬
  • ksort()- 키에 따라 연관 배열을 오름차순으로 정렬
  • arsort()- 값에 따라 연관 배열을 내림차순으로 정렬
  • krsort()- 키에 따라 연관 배열을 내림차순으로 정렬
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);

 
완전 전역 변수

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

$GLOBALS
스크립트의 어디에서나 전역 변수에 액세스하는 데 사용되는 PHP 슈퍼 전역 변수입니다(또한 함수 또는 메서드 내에서).

$x = 75;
$y = 25;
 
function addition() {
  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
 
addition();
echo $z;	// 100

 
$_SERVER
헤더, 경로 및 스크립트 위치에 대한 정보를 보유하는 PHP 슈퍼 전역 변수입니다.
참고: https://www.w3schools.com/php/php_superglobals_server.asp

echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];

 
$_REQUEST
양식을 제출한 후 데이터를 수집하는 데 사용되는 PHP 슈퍼 전역 변수입니다.

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = htmlspecialchars($_REQUEST['fname']);
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>

 
$_POST
method="post"로 HTML 양식을 제출한 후 양식 데이터를 수집하는 데 사용되는 PHP 슈퍼 전역 변수입니다. $_POST는 또한 변수를 전달하는 데 널리 사용됩니다.

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>

 
$_GET
method="get"으로 HTML 양식을 제출한 후 양식 데이터를 수집하는 데 사용되는 PHP 슈퍼 글로벌 변수입니다.
$_GET은 또한 URL로 전송된 데이터를 수집할 수 있습니다.

<!DOCTYPE html>
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>

<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>

 
정규식
참고: https://www.w3schools.com/php/php_regex.asp
대소문자를 구분하지 않고 검색한다는 정규식 찾으면 1 못 찾으면 0

$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // 1

 
위처럼 찾는 거지만 모두 찾는 정규식

$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);	// 4개라서 4 출력

 
찾아서 바꾸기

$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);	// Visit W3Schools!

 
이어서 할 곳
https://www.w3schools.com/php/php_forms.asp

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/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
글 보관함