본문 바로가기
Program

fopen

본문

fopen

(PHP 3, PHP 4 , PHP 5)

fopen -- 파일이나 URL을 엽니다

Description

int fopen ( string filename, string mode [, int use_include_path])

만약filename이 "http://"로 시작하면 (sensitive 하지 않은 경우에), HTTP 1.0 연결이 지정된 서버를 열어줍니다.그리고 파일 포인터는 응답텍스트의 시작부분으로 돌려집니다.. A '호스트:' 헤더부분은 name-based virtual hosts를 핸들링하기 위해서 요청과 함께 보내집니다.

HTTP 리다이렉트를 건드리지 마십시오. 반드시 디렉토리뒤에 따르는 슬래쉬를 포함시켜야 합니다.

만약에 filename이 "ftp://"로 시작이 되면 (sensitive 하지 않은 경우에), 지정된 서버가 ftp연결에 의해 열려집니다. 그리로 요청된 파일에 대한 포인터가 반환됩니다. 만약에 서버의 ftp가 받을 수 있는 모드를 지원하지 않으면, 이것은 실행될 수 없습니다. ftp를 통해서 파일을 읽거나 쓸수도 있습니다.ftp (동시에 할 수는 없습니다).

만약에filename이 "php://stdin", "php://stdout", "php://stderr",중의 하나라면 일치하는 표준입출력 스트림이 열리게 됩니다 (PHP 3.0.13에 소개가 되어 있습니다; 이전 버전에서 표준입출력 스트림에 접근하려면 filename이 "/dev/stdin" 이나 "/dev/fd/0" 이어야 합니다.)

filename이 다른 것으로 시작되면 그 파일은 파일 시스템에서 열려집니다. 그리고, 파일에 대한 파일 포인터가 열려서 반환됩니다.

열수가 없다면 FALSE를 반환합니다.

mode다음의 어느것이라도 될 수가 있습니다:

  • 'r' - 읽기전용으로 열립니다; 파일포인터를 파일의 맨 앞에 놓습니다.

  • 'r+' - 읽기 쓰기가 가능합니다.; 파일 포인터를 파일의 맨 앞에 놓습니다.

  • 'w' - 쓰기 전용으로 열립니다; 파일 포인터를 파일의 맨 앞에 놓습니다 그리고 파일의 크기를 0으로 만듭니다. 파일이 없으면 만듭니다.

  • 'w+' - 읽기 쓰기가 가능합니다; 파일포인터를 파일의 맨 앞에 놓습니다. 그리고 파일의 크기를0으로 만듭니다. 파일이 없으면 만듭니다.

  • 'a' - 쓰기 전용으로 열립니다; 파일 포인터를 파일의 끝에 놓습니다. 파일이 없으면 만듭니다.

  • 'a+' - 읽기 쓰기가 가능합니다; 파일 포인터를 파일의 끝에 놓습니다. 파일이 없으면 만듭니다.

mode가 문자'b'를 포함할 수도 있습니다. 이것은 시스템상에서 바이너리와 텍스트 파일을 구별짓는데 쓸모가 있습니다 (다시 말하면 유닉스에서는 쓸모가 없습니다).필요가 없으면 사용하지 마세요.

세번째 매개변수를 사용할 수 있는데 include_path가운데서 파일을 찾고 싶으면 "1"로 설정하세요.

예 1. fopen() example

$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.php.net/", "r");
$fp = fopen ("ftp://user:password@example.com/", "w");

PHP의 서버 모듈 버전을 사용하는데 파일을 읽고 쓰는데 문제를 겪었다면 파일과 디렉토리를 서버 프로세스가 접근이 가능하게 했는지 확인해보세요

윈도우즈에서는, 파일의 경로에서 백슬래시를 사용했는지 슬래시를 사용했는지 주의하세요.

$fp = fopen ("c:\\data\\info.txt", "r");

참조 fclose(), fsockopen(), socket_set_timeout(), and popen().



 

add a note add a note User Contributed Notes
fopen
anonymous at anonymous dot com
26-Dec-2005 11:11
Contrary to a note below the concept of what the preferred line ending is on mac os x is a little bit fuzzy.  I'm pretty sure all the bsd utils installed by default are going to use \n but that is not necessarily the norm.  Some apps will use that while others will use \r.

