Ejemplo n.º 1
0
function rest_post()
{
    include "serverconfig.php";
    include "./image_test/dbconfig.php";
    $debug_msg = '';
    // echo "saveHTMLFile filename: ".$_FILES ['html_file'] ['name'];
    if (!isset($_FILES['html_file'])) {
        $debug_msg = "업로드 파일 존재하지 않음";
        return $debug_msg;
    }
    if ($_FILES['html_file']['error'] > 0) {
        switch ($_FILES['html_file']['error']) {
            case 1:
                $debug_msg = "php.ini 파일의 upload_max_filesize 설정값을 초과함(업로드 최대용량 초과)";
                return $debug_msg;
            case 2:
                $debug_msg = "Form에서 설정된 MAX_FILE_SIZE 설정값을 초과함(업로드 최대용량 초과)";
                return $debug_msg;
            case 3:
                $debug_msg = "파일 일부만 업로드 됨";
                return $debug_msg;
            case 4:
                $debug_msg = "업로드된 파일이 없음";
                return $debug_msg;
            case 6:
                $debug_msg = "사용가능한 임시폴더가 없음";
                return $debug_msg;
            case 7:
                $debug_msg = "디스크에 저장할수 없음";
                return $debug_msg;
            case 8:
                $debug_msg = "파일 업로드가 중지됨";
                return $debug_msg;
            default:
                $debug_msg = "시스템 오류가 발생";
                return $debug_msg;
        }
        // switch
    }
    $ableExt = array('html');
    $path = pathinfo($_FILES['html_file']['name']);
    $ext = strtolower($path['extension']);
    if (!in_array($ext, $ableExt)) {
        $debug_msg = "허용되지 않는 확장자입니다.";
        return $debug_msg;
    }
    $mysqli = new mysqli($dbhost, $dbusr, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    // $create_table = "CREATE TABLE if not exists posts (
    // id int auto_increment,
    // user_id varchar(30),
    // title varchar(100),
    // upload_filename varchar(100),
    // db_filename varchar(100),
    // filepath varchar(100),
    // filesize int(8),
    // file_type VARCHAR(40),
    // upload_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    // thumb_img_path varchar(100),
    // category varchar(20),
    // rank float,
    // PRIMARY KEY (id)
    // );";
    // $mysqli->query ( $create_table );
    do {
        // 6. 새로운 파일명 생성(마이크로타임과 확장자 이용)
        $time = explode(' ', microtime());
        $fileName = $time[1] . substr($time[0], 2, 6) . '.' . strtoupper($ext);
        // 중요 이미지의 경우 웹루트(www) 밖에 위치할 것을 권장(예제 편의상 아래와 같이 설정)
        $filePath = 'http://localhost:8080/web_test/image_test/upload_html/';
        // $_SERVER ['DOCUMENT_ROOT'] . '/web_test/image_test/upload_html/';
        $fileServerPath = $_SERVER['DOCUMENT_ROOT'] . '/web_test/image_test/upload_html/';
        if (!is_dir($fileServerPath)) {
            @mkdir($fileServerPath);
        }
        // 7. 생성한 파일명이 DB내에 존재하는지 체크
        $query = sprintf("SELECT no FROM image_files WHERE db_filename = '%s'", $fileName);
        $result = $mysqli->query($query);
        if ($result === NULL) {
            break;
        }
        // 생성한 파일명이 중복하는 경우 새로 생성해서 체크를 반복(동시저장수가 대량이 아닌경우 중복가능 희박)
    } while ($result != NULL && $result->num_rows > 0);
    // db에 저장할 정보 가져옴
    $upload_filename = $_FILES['html_file']['name'];
    //$mysqli->real_escape_string ( $_FILES ['html_file'] ['name'] );
    $file_size = $_FILES['html_file']['size'];
    $file_type = $_FILES['html_file']['type'];
    // set time to Seoul.
    date_default_timezone_set("Asia/Seoul");
    $upload_date = date("Y-m-d H:i:s");
    // create and save thumbnail
    $thumbPath = 'http://localhost:8080/web_test/image_test/thumbnails/';
    $thumb_url = isset($_POST['thumb_img_url']) ? $_POST['thumb_img_url'] : null;
    $thumbimagename = save_thumbnail($thumb_url);
    // 	$mysqli->autocommit ( false );
    // 	$query = sprintf ( "INSERT INTO posts
    // 		(user_id, title, upload_filename,db_filename,filepath,filesize,file_type,upload_date,thumb_img_path,category)
    // 		VALUES ('%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')", $_POST ["user_id"], $_POST ["title"], $upload_filename, $fileName, $filePath, $file_size, $file_type, $upload_date, $thumbimagename, $_POST ["category"] );
    // 	$mysqli->query ( $query );
    $insert_id = NULL;
    if (move_uploaded_file($_FILES['html_file']['tmp_name'], $fileServerPath . $fileName)) {
        $post = new PostModel();
        $post->prepareDb();
        $post->user_id = $_POST["user_id"];
        $post->title = $_POST["title"];
        $post->upload_filename = $upload_filename;
        $post->db_filename = $fileName;
        $post->filepath = $filePath;
        $post->filesize = $file_size;
        $post->file_type = $file_type;
        $post->upload_date = $upload_date;
        $post->thumb_img_path = $thumbimagename;
        $post->category = $_POST["category"];
        $result = $post->save();
        $insert_id = $result['id'];
    }
    // 	if ($mysqli->error) {
    // 		echo "Failed to insert posts db: (" . $mysqli->error . ") ";
    // 	}
    // 	$insert_id = $mysqli->insert_id;
    // 	if ($mysqli->affected_rows > 0) {
    // 		// 9. 업로드 파일을 새로 만든 파일명으로 변경 및 이동
    // 		if (move_uploaded_file ( $_FILES ['html_file'] ['tmp_name'], $fileServerPath . $fileName )) {
    // 			$mysqli->commit ();
    // 		} else {
    // 			$mysqli->rollback ();
    // 			$debug_msg = "업로드 실패";
    // 			return $debug_msg;
    // 		} // if
    // 	}
    $html_saving_info = array("id" => $insert_id);
    // 	$mysqli->close ();
    if (isset($_POST['images_name'])) {
        $html_saving_info['ret_detail'] = insert_post_images($insert_id, $_POST['images_name']);
    }
    $html_saving_info['ret_val'] = "success";
    return $html_saving_info;
}