웹 프로그래밍

file_get_contents() 에러 - php 본문

php

file_get_contents() 에러 - php

B. C Choi 2023. 4. 6. 16:57

Apache, php를 사용하여 결제 API 개발하고 있었다.

그중에서 결제 파라미터를 post 방식으로 특정 url에 전송하기 위해 아래 함수를 사용했다.

<?php
    function sendPost($url, $data) {
        $req_data = json_encode($data);
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'content' => $req_data
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $data = json_decode($result, true);
        return $data;
    }
?>

하지만, timeout이 발생하여 결제 파라미터가 url에 전송되지 않았고 반환값을 받지 못하고 408 에러가 발생하는 상황이었다. 수행시간 측정 결과 file_get_contents()가 timeout을 발생하고 있었다.

 

 

해결 방법을 찾아보던 중에 php 사이트의 file_get_contents()함수 Manual을 보았다

php7, php8 버전대 모두 호환되는 줄 알고 php7.4, php8.0, php8.2 모두 사용해 보았지만 똑같이 timeout이 발생했다.

(다른 버전은 사용해보지 않아서 자세히는 모르겠지만 다른 버전도 사용해볼 것을 권장)

 

 

 

결국 docker를 이용해 컨테이너의 이미지를 띄우는 방식을 선택했다.

docker desktop 4.18.0버전을 사용하여 이미지를 띄웠는데 그럼에도 timeout이 발생...

docker run -d -p 8888:80 --name my-apache-php-app -v C:\dev\docker-ws\httpd:/var/www/html php:7.2-apache

위 명령어를 사용했지만 문제가 해결되지 않았다.

 

포기하던 찰나 docker의 특정 버전은 버그가 발생한다는 것을 찾았고 docker 버전을 4.14로 downgrade 했다.

마침내 timeout 없이 결제 파라미터가 특정 url로 정상적으로 전송되는 것을 확인할 수 있었고 반환 파라미터도 확인했다.

 

결론은

1. php 버전을 변경.

2. docker desktop 4.14 이하 버전 사용.

 

 

 

참고 url :

https://www.php.net/manual/en/function.file-get-contents.php

https://forums.docker.com/t/docker-breaks-php-file-get-contents-and-http-s-stream-wrappers/132885/7

 

Docker breaks PHP file_get_contents() and http(s) stream wrappers?

I can confirm the very similar behavior after upgrading to 4.15.0. Using PHP 7.4.33, any calls (http:// and https://) to IIS servers with file_get_contents() and related functions hung up until they hit the timeout limit. Connections to non-IIS servers wor

forums.docker.com