You should be prepared to deal with either.
Camillo
19-Dec-2005 05:58
Contrary to what this page says, the preferred line ending on Macintosh systems is \n (LF). \r was used on legacy versions of the Mac OS (pre-OS X), and I don't think PHP even runs on those.
151408626 dot unique at servux dot org
19-Dec-2005 12:05
I found a nice trick how to work around the issue (mentioned here: http://www.php.net/manual/en/function.fopen.php#41243) that the PHP  process will block on opening a FIFO until data is sent to it:

Simply do send some data to the FIFO, using an echo command started in background (and ignoring that spedific data, when parsing whatever read from the FIFO).

A very simple example of that:
<?

// path & name of your FIFO-file
$someFIFO =
"path/to/your/fifo"

// some string, that won't be found in your regular input data
$uniqueData = "some specific data"
;

// this statement actually does the trick providing some data waiting in the FIFO:
//  start echo to send data to the FIFO in the background!!
//  NOTE: parenthesis & second redirection (to /dev/null) are
//  important to keep PHP from waiting for echo to terminate! 
system("(echo -n '$uniqueData' >$someFIFO) >/dev/null &"
);

// now you can safely open the FIFO, without the PHP-process being blocked
$handle = fopen($someFIFO, 'r'
);

// loop reading data from the FIFO
while (TRUE
) {
  
$data = fread($handle, 8192
);

  
// eliminate the initially sent data from our read input
   //  NOTE: this is done only in a very simplyfied way in this example,
   //  that will break if that data-string might also be part of your regular input!!
  
if (!(strpos($inp, $uniqueData) === FALSE))    $data = str_replace($uniqueData, '', $data
);

// here comes your processing of the read data...
}

?>
info at b1g dot de
24-Oct-2005 11:54
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

<?php
#usage:
$r = new HTTPRequest('http://www.php.net'
);
echo
$r->DownloadToString
();

class
HTTPRequest
{
   var
$_fp;       
// HTTP socket
  
var $_url;       
// full URL
  
var $_host;       
// HTTP host
  
var $_protocol;   
// protocol (HTTP/HTTPS)
  
var $_uri;       
// request URI
  
var $_port;       
// port
  
   // scan url
  
function _scan_url
()
   {
      
$req = $this->_url
;
      
      
$pos = strpos($req, '://'
);
      
$this->_protocol = strtolower(substr($req, 0, $pos
));
      
      
$req = substr($req, $pos+3
);
      
$pos = strpos($req, '/'
);
       if(
$pos === false
)
          
$pos = strlen($req
);
      
$host = substr($req, 0, $pos
);
      
       if(
strpos($host, ':') !== false
)
       {
           list(
$this->_host, $this->_port) = explode(':', $host
);
       }
       else
       {
          
$this->_host = $host
;
          
$this->_port = ($this->_protocol == 'https') ? 443 : 80
;
       }
      
      
$this->_uri = substr($req, $pos
);
       if(
$this->_uri == ''
)
          
$this->_uri = '/'
;
   }
  
  
// constructor
  
function HTTPRequest($url
)
   {
      
$this->_url = $url
;
      
$this->_scan_url
();
   }
  
  
// download URL to string
  
function DownloadToString
()
   {
      
$crlf = "\r\n"
;
      
      
// generate request
      
$req = 'GET ' . $this->_uri . ' HTTP/1.0' .
$crlf
          
.    'Host: ' . $this->_host .
$crlf
          
.    $crlf
;
      
      
// fetch
      
$this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port
);
      
fwrite($this->_fp, $req
);
       while(
is_resource($this->_fp) && $this->_fp && !feof($this->_fp
))
          
$response .= fread($this->_fp, 1024
);
      
fclose($this->_fp
);
      
      
// split header and body
      
$pos = strpos($response, $crlf . $crlf
);
       if(
$pos === false
)
           return(
$response
);
      
$header = substr($response, 0, $pos
);
      
$body = substr($response, $pos + 2 * strlen($crlf
));
      
      
// parse headers
      
$headers
= array();
      
$lines = explode($crlf, $header
);
       foreach(
$lines as $line
)
           if((
$pos = strpos($line, ':')) !== false
)
              
$headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1
));
      
      
// redirection?
      
if(isset($headers['location'
]))
       {
          
$http = new HTTPRequest($headers['location'
]);
           return(
$http->DownloadToString($http
));
       }
       else
       {
           return(
$body
);
       }
   }
}
?>
admin at sellchain dot com
17-Oct-2005 02:34
TIP: If you are using fopen and fread to read HTTP or FTP or Remote Files, and experiencing some performance issues such as stalling, slowing down and otherwise, then it's time you learned a thing called cURL.

Performance Comparison:

10 per minute for fopen/fread for 100 HTTP files
2000 per minute for cURL for 2000 HTTP files

cURL should be used for opening HTTP and FTP files, it is EXTREMELY reliable, even when it comes to performance.

I noticed when using too many scripts at the same time to download the data from the site I was harvesting from, fopen and fread would go into deadlock. When using cURL i can open 50 windows, running 10 URL's from each window, and getting the best performance possible.

Just a Tip :)
nefertari at nefertari dot be
20-Sep-2005 12:47
Important note:

