file get content php code example

Example 1: php get file contents

<?php
file_get_contents("file.txt");
?>

Example 2: turn text file to string php

$fileContent = file_get_contents($url);

Example 3: php get filetype

<?php
echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir
?>

Example 4: transfer file using file_get_content

file_get_contents('http://url/to/upload/handler', false, $context);

Example 5: transfer file using file_get_content

$filename = "/path/to/uploaded/file.zip";
$file_contents = file_get_contents($filename);    

$content =  "--".MULTIPART_BOUNDARY."\r\n".
            "Content-Disposition: form-data; name=\"".FORM_FIELD."\"; filename=\"".basename($filename)."\"\r\n".
            "Content-Type: application/zip\r\n\r\n".
            $file_contents."\r\n";

// add some POST fields to the request too: $_POST['foo'] = 'bar'
$content .= "--".MULTIPART_BOUNDARY."\r\n".
            "Content-Disposition: form-data; name=\"foo\"\r\n\r\n".
            "bar\r\n";

// signal end of request (note the trailing "--")
$content .= "--".MULTIPART_BOUNDARY."--\r\n";

Example 6: php file get contents post

$postdata = http_build_query([
 	'var1' => 'some content',
    'var2' => 'doh'
]);

$opts = [
  'https' =>
    [
    	'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    ]
);

$result = file_get_contents('http://example.com/submit.php', false, stream_context_create($opts));

Tags:

Php Example