file_get_contents 함수

함수 file_get_contents는 파일의 내용을 읽어 문자열로 반환합니다. 첫 번째 매개변수에는 파일 경로, 두 번째 - 탐색 경로 포함 여부 플래그, 세 번째 - 스트림 컨텍스트, 네 번째 - 읽기 시작 위치 오프셋, 다섯 번째 - 읽을 데이터의 최대 길이를 전달합니다.

세 번째 매개변수는 파일을 PHP 설정 파일의 표준 디렉토리에서만 찾는 것이 아니라 절대 경로로도 검색할 필요가 있을 때 특히 유용합니다.

구문

phpfile_get_contents(
  string $filename,
  bool $use_include_path = false,
  ?resource $context = null,
  int $offset = 0,
  ?int $maxlen = null
): string|false

매개변수

매개변수 설명
filename 파일 경로 또는 URL
use_include_path true로 설정하면, 함수는 php.ini 설정 파일의 include_path 매개변수에 지정된 디렉토리에서 파일을 찾습니다. 기본값은 false입니다.
context 스트림 컨텍스트 리소스
offset 읽기 시작 오프셋
maxlen 읽을 데이터의 최대 길이

예제

로컬 파일 내용 읽기:

php<?php
  $res = file_get_contents('data.txt');
  echo $res;
?>

코드 실행 결과:

php'abcde'

예제

오프셋과 길이를 지정하여 파일 일부 읽기:

php<?php
  $res = file_get_contents('data.txt', false, null, 1, 3);
  echo $res;
?>

코드 실행 결과:

php'bcd'

예제

웹페이지 내용 읽기:

php<?php
  $res = file_get_contents('https://example.com');
  echo substr($res, 0, 50) . '...';
?>

코드 실행 결과:

php'<!doctype html><html><head><title>Example D...'

예제

include_path에서 파일 찾기:

php<?php
  $res = file_get_contents('config.ini', true);
  echo $res;
?>

코드 실행 결과:

php'config_data'

스트림 컨텍스트 매개변수

매개변수 context는 스트림 컨텍스트 리소스를 전달할 수 있게 하며, 이 컨텍스트는 파일 작업이나 네트워크 리소스 작업 시 함수의 동작을 수정할 수 있습니다.

함수 stream_context_create로 생성된 스트림 컨텍스트 리소스. 특별한 설정이 필요하지 않으면 null를 전달할 수 있습니다.

컨텍스트의 가능한 기능:

작동 예:

php<?php
  $opts = [
    'http' => [
      'method' => "GET",
      'header' => "Accept-language: en\r\n"
    ]
  ];
  $context = stream_context_create($opts);
  $res = file_get_contents('https://example.com', false, $context);
?>

함께 보기

  • 데이터를 파일에 기록하는 함수 file_put_contents,
  • 파일을 여는 함수 fopen,
  • 파일을 문자열 배열로 읽는 함수 file,