You have always to use the real path name for a file with the command fopen [for example: fopen($filename, 'w')], never use a symbolic link, it will not work (unable to open $filename).
francis dot fish at gmail dot com
10-Sep-2005 03:10
None of the examples on the page test to see if the file has been opened successfully. Fopen will return false if it failed. To quickly extend one of the examples in the manual:

  $filename = "some.dat" ;
  $dataFile = fopen( $filename, "r" ) ;

  if ( $dataFile )
  {
   while (!feof($dataFile))
   {
       $buffer = fgets($dataFile, 4096);
       echo $buffer;
   }

   fclose($dataFile);
  }
  else
  {
   die( "fopen failed for $filename" ) ;
  }

Hope this is some use.
durwood at speakeasy dot NOSPAM dot net
07-Sep-2005 06:43
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser.  After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:

https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700

Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:

/usr/sbin/setsebool httpd_can_network_connect=1

To make the change permanent, run it with the -P option:

/usr/sbin/setsebool -P httpd_can_network_connect=1

Hope this helps others out -- it sure took me a long time to track down the problem.
ericw at w3consultant dot net
02-Sep-2005 06:49
RE: using fopen to read an http doc
I beat my head against the wall trying to figure out why i couldn't fopen("
http://www.mainserver.com/mySettings.php","r");
on just 1 webserver. It was working on all the other webservers, but on this one, it would just hang, then fail.

Finally i figured out the machine i was doing it on was unable to look up domain names!
If you are having this problem try an nslookup to the website you are having from the command line.
ie: nslookup www.yahoo.com

If that fails, the fopen will not work either.
I changed to an IP (temp solution) and it works like a charm.
-e
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br)
17-Aug-2005 08:11
If you are getting message "Warning: fopen(): URL file-access is disabled in the server configuration", you can use function below to get the content from a local or remote file.

Function uses CURL lib, follow the link to get help:
http://www.php.net/curl

<?php
/*
   * @return string
   * @param string $url
   * @desc Return string content from a remote file
   * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
*/

function get_content($url
)
{
  
$ch = curl_init
();

  
curl_setopt ($ch, CURLOPT_URL, $url
);
  
curl_setopt ($ch, CURLOPT_HEADER, 0
);

  
ob_start
();

  
curl_exec ($ch
);
  
curl_close ($ch
);
  
$string = ob_get_contents
();

  
ob_end_clean
();
  
   return
$string
;   
}

#usage:
$content = get_content ("http://www.php.net"
);
var_dump ($content
);
?>
zachajc at yahoo dot com (Zealot)
05-Aug-2005 08:35
When designing a few flatfile databases and admin panels, I stumbled upon an interesting thing. If a file has been generated into a page or variable via the readfile or include methods (did not try require), an ereg or preg replace to replace \n with <br> does not detect any \n in the file. However, when attempting the same thing with fopen, fread, it works perfectly.
ideacode
03-Aug-2005 02:28
Note that whether you may open directories is operating system dependent. The following lines:

<?php
// Windows ($fh === false)
$fh = fopen('c:\\Temp', 'r'
);

// UNIX (is_resource($fh) === true)
$fh = fopen('/tmp', 'r'
);
?>

demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.

On UNIX, you may happily read the directory format for the native filesystem.
rafaelbc at matrix dot com dot br
23-May-2005 04:23
pflaume dot NOSPAM at NOSPAM dot gmx dot de's proxy_url() was very helpful to me!
Although, I still had a problem: proxy authentication.

So I added some code to enable http get through a proxy with user authentication.

<?php
function proxy_url($proxy_url
)
{
  
$proxy_name = '127.0.0.1'
;
  
$proxy_port = 4001
;
  
$proxy_user = "user";   
// added
  
$proxy_pass = "password";   
// added
  
$proxy_cont = ''
;

  
$proxy_fp = fsockopen($proxy_name, $proxy_port
);
   if (!
$proxy_fp)    {return false
;}
  
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n"
);
  
fputs($proxy_fp, "Proxy-Authorization: Basic " . base64_encode ("$proxy_user:$proxy_pass") . "\r\n\r\n");   
// added
  
while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096
);}
  
fclose($proxy_fp
);
  
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4
);
   return
$proxy_cont
;
}
?>
francois AT crevola DOT com
11-May-2005 11:54
In reply to "pflaume dot NOSPAM at NOSPAM dot gmx dot de"
about  fopen() and PROXY

With PHP 5.0.0 and after, you can use a proxy by using a stream context. See the note about "Context support was added with PHP 5.0.0".
18-Apr-2005 03:41
This only relavant to those opening a remote file for writing using the PECL SSH2 for SFTP paths for the string filename.  Since SFTP has variations, most of which are non-secure, using this module is the only viable solution.  The optional FTP extension class that uses the function 'ftp_ssl_connect' uses openssl, which only encrypts the communication requests and not the data - or something close to that.  At any rate, many systems will not allow connection to their SFTP server using this method.

