PHP 8.3.4 Released!

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contentsDosya içeriğinin tamamını bir dizge olarak döndürür

Açıklama

file_get_contents(
    string $dosyaismi,
    bool $use_include_path = false,
    ?resource $bağlam = null,
    int $başlangıç = 0,
    ?int $uzunluk = null
): string|false

Belirtilen dosyanın başlangıç konumundan başlayan uzunluk baytını bir dizge olarak döndürmesi dışında file() işlevi gibidir. İşlem başarılı olmazsa false döner.

file_get_contents() işlevi bir dosyanın içeriğini bir dizgeye okumak için tercih edilen bir işlevdir. Başarımı arttırmak için eğer işletim sistemi tarafından destekleniyorsa bellek eşlem tekniklerini kullanılacaktır.

Bilginize:

Boşluklar gibi özel karakterler içeren bir URI'yi açmaya çalışıyorsanız URI'yi urlencode() ile kodlamalısınız.

Bağımsız Değişkenler

dosyaismi

İçeriği okunacak dosyanın ismi.

use_include_path

Bilginize:

Aramanın include path yönergesinde belirtilen yollarda da yapılacağını belirtmek için FILE_USE_INCLUDE_PATH sabiti kullanılabilir. Ancak, katı kodlama etkinse FILE_USE_INCLUDE_PATH sabiti int türünde olduğundan bu mümkün değildir. Yerine true kullanın.

bağlam

stream_context_create() işlevi tarafından oluşturulmuş geçerli bir bağlam özkaynağı. Özel bir bağlam kullanmaya ihtiyacınız yoksa bu bağımsız değişkene null atayabilirsiniz.

başlangıç

Akım üzerinde okumaya başlanacak konum. Negatif değerler dosyanın sonundan itibaren sayılır.

Uzak dosyalarda arama (başlangıç) desteklenmemektedir. Yerel olmayan dosyalarda küçük başlangıçlarla çalışmak mümkünse de bu işlem tamponlanmış akım üzerine yapılacağından sonuçları öngörülemez.

uzunluk

Okunacak verinin azami uzunluğu. Öntanımlı olarak dosya sonuna kadar okunur. Bu bağımsız değişken süzgeçler tarafından işlenen akıma ugulanır.

Dönen Değerler

Hata durumunda false aksi takdirde dosyadan okunan veriyi döndürür.

Uyarı

Bu işlev mantıksal false değeriyle dönebileceği gibi false olarak değerlendirilebilecek mantıksal olmayan bir değerle de dönebilir. Bu konuda daha fazla bilgi Mantıksal Değerler bölümünde bulunabilir. Bu işlevden dönen değeri sınamak için === işleci kullanılabilir.

Hatalar/İstisnalar

dosyaismi bulunamazsa, uzunluk sıfırdan küçükse, başlangıç akım üzerinde aranabilir değilse, E_WARNING seviyesinde bir hata üretilir.

file_get_contents() bir dizin için çağrılırsa, Windows'ta ve PHP 7.4'ten beri diğer işletim sistemlerinde E_WARNING seviyesinde bir hata üretilir.

Sürüm Bilgisi

Sürüm: Açıklama
8.0.0 uzunluk artık null olabiliyor.
7.1.0 başlangıç artık negatif değer kabul ediyor.

Örnekler

Örnek 1 - Site başsayfasının kaynak kodunun çıktılanması

<?php
$homepage
= file_get_contents('http://www.example.com/');
echo
$homepage;
?>

Örnek 2 - include_path içinde arama

<?php
// Katı kodlama etkinse, yani declare(strict_types=1); ise
$file = file_get_contents('./people.txt', true);
// değilse
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Örnek 3 - Bir dosyanın belli bir bölümünün okunması

<?php
// 21. karakterden itibaren 14 karakter okuyalım
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

Yukarıdaki örnek şuna benzer bir çıktı üretir:

string(14) "lle Bjori Ro"

Örnek 4 - Akım bağlamı kullanımı

<?php
// Bir akım oluşturalım
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

// Yukarıda atadığımız HTTP başlıklarını kullanarak dosyayı açalım
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Notlar

Bilginize: Bu işlev ikil dosyalarla çalışırken dosya içeriğini değiştirmez.

İpucu

fopen sarmalayıcıları etkin kılınmışsa bu işlevde dosya ismi olarak bir URL belirtilebilir. Dosya isminin nasıl belirtilebileceği hakkında bilgi edinmek için fopen() işlevine bakılabilir. Sarmalayıcıların neler yapabildiği, kullanım bilgileri ve bunlar tarafından kullanılan öntanımlı değişkenler hakkında bilgi Desteklenen Protokoller ve Sarmalayıcılar bölümünde bulanabilir.

Uyarı

Microsoft IIS, SSL kullanırken bir close_notify göndermeden bağlantıyı kapatarak protokolle çelişir. Verinin sonuna ulaştığınız zaman PHP bunu "SSL: Fatal Protocol Error" (SSL: "Ölümcül Protokol Hatası") olarak raporlar. Bu sorunu bertaraf etmek için error_reporting değerini uyarıları içermeyecek bir seviyeye indirmek gerekir. PHP, akımı https:// şeması kullanılarak açılırsa hatalı IIS sunucu yazılımını saptayıp uyarıları engelleyebilir. Bir ssl:// soketi oluşturmak için fsockopen() kullanılacaksa uyarıları saptayıp engellemekten geliştirici sorumludur.

Ayrıca Bakınız

add a note

User Contributed Notes 8 notes

up
5
KC
3 months ago
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.

If you want it to just return what is available when the file is shorter than the negative offset, you could try again.

For example...

$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KB

if ( false === $contents ) {
// Maybe error, or maybe file less than 4KB in size.

$contents = file_get_contents( $log_file, false, null );

if ( false === $contents ) {
// Handle real error.
}
}
up
33
Bart Friederichs
11 years ago
file_get_contents can do a POST, create a context for that first:

<?php

$opts
= array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);

$context = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

?>
up
0
daniel at dangarbri dot tech
1 year ago
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
up
-2
soger
1 year ago
There's barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you're expecting an image you can do this:

<?php
$data
= file_get_contents('https://example.net/some-link');

$mimetype = null;
foreach (
$http_response_header as $v) {
if (
preg_match('/^content\-type:\s*(image\/[^;\s\n\r]+)/i', $v, $m)) {
$mimetype = $m[1];
}
}

if (!
$mimetype) {
// not an image
}
up
-1
brentcontact at daha dot us
7 months ago
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol.

This does not work:
<?php
$jsonData
= file_get_contents('//example.com/file.json');
print
$jsonData;
?>

Specifying only 'example.com/file.json' without the double slash does not work either.

When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.
<?php
$jsonData
= file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');
print
$jsonData;
?>

If using another web server, you may have to get the protocol another way or hard code it.
up
-22
Anonymous
2 years ago
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
up
-24
453034559 at qq dot com
2 years ago
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null){
if(!file_exists($path)) return false;
$size=filesize($path);
if($start<0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
}
up
-29
allenmccabe at gmail dot com
2 years ago
I'm not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> ""
>>> file_get_contents($path, false, null, 5, 5)
=> "r/bin"
To Top