PHP 파일 업로드
페이지 정보

본문
PHP 파일 업로드 구현하기(1)
PC의 이미지 파일을 서버에 업로드 해서 결과를 확인 하는 기능을 구현해 보자.
서버에 업로드 되는 파일을 저장할 수 있는 디렉토리를 하나 만들자.
디렉토리 이름은 'uploads'라고 하자. 쉽게 이해하기 위해 간단히 만들어 보는 것이다.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
업로드 할 파일을 선택하는 웹페이지를 만들자. 파일을 선택하고 버튼을 누르면 upload.php를 실행되어 파일 업로드가 진행된다. method와 enctype에 유의하자.
<?php
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "<p>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</p>";
echo "<br><img src=/uploads/". basename( $_FILES["fileToUpload"]["name"]). ">";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
}
}
?>
선택한 파일의 확장자를 체크하고 지정된 서버의 디렉토리에 파일을 업로드 한다.
서버에 파일이 올라가 있는 것과 그 결과를 확인 할 수 있다.
PHP + Mysql 파일 업로드 구현하기(2)
앞에서는 단순히 PHP를 이용한 파일 업로드 구현이었다.
이번에는 Mysql에 이미지 정보를 기록하는 예제를 만들어 보자.
보통 앞 예제 처럼 이미지를 서버에 업로드 하고 그 정보들, 단순 텍스트들만 DB에 저장하는 방식을 사용한다고 한다.
결국 2단계를 거쳐 이미지를 업로드 한다는 것이다.
이미지를 서버에 올리는 작업과 그 정보를 데이터베이스에 기록하는 단계이다.
앞 예제에 데이터베이스 기록하는 단계를 추가해 보기로 하자.
<?php
create table images (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
filename varchar(100) not null,
imgurl varchar(512) not null,
size int not null
)
?>
먼저 이미지 데이터를 저장할 table를 만들자.
DB구조는 프로젝트에 따라 설계를 해야 겠지만 여기서는 가능한 간단히 만들어 보자.
파일명과 나중에 <img 태그에 뿌려줄 url, 파일 사이즈정도 저장하기로 하자.
실상 url은 파일명이 있기때문에 나중에 가져다 사용할때 패스를 추가해서 사용하면 되기는 한데 일단 넣어서 만들어 보자.
이미지의 width, height등도 추가해 줄 수 있을것 같다.
<?php
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
/*database에 업로드 정보를 기록하자.
- 파일이름(혹은 url)
- 파일사이즈
- 파일형식
*/
$filename = $_FILES["fileToUpload"]["name"];
$imgurl = "http://웹서버주소/uploads/". $_FILES["fileToUpload"]["name"];
$size = $_FILES["fileToUpload"]["size"];
include_once 'config.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//images 테이블에 이미지정보를 저장하자.
$sql = "insert into images(filename, imgurl, size) values('$filename','$imgurl','$size')";
mysqli_query($conn,$sql);
mysqli_close($conn);
echo "<p>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</p>";
echo "<br><img src=/uploads/". basename( $_FILES["fileToUpload"]["name"]). " width=400>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
}
}
?>
업로드한 이미지의 필요한 정보를 취합해서 데이터베이스 insert 쿼리를 수행한다.
데이터베이스를 확인해 보면 정상적으로 저장되어 있는 것을 확인 할 수 있다.
이제 파일도 업로드 가능하고 데이터베이스에 데이터들도 정상적으로 기록이 되었다.
이제 DB에 있는 정보를 가져와서 페이지에 출력해 보도록 하자.
파일을 선택하는 페이지 하단에 이미지 목록을 출력해 보기로 하자.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<div style="width: 300px; margin:0 auto;">
<h3>이미지 파일 업로드 연습</h3>
<form action="upload.php" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<input type="submit" value="업로드" name="submit" style="margin: .9em">
</form>
</div>
<!-- database에서 이미지 목록을 가져 온다. -->
<ul>
<?php
include_once 'config.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
echo "연결실패! ".mysqli_connect_error();
}
$query = "SELECT * FROM images";
$result = mysqli_query($conn, $query);
while($data = mysqli_fetch_array($result)){
echo '<li style='float:left; margin: 2px;'>';
echo '<img src='.$data['imgurl'].' width=200><br>';
echo ($data['filename']);
echo '</li>';
}
mysqli_close($conn);
?>
</ul>
</body>
</html>
파일을 선택하는 시작 페이지를 수정하자.
하단에 현재 데이터베이스에 저장된 이미지들 정보를 가져와서 출력해 주자.
[php] 대용량 파일 업로드시 확인해야 하는 것
대용량(< 1GB) 정도의 데이터를 서버에 업로드 할 일이 있어서 php.ini를 만졌다.
그 과정에서 나온 것들 정리
★ 개발 환경
1. ajax로 php서버에 요청
2. post 요청
3. apache2사용
4. php7 사용
5. 서버1 macOS, 서버2 linux ubuntu (상관없을듯)
★ php.ini
upload_max_filesize = 1024M
post_max_filesize = 1024M # 위의 upload_max_filesize만 수정하고 이걸 수정하지 않으면 업로드 안됨
memory_limit = 1500M # 쫄려서 넉넉하게 줌
max_execution_time = 300 # 업로드 속도가 빠른 편이라 리미트를 넉넉하게 준다고 준거..
max_input_time = -1 # 입력 데이터 처리에 허용되는 최대 시간 (php 호출 시점 ~ 실행이 시작될 때까지 시간)
★ 그 외
php.ini에서 upload_max_filesize만 설정해주고 post_max_filesize 이건 설정하지 않았는데 (--...)
그 경우 서버 요청도 되고 서버 내의 프로세스가 자연스럽게 흘러가지만 파일 처리는 되지 않는다.
즉, $_FILES == [] 인 상태로 실행되고, $_SERVER != [] 인 상태로 실행되는 것...
요청은 되는데 파일이 없길래 ajax 단의 문제인줄 알았는데 php는 설정과 다른 요청의 엑세스를 차단하는건 아니었다. 그냥 파일만 안받고 실행.. 역시 php 다움...(-- )...
max_input_time은 얼마나 줘야할지 모르겠어서 일단은 리미트로 두었다.
PHP File Upload(파일업로드)
복사https://blog.naver.com/linux_master/221247647674
1.PHP 5 File Upload
- php로 쉽게 파일을 서버로 업로드 할 수 있으나 위험하기때문에 항상 파일업로드는 주의해야한다.
- 지금은 php.net에서 이함수를 찾을 수는 없으나 예전에 php파일에서 리눅스 명령을 실행할 수 있게 해주는 함수가 있었다
만약에 이파일을 게시판에서 업로드 시키고 브라우저 주소표시줄에서 리눅스 명령을 실행한다면 권한설정이 잘못된파일은 삭제,수정,다운로드 압축까지모든게 가능하며 이런 방식으로 해킹 할 수 있었다.
- 이러한 이유로 파일을 업로드 하는 부분은 매우신경을 써야하는 부분이다.
2.파일업로드 설정(php.ini)
- 먼저 php에서 파일이 업로드 될 수 있도록 설정한다.
- php.ini파일에서 file_uploads = On 으로 셋팅되어 있는지 확인한다.
- APM_Setup설치시에는 아래의 디렉토리에서 php.ini파일을 편집기로 열고 확인한다.
3.HTML폼을 생성한다.
- HTML폼은 업로드 하기 원하는 파일을 사용자에게 허락한다.
- 아래의 HTML폼에서 파일을 업로드하기 위해서 사용되는 규칙은 다음과 같다.
- 아래의 규칙이 없이는 파일이 업로드 되지 않는다.
1)method="post"가 되도록한다.
2)폼에는 다음 속성을 필요로한다.:enctype="multipart/form-data". 이것은 양식이 제출될때 content-type을 지정한다.
- 주목해야할 다른 것들 : <input>태그의 type="file"속성은 입력필드를 파일선택컨트롤로써 보여주고 입력컨트롤 옆에는 Browser버튼이 있다.
- 폼의 데이터는 upload.php파일로 보내진다.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
4.파일을 업로드할 php스크립트 만들기(upload_form.php)
- upload.php에는 파일을 업로드할 php코드를 포함하고 있다.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 진짜 이미지 파일인지 가짜 이미지 파일인지 체크
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "이미지 파일입니다 - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "이미지 파일이 아닙니다.";
$uploadOk = 0;
}
}
?>
- php스크립트 설명
1)$target_dir = "uploads/" : 파일이 위치할 디렉토리를 지정한다.
2)$target_file : 업로드될 파일의 경로를 지정한다.
3)$uploadOk=1 : 1로 초기화 되어있고 추후에 업로드가 완료되면 1 아니면 0으로 다시 초기화됨
4)$imageFileType : 소문자에서 파일의 파일확장자를 유지한다.
5)다음은 실제 이미지파일 여부를 체크한다.
6)upload.php파일이 위치한 곳에 upload디렉토리를 만든다 업로드된 파일은 이 upload디렉토리내에 저장된다.
5.파일의 존재여부 체크하기
- 약간의 제한할 부분을 추가한다.
- upload디렉토리내에 파일이 존재하는지를 체크하여 파일이 존재하지 않으면 에러메세지를 표시하고 $uploadOk 는 0으로 셋팅한다.
// 파일의 존재여부 체크하기
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
6.파일 사이즈의 제한
- 위의 html폼에서 파일 입력필드의 이름은 "fileToUpload"라고 이름이 지어져 있다.
- 우리가 체크하길 원하는 파일사이즈가 500kb보다 크면 에러메세지를 표시하고 $uploadOk 는 0 으로셋팅한다.
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "파일사이즈가 너무 큽니다.";
$uploadOk = 0;
}
7.파일타입의 제한
- 아래의 코드는 사용자에게 JPG,JPEG,PNG,GIF파일을 업로드 하도록 허가한다.
- 모든 다른 파일타입은 $uploadOk 가 0으로 셋팅되기 전에 에러메세지를 표시한다.
// 파일 타입체크
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "JPG, JPEG, PNG ,GIF 파일만 업로드 할 수 있습니다.";
$uploadOk = 0;
}
8.upload.php파일의 전체 소스코드
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 파일이 진짜 이미지인지 가짜 이미지인지 체크한다
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "파일이 이미지입니다 - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "파일이 이미지가 아닙니다.";
$uploadOk = 0;
}
}
// 파일이이미 존재하고 있는지 체크한다
if (file_exists($target_file)) {
echo "파일이 이미존재하고 있습니다.";
$uploadOk = 0;
}
// 파일사이즈를 체크한다
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "파일 사이즈가 너무 큽니다.";
$uploadOk = 0;
}
// 허용할 파일의 타입을 체크한다
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "JPG, JPEG, PNG & GIF 파일만 업로드 가능합니다.";
$uploadOk = 0;
}
// $uploadOk가 0 인지 체크한다
if ($uploadOk == 0) {
echo "파일이 업로드 되지 않았습니다.";
// 파일업로드 진행
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "업로드된 파일: ". basename( $_FILES["fileToUpload"]["name"]);
} else {
echo "업로드된 파일에 에러가 발생했습니다.";
}
}
?>
PHP - 파일 업로드/이미지 업로드
1. <form> 태그에서 enctype="multipart/form-data" 라는 애트리뷰트 추가
2. <input> 태그의 Type을 file로 설정
<form action="event.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myImage" id="myImage" value="" />
<input type="submit" value="등록"/>
</form>
event.php 페이지
<?php
$image = $_FILES['myImage'];
$imageName = "";
if($image != null)
{
$tmp_name = $_FILES["myImage"]["tmp_name"];
$Ext = substr(strrchr($_FILES['myImage']['name'], "."), 1);
$imageName = md5(rand() * time()) . ".$Ext";
if(move_uploaded_file($tmp_name, "./images/event/".$imageName)) {
}
chmod("./images/event/".$imageName, 0777);
}
?>
1. GET/POST가 아닌 $_FILES 형식으로 파라미터를 받은 다음
2. substr, strrchr 메서드를 사용하여 문자열 중 "." 마침표 문자 뒤 텍스트 분리 처리
3. 정수난수 * 현재 시간을 암호화 처리한 임의의 값을 만든 다음 뒤에 분리 처리한 확장자를 붙여서
새로운 이름의 파일명을 생성 후 지정된 경로에 파일 업로드 처리
4. 업로드된 파일에 chmod 명령어로 권한 처리
php 에서 파일 업로드를 하기 위해서는
1. 하나의 php 파일 안에서 html 과 php 를 작성하는 방법,
2. 하나의 html파일, 그리고 하나의 php 파일을 작성, 즉 2개의 파일을 작성하는 방법이 있습니다.
한번 만들고 보여주고 버리는 코드라면 1번이 편리하겠지만, 추후에 수정도 하며 유지보수를 하기 위해서는 2방법이 좋습니다.
이 글에서는 php를 이용하여 파일 업로드를 하는 방법을 적어보도록 하겠습니다.
우선 html 파일과 php 파일을 만들어 놓고 작업을 해도 좋고, 만들어가면서 작업해도 좋습니다.
1. upload.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="upload_ok.php">
<input type="file" name="file" required />
<input type="text" name="text" required />
<input type="submit" name="submit" >
</form>
</body>
</html>
-------------------------------------------------------------------------
위 소스를 보시면 빨간색으로 표시한 곳을 잘 확인해주셔야합니다.
1) http-equiv
html에서 '초기정보'를 나타내주는데 우리는 Content-type라고 선언을 해주면
이 파일이 저런 타입의 파일이구나 라고 말해주는것 같습니다.
2) content="text/html"
여기서는 우리의 파일종류가 text, 포맷형식이 html 라고 설명하는 정도라고 생각하시면 됩니다!
3) action="upload_ok.php"
현재 upload.html 은 보여주는 창이며 아무 기능이 없는 페이지임으로
작업을 하는 장소는 upload_ok.php 에서 작업을 할 것이다 라고 지정해주는 것입니다.
4) method="POST"
현재 페이지에서 upload_ok.php로 정보를 넘길때 POST를 사용하여 넘기겠다는 말입니다.
5) enctype="multipart/form-data"
파일이나 이미지를 서버로 전송할 경우 사용해야 하는 속성입니다.
이걸 쓰지 않으면 파일의 경로만 전송이 되며 내용은 전송이 되지 않습니다.
앞서서 파일을 업로드 할 수 있는 아주 아주 아주 간단한 html을 만들었습니다.
그렇다면 이제 php 페이지를 만들어 봅시다!
2. upload_ok.php
2-1(서버 연결 part)
=============================================================
<?php
$servername='서버이름';
$username='유저이름';
$password='비밀번호';
$dbname='DB이름';
$conn=new mysqli($servername, $username, $password, $dbname);
mysqli_query($conn, "set names utf8");
if($conn->connect_error){
die("Connetion error:" . $conn -> connect_error);
}
?>
--------------------------------------------------------------
이 부분은 서버에 php를 연결 시키는 부분입니다.
원하시면 이 부분만 따로 php 파일을 만들어 저장한 후 ("server.php" 로 저장했다고 가정)
<?php
include("server.php"); 혹은 require_once("server.php"); 이런 방식으로 연결을 시킬 수 있습니다.
이렇게 하면 굳이 일일이 저 코드들을 파일에 다 작성하지 않아도 된다는 것!
2-2(post 부분)
--------------------------------------------------------------
<?php
if (isset($_POST['submit'])){
$name=$_POST['text'];
$file=$_FILES['file']['name'];
$dir="./"
$upfile=$dir.$name;
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
if(!move_uploaded_file($_FILES['file']['tmp_name'],$upfile))
{
echo "upload error_file1";
exit;
}
}else{ echo "upload error_file2";}
?>
</center>
</html>
목록
이전글날짜 표기 형식 변경하는 방법 (게시판 스킨도 동일)19.07.10
다음글게시판 목록에서 페이징 처리를 하였는데 검색 기능을 추가19.07.01
댓글목록
관리자 19-07-01 19:57
php 파일 업로드 질문입니다.
실습용 게시판을 만드는 중인데, 파일업로드 부분이 자꾸 안되네요..
저런식으로 입력값을 전달하면, 나머지 값들은 잘 들어가는데 파일 업로드 부분만 문제인것 같습니다
고수분들 도움부탁드립니다ㅠㅠㅠㅠ
1.우선 write.php 파일입니다.
<!DOCTYPE>
<html>
<head>
<meta charset = 'utf-8'>
</head>
<style>
table.table2{
border-collapse: separate;
border-spacing: 1px;
text-align: left;
line-height: 1.5;
border-top: 1px solid #ccc;
margin : 20px 10px;
}
table.table2 tr {
width: 50px;
padding: 10px;
font-weight: bold;
vertical-align: top;
border-bottom: 1px solid #ccc;
}
table.table2 td {
width: 100px;
padding: 10px;
vertical-align: top;
border-bottom: 1px solid #ccc;
}
</style>
<body>
<form method = "post" action = "./write_ok.php">
<table style="padding-top:50px;" align = center width=700 border=0 cellpadding=2 enctype="mutipart/form-data">
<tr>
<td height=20 align= center bgcolor=#ccc><font color=white> 글쓰
기</font></td>
</tr>
<tr>
<td bgcolor=white>
<table class = "table2">
<tr>
<td>작성자</td>
<td><input type = text name = name size=20> </td>
</tr>
<tr>
<td>제목</td>
<td><input type = text name = title size=60></td>
</tr>
<tr>
<td>내용</td>
<td><textarea name = content cols=85 rows=15></textarea></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type = password name = pw size=10 maxlength=10></td>
</tr>
<div id="in_file">
<td>첨부파일</td>
<td><input type="file" value="1" name="ufile" />
</td></div>
</table>
<center>
<input type = "submit" value="작성">
</center>
</td>
</tr>
</table>
</form>
</body>
</html>
2.wrtie_ok.php 파일입니다.
<?php
$connect = mysqli_connect("localhost", "root", "1111", "test") or die("fail");
$id = $_POST[name]; //Writer
$pw = $_POST[pw]; //Password
$title = $_POST[title]; //Title
$content = $_POST[content]; //Content
$date = date('Y-m-d H:i:s'); //Date
$tmpfile = $_FILES['b_file']['tmp_name'];
$o_name = $_FILES['b_file']['name'];
$filename = iconv("UTF-8", "EUC-KR",$_FILES['b_file']['name']);
$folder = "../upload/".$filename;
move_uploaded_file($tmpfile,$folder);
$URL = '../index.php'; //return URL
$query = "insert into board (number,title, content, date, hit, id, password,file)
values(null,'$title', '$content', '$date',0, '$id', '$pw','$o_name')";
$result = $connect->query($query);
if($result){
?> <script>
alert("<?php echo "글이 등록되었습니다."?>");
location.replace("<?php echo $URL?>");
</script>
<?php
}
else{
echo "FAIL";
}
mysqli_close($connect);
?>
답변1개
form 속성에 enctype 추가해서 해보세요.
PHP 5 File Upload
With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP script explained:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Limit File Size
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Complete Upload File PHP Script
The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
관리자 19-07-01 19:58
모바일 file upload에 관하여 (php)
모바일 웹을 만들다가 input file 에 대해서 막혀서 질문합니다..
웹구현으로는 file upload가 정상 작동을 하는데,
모바일로 들어가니 file upload가 파일을 넣기는 되는데
서버에서 받지를 못하더군요..
왜 그러는지 알 수 있을까요?
웹에서와 다르게 짜여야 된다면..
예제도 볼 수 있으면 좋겠습니다.
간단히는 다음처럼 합니다.
<?php
error_reporting(0);
if (isset($_FILES['image'])) {
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));
$extensions = array("jpeg","jpg","gif","png");
if (in_array($file_ext, $extensions) === false) {
$errors[] = "이미지만선택하세요";
}
if ($file_size > 2097152) {
$errors[]='2 MB 초과';
}
if (empty($errors) == true) {
move_uploaded_file($file_tmp, "H:/tmp/".$file_name);
echo "success";
} else {
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
</form>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</body>
</html>
관리자 19-07-01 20:00
php 게시판 댓글기능에대하여.
리스트에서 잘보고 글누르면(read) 잘보이다가 댓글 텍스트에 할말쓰고 댓글작성 누르면
아래 사진과 같이 나타납니다...
read 에서 11번째줄 도에러였는데 형식약간바꾸니까잡히고
근데 저형식이 이해도안되고..
우선은 .. 이게 실행결과구요 소스 첨부합니다.
첨부 이미지데이터베이스
----------testboard.sql------------
g_num int
g_subject varchar
g_name varchar
g_date date
g_ip varchar
g_view int
g_content text
file_name1 varchar
file_copied1 varchar
file_name2 varchar
file_copied2 varchar
file_name3 varchar
file_copied3 varchar
---------------testboard_ripple.sql------
num int
parent int
id varchar
content text
regist_day varchar
파일
-------read.php -------------------
<?
@extract($_GET);
@extract($_POST);
@extract($_SERVER);
include "db_connect.php";
$query="select * from testboard where g_num='" . mysql_escape_string($g_num) . "' ";// where g_num=$g_num";
$result=mysql_query($query,$conn);
$row=mysql_fetch_array($result);
$item_num = $row[g_num];
$item_id = $row[g_name];
$image_name[0] = $row[file_name1]; //
$image_name[1] = $row[file_name2];
$image_name[2] = $row[file_name3];
$image_copied[0] = $row[file_copied1];
$image_copied[1] = $row[file_copied2];
$image_copied[2] = $row[file_copied3];
$item_date=$row[regist_day];
$item_subject=str_replace(" ", " ", $row[subject]);
$item_content = $row[content];
for($i=0; $i<3; $i++){ // 이미지
if($image_copied[$i]){
$imageinfo = GetImageSize("./data/".$image_copied[$i]);
$image_width[$i] = $imageinfo[0];
$image_height[$i] = $imageinfo[1];
$image_type[$i] = $imageinfo[2];
if ($image_width[$i] > 785)
$image_width[$i] = 785;
}else{
$image_width[$i] = "";
$image_height[$i] = "";
$image_type[$i] = "";
}
}
?>
<meta charset= "utf-8">
<style>
td, input{font-size:9pt}
A:link{font-size:9pt; color:black; text-decoration:none; } <!--링크-->
A:visited{font-size:9pt; color:black; text-decoration:none; } <!--방문시-->
A:hover{font-size:9pt; color:black; text-decoration:none; underline;}
</style>
<center>
<br />
◎ <font size=5 face="Times New Roman, Times, serif" color="#aa3366"><b> 연습용 게시판</b></font> ◎
<br /><br />
<table width=600 border=0 cellpadding=2 cellspacing=1 bgcolor=#336699>
<tr bgcolor=#f2ffff>
<td height=20 align=center colspan=4 bgcolor=#336699><font color=#f2ffff><b><?=$row[g_subject]?></b></font>
<tr bgcolor=white>
<td bgcolor=#f2ffff width=50 align=center>글쓴이
<td width=250><?=$row[g_name]?>
<td width=50 bgcolor=#f2ffff align=center>이메일
<td width=250><?=$row[g_mail]?>
<tr bgcolor=white>
<td bgcolor=#f2ffff width=50 align=center>날짜
<td width=250><?=$row[g_date]?>
<td bgcolor=#f2ffff width=50 align=center>조회수
<td width=250><?=$row[g_view]?>
<tr bgcolor=#f2ffff>
<td colspan=4 bgcolor=white><pre>
<? // 이미지
for ($i=0; $i<3; $i++){
if ($image_copied[$i])
{
$img_name = $image_copied[$i];
$img_name = "./data/".$img_name;
$img_width = $image_width[$i];
echo "<img src='$img_name' width='$img_width'>"."<br><br>";
}
}
?>
<?=$row[g_content]?></pre>
<div id="ripple">
<?
$sql = "select * from testboard_ripple where parent='$item_num'"; // 댓글
$ripple_result = mysql_query($sql);
while ($row_ripple = mysql_fetch_array($ripple_result))
{
$ripple_num = $row_ripple[num];
$ripple_id = $row_ripple[id];
$ripple_content = str_replace("\n", "<br>", $row_ripple[content]);
$ripple_content = str_replace(" ", " ", $ripple_content);
$ripple_date = $row_ripple[regist_day];
?>
<div id="ripple_writer_title">
<ul>
<li id="writer_title1"><?=$ripple_id?></li>
<li id="writer_title2"><?=$ripple_date?></li>
<li id="writer_title3">
<?
//if($userid=="admin" || $userid==$ripple_id) // session
echo "<a href='delete_ripple.php?num=$item_num&ripple_num=$ripple_num'>[삭제]</a>";
?>
</li>
</ul>
</div>
<div id="ripple_content"><?=$ripple_content?></div>
<?
}
?>
<form name="ripple_form" method="post" action="insert_ripple.php?num=<?=$item_num?>">
<div id="ripple_box">
<div id="ripple_box1"><textarea rows="3" cols="82" name="ripple_content"></textarea>
</div>
<div id="ripple_box2"><input type = "submit" value="덧글작성"></div>
</div>
</form>
<!--기타 메뉴 -->
<tr>
<td colspan=4 bgcolor=white>
<table width=100%>
<tr>
<td width=200 height=20>
<a href=list.php?no=<?=$no?>>리스트</a>
<a href=write.php>글작성</a>
<a href=edit.php?g_num=<?=$g_num?>>수정</a>
<a href=predel.php?g_num=<?=$g_num?>>삭제</a>
<td align=right>
<?
//다음글
$query1=mysql_query("select g_num from testboard where g_num > $g_num limit 1",$conn); // 현재 글 넘버 값보다 값이 큰 넘버값을 한개 뽑아라,
$next_num=mysql_fetch_array($query1); //where g_num='" . mysql_escape_string($g_num) . "' ";
if($next_num[g_num])
{
echo "<a href=read.php?g_num=$next_num[g_num]>다음 글</a>";
}else{
echo "다음 글";
}
//이전글
$query1=mysql_query("select g_num from testboard where g_num < $g_num order by g_num desc limit 1",$conn); // 현재 글 넘버 값보다 값이 작은 넘버값을 한개 뽑아라,
$prev_num=mysql_fetch_array($query1);
//where g_num='" . mysql_escape_string($g_num) . "' ";
if($prev_num[g_num])
{
echo "<a href=read.php?g_num=$prev_num[g_num]> 이전 글</a>";
}else{
echo " 이전 글";
}
?>
</table>
</td>
</tr>
<?
//조회수
$result=mysql_query("update testboard set g_view = g_view + 1 where g_num=$g_num"); // 글번호가 같으면 조회수 1증가
//디비종료
mysql_close($conn)
?>
</table>
</center>
-----------------insert.php------------------
<?
//extract($array); // 키 값을 변수화 시켜주는것, 보안상 취약함.
// @ 오류제어연산자 // 오류메시지꺼버림.
@extract($_GET);
@extract($_POST);
@extract($_SERVER);
include "db_connect.php";
$regist_day = date("Y-m-d (H:i)"); // 현재 년월일 시 분 을 저장
$files = $_FILES["upfile"]; // FILES로 upfile를 받아온다.
$count = count($files["name"]); // 업로드할 파일의 개수 구해서 저장 // 배열 $files['name']에 저장된 파일명의 개수를 count로 구한다.
$upload_dir = './data/'; // 이미지 저장될 경로지정용변수
for ($i=0; $i<$count; $i++){ // 업로드하려는 파일의 업로드 조건을 만족하는지 확인한 뒤 올려준다.
$upfile_name[$i] = $files["name"][$i]; // $FILES로 한번에 전달받은 파일 관련 정보를 쪼개서 변수들에 저장함.
$upfile_tmp_name[$i] = $files["tmp_name"][$i];
$upfile_type[$i] = $files["type"][$i];
$upfile_size[$i] = $files["size"][$i];
$upfile_error[$i] = $files["error"][$i];
$file = explode(".", $upfile_name[$i]); // explode로 확장자랑 파일명 분할하여
$file_name = $file[0]; // 여기에 파일명
$file_ext = $file[1]; // 여기에 확장자
if (!$upfile_error[$i]){ //파일에 에러가 있는가 ? 확인하는문.
$new_file_name = date("Y_m_d_H_i_s");
$new_file_name = $new_file_name."_".$i;
$copied_file_name[$i] = $new_file_name.".".$file_ext;
$uploaded_file[$i] = $upload_dir.$copied_file_name[$i];
if( $upfile_size[$i] > 500000 ) { // 파일이 500kb를 초과하나 ?
echo("
<script>
alert('업로드 파일 크기가 지정된 용량(500KB)을 초과합니다!<br>파일 크기를 체크해주세요! ');
history.go(-1)
</script>
");
exit;
}
if ( ($upfile_type[$i] != "image/gif") &&
($upfile_type[$i] != "image/jpeg") &&
($upfile_type[$i] != "image/pjpeg") ) //gif, jpg, jpeg받아준다.
{
echo("
<script>
alert('JPG와 GIF 이미지 파일만 업로드 가능합니다!');
history.go(-1)
</script>
");
exit;
}
if (!move_uploaded_file($upfile_tmp_name[$i], $uploaded_file[$i]) ){ // 실제업로드된파일 upfile_tmp_name[$i]을 uploaded_file[$i]에 저장한다.
echo("
<script>
alert('파일을 지정한 디렉토리에 복사하는데 실패했습니다.');
history.go(-1)
</script>
");
exit;
}
}
}
if($content!=NULL && $subject!=NULL) { // 내용, 제목 다 작성해야된다. 이름까지하려면 $name!=NULL 추가.
if ($mode=="modify"){ // 수정글 저장 글 수정 모드.
$num_checked = count($_POST['del_file']); // 삭제 체크박스에 표시된 항목의 개수를 $num_checked에 저장 $[del_file]에는 체크박스 표시 여부가 저장되는데 count함수를 이용해 그개수를 가져옴.
$position = $_POST['del_file']; // $_POST['del_file']을 $position에 저장된다. $position은 배열 변수로 체크박스가 체크된 항목의 번호를 가진다.
for($i=0; $i<$num_checked; $i++){ // 삭제 표시한 항목
$index = $position[$i]; // 삭제한 파일번호를 인덱스에 저장하고
$del_ok[$index] = "y"; // 배열 $델_ok[index]에 y저장 이 과정을 삭제ㅏㅎㄹ 파일의 개수만큼 반복
}
$query = "select * from testboard where g_num=$g_num"; // 수정할 레코드 검색
$result = mysql_query($query); // testboard 테이블에서 파일삭제하거나 수정할 레코드의 정보를 가져와
$row = mysql_fetch_array($result); // 로우에 저장
for ($i=0; $i<$count; $i++){// 디비 정보 갱신
$field_org_name = "file_name".$i; // 이름들 다른 변수로 뺌.
$field_real_name = "file_copied".$i;
$org_name_value = $upfile_name[$i];
$org_real_value = $copied_file_name[$i];
if ($del_ok[$i] == "y")
{
$delete_field = "file_copied".$i;
$delete_name = $row[$delete_field];
$delete_path = "./data/".$delete_name;
unlink($delete_path);
$query = "update testboard set $field_org_name = '$org_name_value', $field_real_name = '$org_real_value' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
else
{
if (!$upfile_error[$i])
{
$query = "update testboard set $field_org_name = '$org_name_value', $field_real_name = '$org_real_value' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
}
}
$query = "update testboard set subject='$subject', content='$content' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
else
{
$query = "insert into testboard(g_name, g_subject, g_content, g_date, g_ip, g_view,file_name1, file_name2, file_name3, file_copied1, file_copied2, file_copied3)
values('$name','$subject','$content',now(),'$REMOTE_ADDR',0,
'$upfile_name[0]', '$upfile_name[1]', '$upfile_name[2]', '$copied_file_name[0]', '$copied_file_name[1]','$copied_file_name[2]')";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
echo "정상작동";
echo ("<meta http-equiv='Refresh' content='1; URL=list.php'>");
}else{
echo "입력하지 않은 정보가 있습니다";
echo ("<meta http-equiv='Refresh' content='1; URL=write.php'>");
}
mysql_close($conn);
?>
-------
관리자 19-07-01 20:01
----------------insert_ripple.php------------------
<?
//session_start();
?>
<meta charset="euc-kr">
<?
/*if(!$userid) {
echo("
<script>
window.alert('로그인 후 이용하세요.')
history.go(-1)
</script>
");
exit;
} */
include "db_connect.php";
$regist_day = date("Y-m-d (H:i)"); // 현재의 '년-월-일-시-분'을 저장
// 레코드 삽입 명령
$query = "insert into testboard_ripple (parent, id, content, regist_day) ";
$query .= "values($num, '$userid', '$ripple_content', '$regist_day')";
mysql_query($query, $conn); // $sql 에 저장된 명령 실행
mysql_close(); // DB 연결 끊기
echo "
<script>
location.href = 'read.php?num=$num';
</script>
";
?>
작성일2014.10.21. 댓글
약간만 수정하면 정상적으로 작동할 것 같습니다.
우선 아래처럼 수정을 해주세요.
read.php 댓글 부분.
<form name="ripple_form" method="post" action="insert_ripple.php?num=<?=$g_num?>">
insert_ripple.php
<script>
location.href = 'read.php?g_num=$num';
</script>
게시물 값을 변수로 잘 던져주면 문제없이 댓글까지 입력 가능합니다.
실행화면: http://www.icnu.kr/kin/read.php?g_num=3
관리자 19-07-01 20:02
javascript를 이용한 html tag를 동적으로 변경하는 코드에 대해서 문의드립니다.
안녕하세요. 요즘 웹 개발을 배우고 있는 직장인입니다.
기존에 shell로 하던 프로그램을 javascript, html, css, php 등을 이용해서 바꿔보려고 합니다.
우선 제가 하고 있는 단계는 초기 파일을 업로드하는 화면을 구성하는 단계인데,
1. 파일을 업로드 할 수 있어야 하고
2. 원하는 수 만큼 업로드 할 수 있도록 <input type="file"></input> 태그가 계속해서 추가되어야 함.
3. button tag를 이용해서 file tag 추가, 삭제가 javascript function 에서 수행됨.
대략 모습은 갖췄는데 다음과 같은 문제점이 있습니다.
1. 파일을 추가하고 "항목 추가" 버튼을 누르면 기존에 선택되었던 내용들이 초기화 됨.
2. 처음 페이지가 로딩 되고 나서는 "항목 삭제" 기능이 잘 되나, 추가하고 삭제를 하면 동작을 안함.
3. <input type="file"> 태그와, 그 외 버턴을 중앙으로 좀 정렬하고 싶은데, bootstrap에서 중앙으로 오게 하면 어떻게 해야할까요?
소스파일은 아래와 같습니다. 아마 복사해서 붙여넣기 하시면 바로 실행될것 같습니다.
혹시 괜찮으시면 도움을 받을 수 있을까요?
감사합니다.
<html>
<head>
<meta charset="utf-8">
<!-- bootstrap사용을 위한 코드 -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<script>
var LocalRowCount;
var FileForm;
var ControlForm;
var Child;
function AddRow(form) {
LocalRowCount = form.RowCount.value;
LocalRowCount++;
FileForm = document.getElementById("FirstDiv");
FileForm.innerHTML+="<input id=\"attached"+LocalRowCount+"\" type=\"file\" class=\"form-control\">";
form.RowCount.value=LocalRowCount;
alert("RowCount : "+form.RowCount.value);
}
function DelRow(form) {
LocalRowCount = form.RowCount.value;
if(LocalRowCount <= 1) {
alert("1개 입니다.");
return false;
}
alert("1form.RowCount.value : "+LocalRowCount);
FileForm = document.getElementById("FirstDiv");
Child = document.getElementById("Attached"+LocalRowCount);
alert(Child.value);
//FileForm.parentNode.removeChild(Child);
Child.parentNode.removeChild(Child);
LocalRowCount--;
alert("2form.RowCount.value : "+LocalRowCount);
//alert("After removeChild RowCount : "+RowCount);
form.RowCount.value=LocalRowCount;
//alert("form.RowCount.value : "+form.RowCount.value);
}
function DoSubmit(form) {
alert("전송 버튼을 눌렀습니다.");
RowCount = form.RowCount.value;
alert(RowCount);
}
function inititate() {
alert ("page loading complete");
RowCount = document.getElementById("RowCount").value;
alert (RowCount);
FileForm = document.getElementById("FirstDiv");
FileForm.innerHTML+="<input id=\"Attached"+RowCount+"\" type=\"file\" class=\"form-control\">";
InputForm = document.getElementById("DataForm");
InputForm.innerHTML+="<input id=\"add\" type=\"button\" class=\"btn btn-success\" value=\"항목 추가\" onClick=AddRow(form)>";
InputForm.innerHTML+="<input id=\"delete\" type=\"button\" class=\"btn btn-danger\" value=\"항목 제거\" onClick=DelRow(form)>";
InputForm.innerHTML+="<input id=\"submit\" type=\"button\" class=\"btn btn-outline-primary\" value=\"데이터 전송\" onClick=DoSubmit(form)>";
}
</script>
<body onload="inititate()">
<div class="container-fluid">
<div id="FirstDiv">
</div>
<div id="SecondDiv">
<form id="DataForm" name="DataForm" method="POST">
<input type="hidden" id="RowCount" name="RowCount" value="1">
</form>
</div>
</div>
</body>
</html>
Ξ 자바스크립트
내 프로필 이미지
닉네임ttco**** 작성일2018.03.23. 댓글2 나도 궁금해요
더보기
답변1개 정렬 옵션
채택순
필터 옵션
전체보기
보기 옵션
최적원문
1번째 답변
boxe****님 프로필 이미지
boxe**** 님 답변 친구
물신채택답변수 2,060자바, JSP18위, 웹사이트 제작, 운영93위, 웹프로그래밍11위
질문자채택
안녕하세요?
질문하신 소스를 좀 고쳐서 다시만들어보았습니다.
참고해보세요.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- bootstrap사용을 위한 코드 -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<style>
#DataForm { text-align:center; }
</style>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.innerHTML += '<div></div>';
formDivElem.lastChild.innerHTML += '<input type="file" name="file" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML = '<input type="submit" value="데이터 전송" />';
}
}
function DelRow(obj) {
var form = document.forms["DataForm"];
if (Number(form.rc.value) == 1) {
alert('1개 입니다.');
return false;
}
var childNode = obj.parentNode;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.removeChild(childNode);
var rowCount = Number(form.rc.value);
rowCount-=1;
form.rc.value = rowCount;
}
function inititate() {
var form = document.forms["DataForm"];
form.reset();
form.rc.value = 0;
AddRow('first');
}
function DoSubmit(obj) {
var form = document.forms["DataForm"];
alert("전송 버튼을 눌렀습니다. rowCount : " + form.rc.value );
return false;
}
</script>
</head>
<body onload="inititate()">
<div class="container-fluid">
<div id="wrapperDiv">
<form id="DataForm" name="DataForm" method="POST" onsubmit="return DoSubmit(this);">
<div id="FirstDiv" class="form-group"></div>
<div id="SecondDiv"></div>
<input type="hidden" id="rc" name="rc" value="0" />
</form>
</div>
</div>
</body>
</html>
확인 : https://my.to/test/kin/formtest2.html
2018.03.23.
html form type=file tag를 이용해서 php로 파일을 업로드하는 코드를 짜고자 합니다.
안녕하세요. html, css, javascript, php 등을 이용해서 웹 프로그램을 만들고 있습니다.
우선 설명을 좀 드리면
1. 파일을 선택해서 서버로 전송해야 합니다. 따라서 input type=file tag를 사용했고,
2. 파일의 개수가 동적이라 javascript를 이용해서 추가, 삭제를 가능하도록 하였습니다.
3. 우선 화면은 어느 정도 완료가 되었는데, form의 submit을 이용해서 전송된 파일이 제대로 확인이 안 되는 상황입니다.
파일 전송 버튼을 누른 후에, 파일이 제대로 전송이 되었는지를 확인해보기 위해서
5.php 에서 전송된 파일들의 정보들을 출력해보고자 합니다. 그런데 이게 잘 안 되네요...
form 에서 파일이 여러개이면 배열의 형태로 정보들이 넘어갈것 같은데 null 값이 확인됩니다.
아래는 파일을 업로드하는 화면의 소스입니다.
코드를 좀 검토 부탁드리며, 어떻게 변경하는지 좋을지도 조언을 좀 부탁드리겠습니다.
<html>
<head>
<meta charset="UTF-8">
<title>Sample</title>
<style>
#DataForm { text-align:center; }
</style>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
var d=document.createElement('div');
formDivElem.appendChild(d);
formDivElem.lastChild.innerHTML += '<label class="file-upload btn btn-primary">여기를 클릭해서 업로드 할 파일을 선택해주세요. <input type="file" name="attached" id="attached'+rowCount+'" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
document.getElementById('SecondDiv').innerHTML += '<input type="submit" value="데이터 전송" />';
}
}
function DelRow(obj) {
var form = document.forms["DataForm"];
if (Number(form.rc.value) == 1) {
alert('1개 입니다.');
return false;
}
var childNode = obj.parentNode;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.removeChild(childNode);
var rowCount = Number(form.rc.value);
rowCount-=1;
form.rc.value = rowCount;
}
function inititate() {
var form = document.forms["DataForm"];
form.reset();
form.rc.value = 0;
AddRow('first');
}
function DoSubmit(obj) {
$("#DataForm").submit();
}
</script>
</head>
<body onload="inititate()">
<div class="container-fluid">
<div id="wrapperDiv">
<form id="DataForm" name="DataForm" method="POST" onsubmit="return DoSubmit(this);" action="5.php">
<div id="FirstDiv" class="form-group"></div>
<div id="SecondDiv"></div>
<input type="hidden" id="rc" name="rc" value="0" />
</form>
</div>
</div>
</body>
</html>
다음은 form에서 넘어온 파일들을 확인하는 5.php 입니다.
<html>
<head>
</head>
<body>
<?php
echo "The file is temporarily stored: " . $_FILES['attached']['tmp_name'] . "<br>";
echo "The file name was: " . $_FILES['attached']['name'] . "<br>";
echo "The file type is: " . $_FILES['attached']['type'] . "<br>";
echo "The file size is: " . $_FILES['attached']['size'] . "<br>";
?>
</body>
</html>
$_FILE 객체를 그냥 출력해서 값이 있는지를 확인해보고자 한건데..제대로 하고 있나요?
가이드 좀 부탁드리겠습니다.
감사합니다.
저번에 답변드렸던 내용에 이어서 답변드립니다.
이전답변 : http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040202&docId=297790669&page=1#answer1
소스를 약간 수정하였습니다
관리자 19-07-01 20:02
1. 전송부분
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
var d=document.createElement('div');
formDivElem.appendChild(d);
//formDivElem.innerHTML += '<div></div>';
formDivElem.lastChild.innerHTML += '<input type="file" name="file[]" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML = '<input type="submit" value="데이터 전송" />';
}
}
//...
function DoSubmit(obj) {
var form = document.forms["DataForm"];
form.submit();
//alert("전송 버튼을 눌렀습니다. rowCount : " + form.rc.value );
//return false;
}
2. 결과부분
<?php
$total = count($_FILES['file']['name']);
// 전송파일개수만큼 반복
for($i=0; $i<$total; $i++) {
// 임시파일경로를 설정
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
// 임시파일경로 확인
if ($tmpFilePath != ""){
//파일이 실제로 저장될 경로 설정
$newFilePath = "./data/" . $_FILES['file']['name'][$i];
// 임시경로에서 실제경로로 이동
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "The file is temporarily stored: " . $_FILES['file']['tmp_name'][$i] . "<br>";
echo "The file name was: " . $_FILES['file']['name'][$i] . "<br>";
echo "The file type is: " . $_FILES['file']['type'][$i] . "<br>";
echo "The file size is: " . $_FILES['file']['size'][$i] . "<br>";
echo '<a href="' .$newFilePath. '" target="_blank">'. $newFilePath .'</a><br/>';
}
}
}
?>
이와같이 복수개의 파일전송시에는 배열로 받게끔 해주셔야합니다
결과:
https://my.to/test/kin/formtest2.html
관리자 19-07-01 20:03
[JAVASCRIPT] AJAX 비동기로 파일 첨부하기 (IE도 지원하게 만들기)
Programming Tips/Web Programming 2012.10.10 16:48
* 이전에 AJAX로 XMLHttpRequest에 파일을 첨부하는 방법을 쓴적이 있다.
2012/10/05 - [Programming/Web Programming] - [Javascript] AJAX (XMLHttpRequest)로 비동기적으로 파일 업로드하기
: 맨날 크롬만 쓰니까 테스트를 하니까 잘 동작하길래 넘어갔는데, 이게 왠걸, Internet Explorer (이하 IE)에서는 돌아가지 않는 것이다. 이놈의 IE 또 무엇이 말썽인건가?!
: 개발자 도구를 통해서 확인하니 uploadFile.files가 undefined랜다. 게다가 FormData도 없댄다..헐. 도대체 이것들은 있기는 한가?!
http://msdn.microsoft.com/en-us/library/ie/hh772723(v=vs.85).aspx
: IE 10에 나온다고 한다. 이런.. 그럼 이전에 짰던 소스는 IE에서는 아예 안돌아간다고 봐도 될것이다. 웹 프로그래밍의 최대의 적은 언제나 IE이다. HTML5의 풍성한 기능들을 마음껏 이용하지 못하는게 다 IE 때문이다.
: 각설하고 위의 비동기적으로 파일을 첨부하는 것을 IE에서도 해결해야하는 방법을 찾아야 할 것이다. 현재 cross-browser를 표방하고 있는 jquery에서 해결하는 방법을 따라해볼 것이다. 이들이 사용하는 방법은 바로 '숨겨진 iframe 이용하기' 이다.
: 개념은 이렇다. 현재 페이지의 파일은 form으로 둘러싸고, iframe을 하나 숨겨둔다. 그리고 파일을 선택하고나서 form을 submit하는데 그 타겟을 iframe으로 돌리는 것이다. 아주 간단하다. 아래 사이트에는 그 개념을 그림으로 아주 쉽게 표현하고 있다.
http://www.alfajango.com/blog/ajax-file-uploads-with-the-iframe-method/
: 사실 이는 AJAX가 아니다. AJAX를 통해 파일을 업로드하는 것을 IE에서 아직 지원하지 않기 때문에 비동기적으로 파일을 업로드하고 싶다면 이러한 편법을 써야하는 것이다. 이전에 썼던 글은 크롬, 파이어폭스, 오페라 등의 브라우저에서는 아주 잘 돌아갈것이다. 하지만 언제나 그렇듯 IE가 문제이다. 그럼 간단하게 한번 코딩해보자.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
document.getElementById("uploadForm").onsubmit = function(){
document.getElementById("uploadForm").target = "uploadIFrame";
}
document.getElementById("uploadIFrame").onload = function()
{
alert("파일 업로드 완료!");
}
}
</script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action="upload.php">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" name="action" value="Upload" />
<iframe id="uploadIFrame" name="uploadIFrame" style="display:none;visibility:hidden"></iframe>
</form>
</body>
</html>
: 아주 간단하다. 위에 설명했던 것과 같이 iframe을 하나 숨겨놓고 form이 submit 될 때 target을 iframe으로 돌린 것이다. 그럼 iframe에는 onload 이벤트 콜백 함수를 설정해서 파일 업로드가 완료되었다는 처리를 해주면 된다.
: 이것만 쓰면 모든 브라우저에서 돌아가기는 할 것이다. 하지만 XMLHttpRequest의 onprogress라는 멋진 이벤트를 전혀 활용할 수 없게 된다. 따라서 이전에 짰던 소스와 지금의 소스를 합쳐서 IE 이외의 브라우저에서는 실제로 비동기적으로 XMLHttpRequest를 사용하게 하고, IE의 경우는 위와 같이 편법을 사용하도록 하면 될 것이다.
: 아래가 간단하게 XMLHttpRequest를 이용해서 실제 AJAX 비동기로 파일을 올리는 방법과 IE를 위해 위에 썼던 방법을 합친 예이다.
: IE 10부터는 실제로 XMLHttpRequest를 통해 파일을 업로드하는 것을 지원하겠지만, IE 9 이전 버전에서는 전부다 지원을 안하기 때문에 우리나라에서 파일 업로드를 비동기적으로 해야한다면 위의 방법이나, 어짜피 편법을 쓰는거 플래시 플러그인을 쓰는것도 방법일 것이다.
/upload/request_url 는 어느
PC의 이미지 파일을 서버에 업로드 해서 결과를 확인 하는 기능을 구현해 보자.
서버에 업로드 되는 파일을 저장할 수 있는 디렉토리를 하나 만들자.
디렉토리 이름은 'uploads'라고 하자. 쉽게 이해하기 위해 간단히 만들어 보는 것이다.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
업로드 할 파일을 선택하는 웹페이지를 만들자. 파일을 선택하고 버튼을 누르면 upload.php를 실행되어 파일 업로드가 진행된다. method와 enctype에 유의하자.
<?php
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "<p>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</p>";
echo "<br><img src=/uploads/". basename( $_FILES["fileToUpload"]["name"]). ">";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
}
}
?>
선택한 파일의 확장자를 체크하고 지정된 서버의 디렉토리에 파일을 업로드 한다.
서버에 파일이 올라가 있는 것과 그 결과를 확인 할 수 있다.
PHP + Mysql 파일 업로드 구현하기(2)
앞에서는 단순히 PHP를 이용한 파일 업로드 구현이었다.
이번에는 Mysql에 이미지 정보를 기록하는 예제를 만들어 보자.
보통 앞 예제 처럼 이미지를 서버에 업로드 하고 그 정보들, 단순 텍스트들만 DB에 저장하는 방식을 사용한다고 한다.
결국 2단계를 거쳐 이미지를 업로드 한다는 것이다.
이미지를 서버에 올리는 작업과 그 정보를 데이터베이스에 기록하는 단계이다.
앞 예제에 데이터베이스 기록하는 단계를 추가해 보기로 하자.
<?php
create table images (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
filename varchar(100) not null,
imgurl varchar(512) not null,
size int not null
)
?>
먼저 이미지 데이터를 저장할 table를 만들자.
DB구조는 프로젝트에 따라 설계를 해야 겠지만 여기서는 가능한 간단히 만들어 보자.
파일명과 나중에 <img 태그에 뿌려줄 url, 파일 사이즈정도 저장하기로 하자.
실상 url은 파일명이 있기때문에 나중에 가져다 사용할때 패스를 추가해서 사용하면 되기는 한데 일단 넣어서 만들어 보자.
이미지의 width, height등도 추가해 줄 수 있을것 같다.
<?php
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
/*database에 업로드 정보를 기록하자.
- 파일이름(혹은 url)
- 파일사이즈
- 파일형식
*/
$filename = $_FILES["fileToUpload"]["name"];
$imgurl = "http://웹서버주소/uploads/". $_FILES["fileToUpload"]["name"];
$size = $_FILES["fileToUpload"]["size"];
include_once 'config.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//images 테이블에 이미지정보를 저장하자.
$sql = "insert into images(filename, imgurl, size) values('$filename','$imgurl','$size')";
mysqli_query($conn,$sql);
mysqli_close($conn);
echo "<p>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</p>";
echo "<br><img src=/uploads/". basename( $_FILES["fileToUpload"]["name"]). " width=400>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
echo "<br><button type='button' onclick='history.back()'>돌아가기</button>";
}
}
?>
업로드한 이미지의 필요한 정보를 취합해서 데이터베이스 insert 쿼리를 수행한다.
데이터베이스를 확인해 보면 정상적으로 저장되어 있는 것을 확인 할 수 있다.
이제 파일도 업로드 가능하고 데이터베이스에 데이터들도 정상적으로 기록이 되었다.
이제 DB에 있는 정보를 가져와서 페이지에 출력해 보도록 하자.
파일을 선택하는 페이지 하단에 이미지 목록을 출력해 보기로 하자.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<div style="width: 300px; margin:0 auto;">
<h3>이미지 파일 업로드 연습</h3>
<form action="upload.php" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<input type="submit" value="업로드" name="submit" style="margin: .9em">
</form>
</div>
<!-- database에서 이미지 목록을 가져 온다. -->
<ul>
<?php
include_once 'config.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
echo "연결실패! ".mysqli_connect_error();
}
$query = "SELECT * FROM images";
$result = mysqli_query($conn, $query);
while($data = mysqli_fetch_array($result)){
echo '<li style='float:left; margin: 2px;'>';
echo '<img src='.$data['imgurl'].' width=200><br>';
echo ($data['filename']);
echo '</li>';
}
mysqli_close($conn);
?>
</ul>
</body>
</html>
파일을 선택하는 시작 페이지를 수정하자.
하단에 현재 데이터베이스에 저장된 이미지들 정보를 가져와서 출력해 주자.
[php] 대용량 파일 업로드시 확인해야 하는 것
대용량(< 1GB) 정도의 데이터를 서버에 업로드 할 일이 있어서 php.ini를 만졌다.
그 과정에서 나온 것들 정리
★ 개발 환경
1. ajax로 php서버에 요청
2. post 요청
3. apache2사용
4. php7 사용
5. 서버1 macOS, 서버2 linux ubuntu (상관없을듯)
★ php.ini
upload_max_filesize = 1024M
post_max_filesize = 1024M # 위의 upload_max_filesize만 수정하고 이걸 수정하지 않으면 업로드 안됨
memory_limit = 1500M # 쫄려서 넉넉하게 줌
max_execution_time = 300 # 업로드 속도가 빠른 편이라 리미트를 넉넉하게 준다고 준거..
max_input_time = -1 # 입력 데이터 처리에 허용되는 최대 시간 (php 호출 시점 ~ 실행이 시작될 때까지 시간)
★ 그 외
php.ini에서 upload_max_filesize만 설정해주고 post_max_filesize 이건 설정하지 않았는데 (--...)
그 경우 서버 요청도 되고 서버 내의 프로세스가 자연스럽게 흘러가지만 파일 처리는 되지 않는다.
즉, $_FILES == [] 인 상태로 실행되고, $_SERVER != [] 인 상태로 실행되는 것...
요청은 되는데 파일이 없길래 ajax 단의 문제인줄 알았는데 php는 설정과 다른 요청의 엑세스를 차단하는건 아니었다. 그냥 파일만 안받고 실행.. 역시 php 다움...(-- )...
max_input_time은 얼마나 줘야할지 모르겠어서 일단은 리미트로 두었다.
PHP File Upload(파일업로드)
복사https://blog.naver.com/linux_master/221247647674
1.PHP 5 File Upload
- php로 쉽게 파일을 서버로 업로드 할 수 있으나 위험하기때문에 항상 파일업로드는 주의해야한다.
- 지금은 php.net에서 이함수를 찾을 수는 없으나 예전에 php파일에서 리눅스 명령을 실행할 수 있게 해주는 함수가 있었다
만약에 이파일을 게시판에서 업로드 시키고 브라우저 주소표시줄에서 리눅스 명령을 실행한다면 권한설정이 잘못된파일은 삭제,수정,다운로드 압축까지모든게 가능하며 이런 방식으로 해킹 할 수 있었다.
- 이러한 이유로 파일을 업로드 하는 부분은 매우신경을 써야하는 부분이다.
2.파일업로드 설정(php.ini)
- 먼저 php에서 파일이 업로드 될 수 있도록 설정한다.
- php.ini파일에서 file_uploads = On 으로 셋팅되어 있는지 확인한다.
- APM_Setup설치시에는 아래의 디렉토리에서 php.ini파일을 편집기로 열고 확인한다.
3.HTML폼을 생성한다.
- HTML폼은 업로드 하기 원하는 파일을 사용자에게 허락한다.
- 아래의 HTML폼에서 파일을 업로드하기 위해서 사용되는 규칙은 다음과 같다.
- 아래의 규칙이 없이는 파일이 업로드 되지 않는다.
1)method="post"가 되도록한다.
2)폼에는 다음 속성을 필요로한다.:enctype="multipart/form-data". 이것은 양식이 제출될때 content-type을 지정한다.
- 주목해야할 다른 것들 : <input>태그의 type="file"속성은 입력필드를 파일선택컨트롤로써 보여주고 입력컨트롤 옆에는 Browser버튼이 있다.
- 폼의 데이터는 upload.php파일로 보내진다.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
4.파일을 업로드할 php스크립트 만들기(upload_form.php)
- upload.php에는 파일을 업로드할 php코드를 포함하고 있다.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 진짜 이미지 파일인지 가짜 이미지 파일인지 체크
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "이미지 파일입니다 - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "이미지 파일이 아닙니다.";
$uploadOk = 0;
}
}
?>
- php스크립트 설명
1)$target_dir = "uploads/" : 파일이 위치할 디렉토리를 지정한다.
2)$target_file : 업로드될 파일의 경로를 지정한다.
3)$uploadOk=1 : 1로 초기화 되어있고 추후에 업로드가 완료되면 1 아니면 0으로 다시 초기화됨
4)$imageFileType : 소문자에서 파일의 파일확장자를 유지한다.
5)다음은 실제 이미지파일 여부를 체크한다.
6)upload.php파일이 위치한 곳에 upload디렉토리를 만든다 업로드된 파일은 이 upload디렉토리내에 저장된다.
5.파일의 존재여부 체크하기
- 약간의 제한할 부분을 추가한다.
- upload디렉토리내에 파일이 존재하는지를 체크하여 파일이 존재하지 않으면 에러메세지를 표시하고 $uploadOk 는 0으로 셋팅한다.
// 파일의 존재여부 체크하기
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
6.파일 사이즈의 제한
- 위의 html폼에서 파일 입력필드의 이름은 "fileToUpload"라고 이름이 지어져 있다.
- 우리가 체크하길 원하는 파일사이즈가 500kb보다 크면 에러메세지를 표시하고 $uploadOk 는 0 으로셋팅한다.
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "파일사이즈가 너무 큽니다.";
$uploadOk = 0;
}
7.파일타입의 제한
- 아래의 코드는 사용자에게 JPG,JPEG,PNG,GIF파일을 업로드 하도록 허가한다.
- 모든 다른 파일타입은 $uploadOk 가 0으로 셋팅되기 전에 에러메세지를 표시한다.
// 파일 타입체크
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "JPG, JPEG, PNG ,GIF 파일만 업로드 할 수 있습니다.";
$uploadOk = 0;
}
8.upload.php파일의 전체 소스코드
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 파일이 진짜 이미지인지 가짜 이미지인지 체크한다
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "파일이 이미지입니다 - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "파일이 이미지가 아닙니다.";
$uploadOk = 0;
}
}
// 파일이이미 존재하고 있는지 체크한다
if (file_exists($target_file)) {
echo "파일이 이미존재하고 있습니다.";
$uploadOk = 0;
}
// 파일사이즈를 체크한다
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "파일 사이즈가 너무 큽니다.";
$uploadOk = 0;
}
// 허용할 파일의 타입을 체크한다
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "JPG, JPEG, PNG & GIF 파일만 업로드 가능합니다.";
$uploadOk = 0;
}
// $uploadOk가 0 인지 체크한다
if ($uploadOk == 0) {
echo "파일이 업로드 되지 않았습니다.";
// 파일업로드 진행
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "업로드된 파일: ". basename( $_FILES["fileToUpload"]["name"]);
} else {
echo "업로드된 파일에 에러가 발생했습니다.";
}
}
?>
PHP - 파일 업로드/이미지 업로드
1. <form> 태그에서 enctype="multipart/form-data" 라는 애트리뷰트 추가
2. <input> 태그의 Type을 file로 설정
<form action="event.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myImage" id="myImage" value="" />
<input type="submit" value="등록"/>
</form>
event.php 페이지
<?php
$image = $_FILES['myImage'];
$imageName = "";
if($image != null)
{
$tmp_name = $_FILES["myImage"]["tmp_name"];
$Ext = substr(strrchr($_FILES['myImage']['name'], "."), 1);
$imageName = md5(rand() * time()) . ".$Ext";
if(move_uploaded_file($tmp_name, "./images/event/".$imageName)) {
}
chmod("./images/event/".$imageName, 0777);
}
?>
1. GET/POST가 아닌 $_FILES 형식으로 파라미터를 받은 다음
2. substr, strrchr 메서드를 사용하여 문자열 중 "." 마침표 문자 뒤 텍스트 분리 처리
3. 정수난수 * 현재 시간을 암호화 처리한 임의의 값을 만든 다음 뒤에 분리 처리한 확장자를 붙여서
새로운 이름의 파일명을 생성 후 지정된 경로에 파일 업로드 처리
4. 업로드된 파일에 chmod 명령어로 권한 처리
php 에서 파일 업로드를 하기 위해서는
1. 하나의 php 파일 안에서 html 과 php 를 작성하는 방법,
2. 하나의 html파일, 그리고 하나의 php 파일을 작성, 즉 2개의 파일을 작성하는 방법이 있습니다.
한번 만들고 보여주고 버리는 코드라면 1번이 편리하겠지만, 추후에 수정도 하며 유지보수를 하기 위해서는 2방법이 좋습니다.
이 글에서는 php를 이용하여 파일 업로드를 하는 방법을 적어보도록 하겠습니다.
우선 html 파일과 php 파일을 만들어 놓고 작업을 해도 좋고, 만들어가면서 작업해도 좋습니다.
1. upload.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="upload_ok.php">
<input type="file" name="file" required />
<input type="text" name="text" required />
<input type="submit" name="submit" >
</form>
</body>
</html>
-------------------------------------------------------------------------
위 소스를 보시면 빨간색으로 표시한 곳을 잘 확인해주셔야합니다.
1) http-equiv
html에서 '초기정보'를 나타내주는데 우리는 Content-type라고 선언을 해주면
이 파일이 저런 타입의 파일이구나 라고 말해주는것 같습니다.
2) content="text/html"
여기서는 우리의 파일종류가 text, 포맷형식이 html 라고 설명하는 정도라고 생각하시면 됩니다!
3) action="upload_ok.php"
현재 upload.html 은 보여주는 창이며 아무 기능이 없는 페이지임으로
작업을 하는 장소는 upload_ok.php 에서 작업을 할 것이다 라고 지정해주는 것입니다.
4) method="POST"
현재 페이지에서 upload_ok.php로 정보를 넘길때 POST를 사용하여 넘기겠다는 말입니다.
5) enctype="multipart/form-data"
파일이나 이미지를 서버로 전송할 경우 사용해야 하는 속성입니다.
이걸 쓰지 않으면 파일의 경로만 전송이 되며 내용은 전송이 되지 않습니다.
앞서서 파일을 업로드 할 수 있는 아주 아주 아주 간단한 html을 만들었습니다.
그렇다면 이제 php 페이지를 만들어 봅시다!
2. upload_ok.php
2-1(서버 연결 part)
=============================================================
<?php
$servername='서버이름';
$username='유저이름';
$password='비밀번호';
$dbname='DB이름';
$conn=new mysqli($servername, $username, $password, $dbname);
mysqli_query($conn, "set names utf8");
if($conn->connect_error){
die("Connetion error:" . $conn -> connect_error);
}
?>
--------------------------------------------------------------
이 부분은 서버에 php를 연결 시키는 부분입니다.
원하시면 이 부분만 따로 php 파일을 만들어 저장한 후 ("server.php" 로 저장했다고 가정)
<?php
include("server.php"); 혹은 require_once("server.php"); 이런 방식으로 연결을 시킬 수 있습니다.
이렇게 하면 굳이 일일이 저 코드들을 파일에 다 작성하지 않아도 된다는 것!
2-2(post 부분)
--------------------------------------------------------------
<?php
if (isset($_POST['submit'])){
$name=$_POST['text'];
$file=$_FILES['file']['name'];
$dir="./"
$upfile=$dir.$name;
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
if(!move_uploaded_file($_FILES['file']['tmp_name'],$upfile))
{
echo "upload error_file1";
exit;
}
}else{ echo "upload error_file2";}
?>
</center>
</html>
목록
이전글날짜 표기 형식 변경하는 방법 (게시판 스킨도 동일)19.07.10
다음글게시판 목록에서 페이징 처리를 하였는데 검색 기능을 추가19.07.01
댓글목록
관리자 19-07-01 19:57
php 파일 업로드 질문입니다.
실습용 게시판을 만드는 중인데, 파일업로드 부분이 자꾸 안되네요..
저런식으로 입력값을 전달하면, 나머지 값들은 잘 들어가는데 파일 업로드 부분만 문제인것 같습니다
고수분들 도움부탁드립니다ㅠㅠㅠㅠ
1.우선 write.php 파일입니다.
<!DOCTYPE>
<html>
<head>
<meta charset = 'utf-8'>
</head>
<style>
table.table2{
border-collapse: separate;
border-spacing: 1px;
text-align: left;
line-height: 1.5;
border-top: 1px solid #ccc;
margin : 20px 10px;
}
table.table2 tr {
width: 50px;
padding: 10px;
font-weight: bold;
vertical-align: top;
border-bottom: 1px solid #ccc;
}
table.table2 td {
width: 100px;
padding: 10px;
vertical-align: top;
border-bottom: 1px solid #ccc;
}
</style>
<body>
<form method = "post" action = "./write_ok.php">
<table style="padding-top:50px;" align = center width=700 border=0 cellpadding=2 enctype="mutipart/form-data">
<tr>
<td height=20 align= center bgcolor=#ccc><font color=white> 글쓰
기</font></td>
</tr>
<tr>
<td bgcolor=white>
<table class = "table2">
<tr>
<td>작성자</td>
<td><input type = text name = name size=20> </td>
</tr>
<tr>
<td>제목</td>
<td><input type = text name = title size=60></td>
</tr>
<tr>
<td>내용</td>
<td><textarea name = content cols=85 rows=15></textarea></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type = password name = pw size=10 maxlength=10></td>
</tr>
<div id="in_file">
<td>첨부파일</td>
<td><input type="file" value="1" name="ufile" />
</td></div>
</table>
<center>
<input type = "submit" value="작성">
</center>
</td>
</tr>
</table>
</form>
</body>
</html>
2.wrtie_ok.php 파일입니다.
<?php
$connect = mysqli_connect("localhost", "root", "1111", "test") or die("fail");
$id = $_POST[name]; //Writer
$pw = $_POST[pw]; //Password
$title = $_POST[title]; //Title
$content = $_POST[content]; //Content
$date = date('Y-m-d H:i:s'); //Date
$tmpfile = $_FILES['b_file']['tmp_name'];
$o_name = $_FILES['b_file']['name'];
$filename = iconv("UTF-8", "EUC-KR",$_FILES['b_file']['name']);
$folder = "../upload/".$filename;
move_uploaded_file($tmpfile,$folder);
$URL = '../index.php'; //return URL
$query = "insert into board (number,title, content, date, hit, id, password,file)
values(null,'$title', '$content', '$date',0, '$id', '$pw','$o_name')";
$result = $connect->query($query);
if($result){
?> <script>
alert("<?php echo "글이 등록되었습니다."?>");
location.replace("<?php echo $URL?>");
</script>
<?php
}
else{
echo "FAIL";
}
mysqli_close($connect);
?>
답변1개
form 속성에 enctype 추가해서 해보세요.
PHP 5 File Upload
With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP script explained:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Limit File Size
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Complete Upload File PHP Script
The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
관리자 19-07-01 19:58
모바일 file upload에 관하여 (php)
모바일 웹을 만들다가 input file 에 대해서 막혀서 질문합니다..
웹구현으로는 file upload가 정상 작동을 하는데,
모바일로 들어가니 file upload가 파일을 넣기는 되는데
서버에서 받지를 못하더군요..
왜 그러는지 알 수 있을까요?
웹에서와 다르게 짜여야 된다면..
예제도 볼 수 있으면 좋겠습니다.
간단히는 다음처럼 합니다.
<?php
error_reporting(0);
if (isset($_FILES['image'])) {
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));
$extensions = array("jpeg","jpg","gif","png");
if (in_array($file_ext, $extensions) === false) {
$errors[] = "이미지만선택하세요";
}
if ($file_size > 2097152) {
$errors[]='2 MB 초과';
}
if (empty($errors) == true) {
move_uploaded_file($file_tmp, "H:/tmp/".$file_name);
echo "success";
} else {
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
</form>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</body>
</html>
관리자 19-07-01 20:00
php 게시판 댓글기능에대하여.
리스트에서 잘보고 글누르면(read) 잘보이다가 댓글 텍스트에 할말쓰고 댓글작성 누르면
아래 사진과 같이 나타납니다...
read 에서 11번째줄 도에러였는데 형식약간바꾸니까잡히고
근데 저형식이 이해도안되고..
우선은 .. 이게 실행결과구요 소스 첨부합니다.
첨부 이미지데이터베이스
----------testboard.sql------------
g_num int
g_subject varchar
g_name varchar
g_date date
g_ip varchar
g_view int
g_content text
file_name1 varchar
file_copied1 varchar
file_name2 varchar
file_copied2 varchar
file_name3 varchar
file_copied3 varchar
---------------testboard_ripple.sql------
num int
parent int
id varchar
content text
regist_day varchar
파일
-------read.php -------------------
<?
@extract($_GET);
@extract($_POST);
@extract($_SERVER);
include "db_connect.php";
$query="select * from testboard where g_num='" . mysql_escape_string($g_num) . "' ";// where g_num=$g_num";
$result=mysql_query($query,$conn);
$row=mysql_fetch_array($result);
$item_num = $row[g_num];
$item_id = $row[g_name];
$image_name[0] = $row[file_name1]; //
$image_name[1] = $row[file_name2];
$image_name[2] = $row[file_name3];
$image_copied[0] = $row[file_copied1];
$image_copied[1] = $row[file_copied2];
$image_copied[2] = $row[file_copied3];
$item_date=$row[regist_day];
$item_subject=str_replace(" ", " ", $row[subject]);
$item_content = $row[content];
for($i=0; $i<3; $i++){ // 이미지
if($image_copied[$i]){
$imageinfo = GetImageSize("./data/".$image_copied[$i]);
$image_width[$i] = $imageinfo[0];
$image_height[$i] = $imageinfo[1];
$image_type[$i] = $imageinfo[2];
if ($image_width[$i] > 785)
$image_width[$i] = 785;
}else{
$image_width[$i] = "";
$image_height[$i] = "";
$image_type[$i] = "";
}
}
?>
<meta charset= "utf-8">
<style>
td, input{font-size:9pt}
A:link{font-size:9pt; color:black; text-decoration:none; } <!--링크-->
A:visited{font-size:9pt; color:black; text-decoration:none; } <!--방문시-->
A:hover{font-size:9pt; color:black; text-decoration:none; underline;}
</style>
<center>
<br />
◎ <font size=5 face="Times New Roman, Times, serif" color="#aa3366"><b> 연습용 게시판</b></font> ◎
<br /><br />
<table width=600 border=0 cellpadding=2 cellspacing=1 bgcolor=#336699>
<tr bgcolor=#f2ffff>
<td height=20 align=center colspan=4 bgcolor=#336699><font color=#f2ffff><b><?=$row[g_subject]?></b></font>
<tr bgcolor=white>
<td bgcolor=#f2ffff width=50 align=center>글쓴이
<td width=250><?=$row[g_name]?>
<td width=50 bgcolor=#f2ffff align=center>이메일
<td width=250><?=$row[g_mail]?>
<tr bgcolor=white>
<td bgcolor=#f2ffff width=50 align=center>날짜
<td width=250><?=$row[g_date]?>
<td bgcolor=#f2ffff width=50 align=center>조회수
<td width=250><?=$row[g_view]?>
<tr bgcolor=#f2ffff>
<td colspan=4 bgcolor=white><pre>
<? // 이미지
for ($i=0; $i<3; $i++){
if ($image_copied[$i])
{
$img_name = $image_copied[$i];
$img_name = "./data/".$img_name;
$img_width = $image_width[$i];
echo "<img src='$img_name' width='$img_width'>"."<br><br>";
}
}
?>
<?=$row[g_content]?></pre>
<div id="ripple">
<?
$sql = "select * from testboard_ripple where parent='$item_num'"; // 댓글
$ripple_result = mysql_query($sql);
while ($row_ripple = mysql_fetch_array($ripple_result))
{
$ripple_num = $row_ripple[num];
$ripple_id = $row_ripple[id];
$ripple_content = str_replace("\n", "<br>", $row_ripple[content]);
$ripple_content = str_replace(" ", " ", $ripple_content);
$ripple_date = $row_ripple[regist_day];
?>
<div id="ripple_writer_title">
<ul>
<li id="writer_title1"><?=$ripple_id?></li>
<li id="writer_title2"><?=$ripple_date?></li>
<li id="writer_title3">
<?
//if($userid=="admin" || $userid==$ripple_id) // session
echo "<a href='delete_ripple.php?num=$item_num&ripple_num=$ripple_num'>[삭제]</a>";
?>
</li>
</ul>
</div>
<div id="ripple_content"><?=$ripple_content?></div>
<?
}
?>
<form name="ripple_form" method="post" action="insert_ripple.php?num=<?=$item_num?>">
<div id="ripple_box">
<div id="ripple_box1"><textarea rows="3" cols="82" name="ripple_content"></textarea>
</div>
<div id="ripple_box2"><input type = "submit" value="덧글작성"></div>
</div>
</form>
<!--기타 메뉴 -->
<tr>
<td colspan=4 bgcolor=white>
<table width=100%>
<tr>
<td width=200 height=20>
<a href=list.php?no=<?=$no?>>리스트</a>
<a href=write.php>글작성</a>
<a href=edit.php?g_num=<?=$g_num?>>수정</a>
<a href=predel.php?g_num=<?=$g_num?>>삭제</a>
<td align=right>
<?
//다음글
$query1=mysql_query("select g_num from testboard where g_num > $g_num limit 1",$conn); // 현재 글 넘버 값보다 값이 큰 넘버값을 한개 뽑아라,
$next_num=mysql_fetch_array($query1); //where g_num='" . mysql_escape_string($g_num) . "' ";
if($next_num[g_num])
{
echo "<a href=read.php?g_num=$next_num[g_num]>다음 글</a>";
}else{
echo "다음 글";
}
//이전글
$query1=mysql_query("select g_num from testboard where g_num < $g_num order by g_num desc limit 1",$conn); // 현재 글 넘버 값보다 값이 작은 넘버값을 한개 뽑아라,
$prev_num=mysql_fetch_array($query1);
//where g_num='" . mysql_escape_string($g_num) . "' ";
if($prev_num[g_num])
{
echo "<a href=read.php?g_num=$prev_num[g_num]> 이전 글</a>";
}else{
echo " 이전 글";
}
?>
</table>
</td>
</tr>
<?
//조회수
$result=mysql_query("update testboard set g_view = g_view + 1 where g_num=$g_num"); // 글번호가 같으면 조회수 1증가
//디비종료
mysql_close($conn)
?>
</table>
</center>
-----------------insert.php------------------
<?
//extract($array); // 키 값을 변수화 시켜주는것, 보안상 취약함.
// @ 오류제어연산자 // 오류메시지꺼버림.
@extract($_GET);
@extract($_POST);
@extract($_SERVER);
include "db_connect.php";
$regist_day = date("Y-m-d (H:i)"); // 현재 년월일 시 분 을 저장
$files = $_FILES["upfile"]; // FILES로 upfile를 받아온다.
$count = count($files["name"]); // 업로드할 파일의 개수 구해서 저장 // 배열 $files['name']에 저장된 파일명의 개수를 count로 구한다.
$upload_dir = './data/'; // 이미지 저장될 경로지정용변수
for ($i=0; $i<$count; $i++){ // 업로드하려는 파일의 업로드 조건을 만족하는지 확인한 뒤 올려준다.
$upfile_name[$i] = $files["name"][$i]; // $FILES로 한번에 전달받은 파일 관련 정보를 쪼개서 변수들에 저장함.
$upfile_tmp_name[$i] = $files["tmp_name"][$i];
$upfile_type[$i] = $files["type"][$i];
$upfile_size[$i] = $files["size"][$i];
$upfile_error[$i] = $files["error"][$i];
$file = explode(".", $upfile_name[$i]); // explode로 확장자랑 파일명 분할하여
$file_name = $file[0]; // 여기에 파일명
$file_ext = $file[1]; // 여기에 확장자
if (!$upfile_error[$i]){ //파일에 에러가 있는가 ? 확인하는문.
$new_file_name = date("Y_m_d_H_i_s");
$new_file_name = $new_file_name."_".$i;
$copied_file_name[$i] = $new_file_name.".".$file_ext;
$uploaded_file[$i] = $upload_dir.$copied_file_name[$i];
if( $upfile_size[$i] > 500000 ) { // 파일이 500kb를 초과하나 ?
echo("
<script>
alert('업로드 파일 크기가 지정된 용량(500KB)을 초과합니다!<br>파일 크기를 체크해주세요! ');
history.go(-1)
</script>
");
exit;
}
if ( ($upfile_type[$i] != "image/gif") &&
($upfile_type[$i] != "image/jpeg") &&
($upfile_type[$i] != "image/pjpeg") ) //gif, jpg, jpeg받아준다.
{
echo("
<script>
alert('JPG와 GIF 이미지 파일만 업로드 가능합니다!');
history.go(-1)
</script>
");
exit;
}
if (!move_uploaded_file($upfile_tmp_name[$i], $uploaded_file[$i]) ){ // 실제업로드된파일 upfile_tmp_name[$i]을 uploaded_file[$i]에 저장한다.
echo("
<script>
alert('파일을 지정한 디렉토리에 복사하는데 실패했습니다.');
history.go(-1)
</script>
");
exit;
}
}
}
if($content!=NULL && $subject!=NULL) { // 내용, 제목 다 작성해야된다. 이름까지하려면 $name!=NULL 추가.
if ($mode=="modify"){ // 수정글 저장 글 수정 모드.
$num_checked = count($_POST['del_file']); // 삭제 체크박스에 표시된 항목의 개수를 $num_checked에 저장 $[del_file]에는 체크박스 표시 여부가 저장되는데 count함수를 이용해 그개수를 가져옴.
$position = $_POST['del_file']; // $_POST['del_file']을 $position에 저장된다. $position은 배열 변수로 체크박스가 체크된 항목의 번호를 가진다.
for($i=0; $i<$num_checked; $i++){ // 삭제 표시한 항목
$index = $position[$i]; // 삭제한 파일번호를 인덱스에 저장하고
$del_ok[$index] = "y"; // 배열 $델_ok[index]에 y저장 이 과정을 삭제ㅏㅎㄹ 파일의 개수만큼 반복
}
$query = "select * from testboard where g_num=$g_num"; // 수정할 레코드 검색
$result = mysql_query($query); // testboard 테이블에서 파일삭제하거나 수정할 레코드의 정보를 가져와
$row = mysql_fetch_array($result); // 로우에 저장
for ($i=0; $i<$count; $i++){// 디비 정보 갱신
$field_org_name = "file_name".$i; // 이름들 다른 변수로 뺌.
$field_real_name = "file_copied".$i;
$org_name_value = $upfile_name[$i];
$org_real_value = $copied_file_name[$i];
if ($del_ok[$i] == "y")
{
$delete_field = "file_copied".$i;
$delete_name = $row[$delete_field];
$delete_path = "./data/".$delete_name;
unlink($delete_path);
$query = "update testboard set $field_org_name = '$org_name_value', $field_real_name = '$org_real_value' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
else
{
if (!$upfile_error[$i])
{
$query = "update testboard set $field_org_name = '$org_name_value', $field_real_name = '$org_real_value' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
}
}
$query = "update testboard set subject='$subject', content='$content' where g_num=$g_num";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
else
{
$query = "insert into testboard(g_name, g_subject, g_content, g_date, g_ip, g_view,file_name1, file_name2, file_name3, file_copied1, file_copied2, file_copied3)
values('$name','$subject','$content',now(),'$REMOTE_ADDR',0,
'$upfile_name[0]', '$upfile_name[1]', '$upfile_name[2]', '$copied_file_name[0]', '$copied_file_name[1]','$copied_file_name[2]')";
mysql_query($query, $conn); // $query 에 저장된 명령 실행
}
echo "정상작동";
echo ("<meta http-equiv='Refresh' content='1; URL=list.php'>");
}else{
echo "입력하지 않은 정보가 있습니다";
echo ("<meta http-equiv='Refresh' content='1; URL=write.php'>");
}
mysql_close($conn);
?>
-------
관리자 19-07-01 20:01
----------------insert_ripple.php------------------
<?
//session_start();
?>
<meta charset="euc-kr">
<?
/*if(!$userid) {
echo("
<script>
window.alert('로그인 후 이용하세요.')
history.go(-1)
</script>
");
exit;
} */
include "db_connect.php";
$regist_day = date("Y-m-d (H:i)"); // 현재의 '년-월-일-시-분'을 저장
// 레코드 삽입 명령
$query = "insert into testboard_ripple (parent, id, content, regist_day) ";
$query .= "values($num, '$userid', '$ripple_content', '$regist_day')";
mysql_query($query, $conn); // $sql 에 저장된 명령 실행
mysql_close(); // DB 연결 끊기
echo "
<script>
location.href = 'read.php?num=$num';
</script>
";
?>
작성일2014.10.21. 댓글
약간만 수정하면 정상적으로 작동할 것 같습니다.
우선 아래처럼 수정을 해주세요.
read.php 댓글 부분.
<form name="ripple_form" method="post" action="insert_ripple.php?num=<?=$g_num?>">
insert_ripple.php
<script>
location.href = 'read.php?g_num=$num';
</script>
게시물 값을 변수로 잘 던져주면 문제없이 댓글까지 입력 가능합니다.
실행화면: http://www.icnu.kr/kin/read.php?g_num=3
관리자 19-07-01 20:02
javascript를 이용한 html tag를 동적으로 변경하는 코드에 대해서 문의드립니다.
안녕하세요. 요즘 웹 개발을 배우고 있는 직장인입니다.
기존에 shell로 하던 프로그램을 javascript, html, css, php 등을 이용해서 바꿔보려고 합니다.
우선 제가 하고 있는 단계는 초기 파일을 업로드하는 화면을 구성하는 단계인데,
1. 파일을 업로드 할 수 있어야 하고
2. 원하는 수 만큼 업로드 할 수 있도록 <input type="file"></input> 태그가 계속해서 추가되어야 함.
3. button tag를 이용해서 file tag 추가, 삭제가 javascript function 에서 수행됨.
대략 모습은 갖췄는데 다음과 같은 문제점이 있습니다.
1. 파일을 추가하고 "항목 추가" 버튼을 누르면 기존에 선택되었던 내용들이 초기화 됨.
2. 처음 페이지가 로딩 되고 나서는 "항목 삭제" 기능이 잘 되나, 추가하고 삭제를 하면 동작을 안함.
3. <input type="file"> 태그와, 그 외 버턴을 중앙으로 좀 정렬하고 싶은데, bootstrap에서 중앙으로 오게 하면 어떻게 해야할까요?
소스파일은 아래와 같습니다. 아마 복사해서 붙여넣기 하시면 바로 실행될것 같습니다.
혹시 괜찮으시면 도움을 받을 수 있을까요?
감사합니다.
<html>
<head>
<meta charset="utf-8">
<!-- bootstrap사용을 위한 코드 -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<script>
var LocalRowCount;
var FileForm;
var ControlForm;
var Child;
function AddRow(form) {
LocalRowCount = form.RowCount.value;
LocalRowCount++;
FileForm = document.getElementById("FirstDiv");
FileForm.innerHTML+="<input id=\"attached"+LocalRowCount+"\" type=\"file\" class=\"form-control\">";
form.RowCount.value=LocalRowCount;
alert("RowCount : "+form.RowCount.value);
}
function DelRow(form) {
LocalRowCount = form.RowCount.value;
if(LocalRowCount <= 1) {
alert("1개 입니다.");
return false;
}
alert("1form.RowCount.value : "+LocalRowCount);
FileForm = document.getElementById("FirstDiv");
Child = document.getElementById("Attached"+LocalRowCount);
alert(Child.value);
//FileForm.parentNode.removeChild(Child);
Child.parentNode.removeChild(Child);
LocalRowCount--;
alert("2form.RowCount.value : "+LocalRowCount);
//alert("After removeChild RowCount : "+RowCount);
form.RowCount.value=LocalRowCount;
//alert("form.RowCount.value : "+form.RowCount.value);
}
function DoSubmit(form) {
alert("전송 버튼을 눌렀습니다.");
RowCount = form.RowCount.value;
alert(RowCount);
}
function inititate() {
alert ("page loading complete");
RowCount = document.getElementById("RowCount").value;
alert (RowCount);
FileForm = document.getElementById("FirstDiv");
FileForm.innerHTML+="<input id=\"Attached"+RowCount+"\" type=\"file\" class=\"form-control\">";
InputForm = document.getElementById("DataForm");
InputForm.innerHTML+="<input id=\"add\" type=\"button\" class=\"btn btn-success\" value=\"항목 추가\" onClick=AddRow(form)>";
InputForm.innerHTML+="<input id=\"delete\" type=\"button\" class=\"btn btn-danger\" value=\"항목 제거\" onClick=DelRow(form)>";
InputForm.innerHTML+="<input id=\"submit\" type=\"button\" class=\"btn btn-outline-primary\" value=\"데이터 전송\" onClick=DoSubmit(form)>";
}
</script>
<body onload="inititate()">
<div class="container-fluid">
<div id="FirstDiv">
</div>
<div id="SecondDiv">
<form id="DataForm" name="DataForm" method="POST">
<input type="hidden" id="RowCount" name="RowCount" value="1">
</form>
</div>
</div>
</body>
</html>
Ξ 자바스크립트
내 프로필 이미지
닉네임ttco**** 작성일2018.03.23. 댓글2 나도 궁금해요
더보기
답변1개 정렬 옵션
채택순
필터 옵션
전체보기
보기 옵션
최적원문
1번째 답변
boxe****님 프로필 이미지
boxe**** 님 답변 친구
물신채택답변수 2,060자바, JSP18위, 웹사이트 제작, 운영93위, 웹프로그래밍11위
질문자채택
안녕하세요?
질문하신 소스를 좀 고쳐서 다시만들어보았습니다.
참고해보세요.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- bootstrap사용을 위한 코드 -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<style>
#DataForm { text-align:center; }
</style>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.innerHTML += '<div></div>';
formDivElem.lastChild.innerHTML += '<input type="file" name="file" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML = '<input type="submit" value="데이터 전송" />';
}
}
function DelRow(obj) {
var form = document.forms["DataForm"];
if (Number(form.rc.value) == 1) {
alert('1개 입니다.');
return false;
}
var childNode = obj.parentNode;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.removeChild(childNode);
var rowCount = Number(form.rc.value);
rowCount-=1;
form.rc.value = rowCount;
}
function inititate() {
var form = document.forms["DataForm"];
form.reset();
form.rc.value = 0;
AddRow('first');
}
function DoSubmit(obj) {
var form = document.forms["DataForm"];
alert("전송 버튼을 눌렀습니다. rowCount : " + form.rc.value );
return false;
}
</script>
</head>
<body onload="inititate()">
<div class="container-fluid">
<div id="wrapperDiv">
<form id="DataForm" name="DataForm" method="POST" onsubmit="return DoSubmit(this);">
<div id="FirstDiv" class="form-group"></div>
<div id="SecondDiv"></div>
<input type="hidden" id="rc" name="rc" value="0" />
</form>
</div>
</div>
</body>
</html>
확인 : https://my.to/test/kin/formtest2.html
2018.03.23.
html form type=file tag를 이용해서 php로 파일을 업로드하는 코드를 짜고자 합니다.
안녕하세요. html, css, javascript, php 등을 이용해서 웹 프로그램을 만들고 있습니다.
우선 설명을 좀 드리면
1. 파일을 선택해서 서버로 전송해야 합니다. 따라서 input type=file tag를 사용했고,
2. 파일의 개수가 동적이라 javascript를 이용해서 추가, 삭제를 가능하도록 하였습니다.
3. 우선 화면은 어느 정도 완료가 되었는데, form의 submit을 이용해서 전송된 파일이 제대로 확인이 안 되는 상황입니다.
파일 전송 버튼을 누른 후에, 파일이 제대로 전송이 되었는지를 확인해보기 위해서
5.php 에서 전송된 파일들의 정보들을 출력해보고자 합니다. 그런데 이게 잘 안 되네요...
form 에서 파일이 여러개이면 배열의 형태로 정보들이 넘어갈것 같은데 null 값이 확인됩니다.
아래는 파일을 업로드하는 화면의 소스입니다.
코드를 좀 검토 부탁드리며, 어떻게 변경하는지 좋을지도 조언을 좀 부탁드리겠습니다.
<html>
<head>
<meta charset="UTF-8">
<title>Sample</title>
<style>
#DataForm { text-align:center; }
</style>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
var d=document.createElement('div');
formDivElem.appendChild(d);
formDivElem.lastChild.innerHTML += '<label class="file-upload btn btn-primary">여기를 클릭해서 업로드 할 파일을 선택해주세요. <input type="file" name="attached" id="attached'+rowCount+'" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
document.getElementById('SecondDiv').innerHTML += '<input type="submit" value="데이터 전송" />';
}
}
function DelRow(obj) {
var form = document.forms["DataForm"];
if (Number(form.rc.value) == 1) {
alert('1개 입니다.');
return false;
}
var childNode = obj.parentNode;
var formDivElem = document.getElementById("FirstDiv");
formDivElem.removeChild(childNode);
var rowCount = Number(form.rc.value);
rowCount-=1;
form.rc.value = rowCount;
}
function inititate() {
var form = document.forms["DataForm"];
form.reset();
form.rc.value = 0;
AddRow('first');
}
function DoSubmit(obj) {
$("#DataForm").submit();
}
</script>
</head>
<body onload="inititate()">
<div class="container-fluid">
<div id="wrapperDiv">
<form id="DataForm" name="DataForm" method="POST" onsubmit="return DoSubmit(this);" action="5.php">
<div id="FirstDiv" class="form-group"></div>
<div id="SecondDiv"></div>
<input type="hidden" id="rc" name="rc" value="0" />
</form>
</div>
</div>
</body>
</html>
다음은 form에서 넘어온 파일들을 확인하는 5.php 입니다.
<html>
<head>
</head>
<body>
<?php
echo "The file is temporarily stored: " . $_FILES['attached']['tmp_name'] . "<br>";
echo "The file name was: " . $_FILES['attached']['name'] . "<br>";
echo "The file type is: " . $_FILES['attached']['type'] . "<br>";
echo "The file size is: " . $_FILES['attached']['size'] . "<br>";
?>
</body>
</html>
$_FILE 객체를 그냥 출력해서 값이 있는지를 확인해보고자 한건데..제대로 하고 있나요?
가이드 좀 부탁드리겠습니다.
감사합니다.
저번에 답변드렸던 내용에 이어서 답변드립니다.
이전답변 : http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040202&docId=297790669&page=1#answer1
소스를 약간 수정하였습니다
관리자 19-07-01 20:02
1. 전송부분
function AddRow(param) {
var form = document.forms["DataForm"];
var rowCount = Number(form.rc.value);
rowCount+=1;
form.rc.value = rowCount;
var formDivElem = document.getElementById("FirstDiv");
var d=document.createElement('div');
formDivElem.appendChild(d);
//formDivElem.innerHTML += '<div></div>';
formDivElem.lastChild.innerHTML += '<input type="file" name="file[]" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="AddRow();" value="추가" />';
formDivElem.lastChild.innerHTML += '<input type="button" name="btn" onClick="DelRow(this);" value="삭제" />';
if (param == 'first') {
document.getElementById('SecondDiv').innerHTML = '<input type="submit" value="데이터 전송" />';
}
}
//...
function DoSubmit(obj) {
var form = document.forms["DataForm"];
form.submit();
//alert("전송 버튼을 눌렀습니다. rowCount : " + form.rc.value );
//return false;
}
2. 결과부분
<?php
$total = count($_FILES['file']['name']);
// 전송파일개수만큼 반복
for($i=0; $i<$total; $i++) {
// 임시파일경로를 설정
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
// 임시파일경로 확인
if ($tmpFilePath != ""){
//파일이 실제로 저장될 경로 설정
$newFilePath = "./data/" . $_FILES['file']['name'][$i];
// 임시경로에서 실제경로로 이동
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "The file is temporarily stored: " . $_FILES['file']['tmp_name'][$i] . "<br>";
echo "The file name was: " . $_FILES['file']['name'][$i] . "<br>";
echo "The file type is: " . $_FILES['file']['type'][$i] . "<br>";
echo "The file size is: " . $_FILES['file']['size'][$i] . "<br>";
echo '<a href="' .$newFilePath. '" target="_blank">'. $newFilePath .'</a><br/>';
}
}
}
?>
이와같이 복수개의 파일전송시에는 배열로 받게끔 해주셔야합니다
결과:
https://my.to/test/kin/formtest2.html
관리자 19-07-01 20:03
[JAVASCRIPT] AJAX 비동기로 파일 첨부하기 (IE도 지원하게 만들기)
Programming Tips/Web Programming 2012.10.10 16:48
* 이전에 AJAX로 XMLHttpRequest에 파일을 첨부하는 방법을 쓴적이 있다.
2012/10/05 - [Programming/Web Programming] - [Javascript] AJAX (XMLHttpRequest)로 비동기적으로 파일 업로드하기
: 맨날 크롬만 쓰니까 테스트를 하니까 잘 동작하길래 넘어갔는데, 이게 왠걸, Internet Explorer (이하 IE)에서는 돌아가지 않는 것이다. 이놈의 IE 또 무엇이 말썽인건가?!
: 개발자 도구를 통해서 확인하니 uploadFile.files가 undefined랜다. 게다가 FormData도 없댄다..헐. 도대체 이것들은 있기는 한가?!
http://msdn.microsoft.com/en-us/library/ie/hh772723(v=vs.85).aspx
: IE 10에 나온다고 한다. 이런.. 그럼 이전에 짰던 소스는 IE에서는 아예 안돌아간다고 봐도 될것이다. 웹 프로그래밍의 최대의 적은 언제나 IE이다. HTML5의 풍성한 기능들을 마음껏 이용하지 못하는게 다 IE 때문이다.
: 각설하고 위의 비동기적으로 파일을 첨부하는 것을 IE에서도 해결해야하는 방법을 찾아야 할 것이다. 현재 cross-browser를 표방하고 있는 jquery에서 해결하는 방법을 따라해볼 것이다. 이들이 사용하는 방법은 바로 '숨겨진 iframe 이용하기' 이다.
: 개념은 이렇다. 현재 페이지의 파일은 form으로 둘러싸고, iframe을 하나 숨겨둔다. 그리고 파일을 선택하고나서 form을 submit하는데 그 타겟을 iframe으로 돌리는 것이다. 아주 간단하다. 아래 사이트에는 그 개념을 그림으로 아주 쉽게 표현하고 있다.
http://www.alfajango.com/blog/ajax-file-uploads-with-the-iframe-method/
: 사실 이는 AJAX가 아니다. AJAX를 통해 파일을 업로드하는 것을 IE에서 아직 지원하지 않기 때문에 비동기적으로 파일을 업로드하고 싶다면 이러한 편법을 써야하는 것이다. 이전에 썼던 글은 크롬, 파이어폭스, 오페라 등의 브라우저에서는 아주 잘 돌아갈것이다. 하지만 언제나 그렇듯 IE가 문제이다. 그럼 간단하게 한번 코딩해보자.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
document.getElementById("uploadForm").onsubmit = function(){
document.getElementById("uploadForm").target = "uploadIFrame";
}
document.getElementById("uploadIFrame").onload = function()
{
alert("파일 업로드 완료!");
}
}
</script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action="upload.php">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" name="action" value="Upload" />
<iframe id="uploadIFrame" name="uploadIFrame" style="display:none;visibility:hidden"></iframe>
</form>
</body>
</html>
: 아주 간단하다. 위에 설명했던 것과 같이 iframe을 하나 숨겨놓고 form이 submit 될 때 target을 iframe으로 돌린 것이다. 그럼 iframe에는 onload 이벤트 콜백 함수를 설정해서 파일 업로드가 완료되었다는 처리를 해주면 된다.
: 이것만 쓰면 모든 브라우저에서 돌아가기는 할 것이다. 하지만 XMLHttpRequest의 onprogress라는 멋진 이벤트를 전혀 활용할 수 없게 된다. 따라서 이전에 짰던 소스와 지금의 소스를 합쳐서 IE 이외의 브라우저에서는 실제로 비동기적으로 XMLHttpRequest를 사용하게 하고, IE의 경우는 위와 같이 편법을 사용하도록 하면 될 것이다.
: 아래가 간단하게 XMLHttpRequest를 이용해서 실제 AJAX 비동기로 파일을 올리는 방법과 IE를 위해 위에 썼던 방법을 합친 예이다.
: IE 10부터는 실제로 XMLHttpRequest를 통해 파일을 업로드하는 것을 지원하겠지만, IE 9 이전 버전에서는 전부다 지원을 안하기 때문에 우리나라에서 파일 업로드를 비동기적으로 해야한다면 위의 방법이나, 어짜피 편법을 쓰는거 플래시 플러그인을 쓰는것도 방법일 것이다.
/upload/request_url 는 어느
- 이전글날짜 표기 형식 변경하는 방법 (게시판 스킨도 동일) 21.02.22
- 다음글게시판 목록에서 페이징 처리를 하였는데 검색 기능을 추가 21.02.22
댓글목록
등록된 댓글이 없습니다.