I think it's worth mentioning that some of the examples provided in various areas failed consistantly using the syntax given, using both possible methods of.
   ssh2.s
ftp://$sftp/example.com/path/to/file
   ssh2.sftp://user:pass@$sftp/example.com/path/to/file

It's just a small adjustment to correct this, but as most coding goes, a long road to find a stupid little oversight.  Apparently it is necessary to supply the port as well in the path.  Could just be the few systems I was testing against, but that would be three separate networks using three separate platforms (Windows Server, Linux, Unix).  At any rate, the following works like a charm, and was very simple to install the libssh2 library and PECL SSH2 module required to use this system.  Gotta love PHP.
   ssh2.s
ftp://$sftp/example.com:22/path/to/file
   ssh2.sftp://user:pass@$sftp:22/example.com/path/to/file

Hope this saves anyone some headache and time.
abesharp at yahoo dot co dot uk
05-Apr-2005 11:12
This function has a basic implementation of HTTP Digest Authentication (as per RFC 2617) to get a file from a web server which requires digest authentication (as opposed to basic authentication - the difference being that, with basic, your password is sent to the server as plain text, whereas with digest, it is hashed with a server-supplied nonce to protect against sniffing and replay attacks).

You just supply the host (e.g www.example.com), the name of the file you want (e.g protected_page.html), and the necessary username and password, and the function returns the contents of the protected file (or the error message that the server sends, if you supplied the wrong credentials).

If the server only supports a QOP of auth-int (rather then auth) this function won't work, but can be easily modified with reference to the RFC at
http://www.ietf.org/rfc/rfc2617.txt

<?php
function readHTTPDigestAuthenticatedFile($host,$file,$username,$password
)
{
   if (!
$fp=fsockopen($host,80, $errno, $errstr, 15
))
       return
false
;
      
  
//first do the non-authenticated header so that the server
   //sends back a 401 error containing its nonce and opaque
  
$out = "GET /$file HTTP/1.1\r\n"
;
      
$out .= "Host: $host\r\n"
;
      
$out .= "Connection: Close\r\n\r\n"
;

    
fwrite($fp, $out
);

  
//read the reply and look for the WWW-Authenticate element
  
while (!feof($fp
))
   {
      
$line=fgets($fp, 512
);
      
       if (
strpos($line,"WWW-Authenticate:")!==false
)
          
$authline=trim(substr($line,18
));
   }
  
  
fclose($fp
);
      
  
//split up the WWW-Authenticate string to find digest-realm,nonce and opaque values
   //if qop value is presented as a comma-seperated list (e.g auth,auth-int) then it won't be retrieved correctly
   //but that doesn't matter because going to use 'auth' anyway
  
$authlinearr=explode(",",$authline
);
  
$autharr
=array();
  
   foreach (
$authlinearr as $el
)
   {
      
$elarr=explode("=",$el
);
      
//the substr here is used to remove the double quotes from the values
      
$autharr[trim($elarr[0])]=substr($elarr[1],1,strlen($elarr[1])-2
);
   }
  
   foreach (
$autharr as $k=>$v
)
       echo(
"$k ==> $v\r\n"
);
  
  
//these are all the vals required from the server
  
$nonce=$autharr['nonce'
];
  
$opaque=$autharr['opaque'
];
  
$drealm=$autharr['Digest realm'
];
  
  
//client nonce can be anything since this authentication session is not going to be persistent
   //likewise for
[이 게시물은 듀라님에 의해 2015-04-03 10:08:13 워드프레스에서 이동 됨]
[이 게시물은 듀라님에 의해 2015-04-03 10:27:24 Public에서 이동 됨]
[이 게시물은 듀라님에 의해 2015-04-03 10:33:53 팁과강좌에서 이동 됨]
[이 게시물은 최고관리자님에 의해 2017-06-10 14:26:42 PHP에서 이동 됨]
0 0
  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기
  • 카카오톡으로 보내기

페이지 정보

l2j (121.♡.101.20) 작성일08-04-03 08:59 조회12,043회 댓글0건

댓글목록

등록된 댓글이 없습니다.

Program 목록

게시물 검색

사이트 정보

  • 회사명 회사명 / 대표 대표자명
  • 주소 OO도 OO시 OO구 OO동 123-45
  • 사업자 등록번호 123-45-67890
  • 전화 02-123-4567 / 팩스 02-123-4568
  • 통신판매업신고번호 제 OO구 - 123호
  • 개인정보관리책임자 정보책임자명

고객센터

  • 02-1234-5678
  • abc@abc.com
  • 월-금 am 11:00 - pm 05:00
  • 점심시간 : am 12:00 - pm 01:00
  • 주말&공휴일은 1:1문의하기를 이용하세요.
상단으로