091
[PHP] CSV 파일을 브라우저에 올리고 삭제하기 본문
728x90
01. CSV 파일을 브라우저에 올리고 삭제하기 -> 파일을 브라우저에 저장하는 건 아님
<?php
session_start(); //start the session
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> CSV </title>
</head>
<body>
<h2>Display a CSV file on the screen and delete it</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="csv_file" accept=".csv">
<button type="submit" name="upload"> Upload </button>
<button type="submit" name="remove"> Delete </button>
</form>
</body>
</html>
<?php
if(!isset($_SESSION['status'])){
$_SESSION['status'] = 0;
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['upload']) && isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK){
$tmp_name = $_FILES['csv_file']['tmp_name'];
$file_type = mime_content_type($tmp_name);
if(str_contains($file_type, 'text') || str_contains($file_type, 'csv')) {
echo "<h3> CSV 파일 내용 : </h3>";
echo "<table border='1' cellpadding='5'>";
if(($handle = fopen($tmp_name, "r")) !== false) {
while(($data = fgetcsv($handle)) !== false) {
echo "<tr>";
foreach($data as $cell) {
echo "<td>" . htmlspecialchars($cell) ."</td>";
}
echo "</tr>";
}
fclose($handle);
$_SESSION['status'] = 1;
} else echo "Failed to open the uploaded file.";
} else echo "<p style='color:red;'>Invalid file type. Only text or CSV files are allowed.</p>";
} else {
if($_SESSION['status'] !== 1) echo "<p style='color:red;'>File upload failed or no file was uploaded.</p>";
}
if(isset($_POST['remove'])){
if($_SESSION['status'] === 1){
echo "<p style='color:green;'>The file has been successfully deleted.</p>";
$_SESSION['status'] = 0;
} else echo "<mark>No file to delete.</mark>";
}
}
?>
- session.start() : 세션을 이용하여 서버에 값을 저장한 뒤 사용할 것이라서 호출해줍니다. 세션의 경우, 호출을 할 때 Set-Cookie 헤더(HTTP 응답 헤더)를 전송해서 세션ID를 클라이언트엘게 알려주는데 HTTP 헤더는 HTML 본문보다 무조건 먼저 보내야하기 떄문에 <html> 위에 작성해줍니다.
* 세션이란 : 웹 서버가 클라이언트의 상태를 일정 시간 동안 기억하도록 해주는 서버 측 저장 메커니즘입니다. HTTP는 비연결(stat
eless) 프로토콜이기 때문에, 매 요청마다 클라이언트를 새로운 사용자로 인식합니다. 클라이언트의 상태를 기억하기 위해 세션을 이용합니다. 세션은 슈퍼글로벌 배열 중 하나이며, 3가지 구성 요소로 이루어져있습니다. 구성 요소로는 세션 ID, 세션 저장소, 세션 데이터가 있습니다. 세션 ID를 쿠키를 통해 클라이언트에 저장해서 사용할 수 있는 구조로, 쿠키를 통신 수단으로 이용합니다. 기본적으로 20분동안 저장합니다.
728x90
'Programming Language > PHP' 카테고리의 다른 글
[PHP] CSV 파일을 브라우저에 올리고 서버에 파일 업로드하기 (0) | 2025.05.08 |
---|---|
[PHP] CSV 파일을 브라우저에 올리고 새로운 파일 만들기 (0) | 2025.05.08 |
[PHP] CSV 파일을 열어 브라우저에 출력하기 (0) | 2025.05.07 |
[PHP] DB와 연결해서 브라우저에 원하는 데이터 값 출력하기 - 심화 (6) | 2025.03.22 |
[PHP] DB와 연결해서 브라우저에 원하는 데이터 값 출력하기 - 기본 (3) | 2025.03.08 |