Contacts

Php load file into variable. File_get_contents - Reads the contents of a file into a string. Example #4 Using Streaming Contexts

Last update: 1.11.2015

Like most programming languages, PHP supports working with files, which are one of the ways to store information.

Reading and writing files

Opening and closing files

To open files in PHP, the fopen() function is defined. It has the following definition: resource fopen(string $filename, string $mode) . The first $filename parameter represents the path to the file, and the second is the opening mode. Depending on the purpose of opening and the type of file this parameter can take the following values:

    "r" : The file is opened read-only. If the file does not exist, returns false

    "r+" : The file is opened read-only and writable. If the file does not exist, returns false

    "w" : The file is opened for writing. If such a file already exists, then it is overwritten, if not, then it is created.

    "w+" : The file is opened for writing and readable. If such a file already exists, then it is overwritten, if not, then it is created.

    "a" : The file is opened for writing. If such a file already exists, then the data is written to the end of the file, and the old data remains. If the file does not exist, it is created

    "a+" : The file is opened for reading and writing. If the file already exists, then the data is appended to the end of the file. If the file does not exist, it is created

The output of the fopen function will be a file descriptor. This handle is used for file operations and to close the file.

After finishing work, the file must be closed using the fclose() function, which takes a file descriptor as a parameter. For example, let's open and close a file:

$fd = fopen("form.php", "r") or die("could not open file"); fclose($fd);

The or die("error text") construct allows the script to stop running and display some error message if the fopen function was unable to open the file.

Reading a file

You can use several functions to read a file. For line-by-line reading, the fgets() function is used, which receives a file descriptor and returns one line read. Let's go through the entire file line by line:

Each time fgets() is called, PHP will place the pointer at the end of the line read. To track the end of a file, the feof() function is used, which returns true when the file is completed. And until the end of the file is reached, we can use the fgets() function.

Reading the entire file

In this case, we do not have to explicitly open the file, obtain a handle, and then close the file.

Block reading

You can also do a block-by-block read, that is, read a certain number of bytes from a file using the fread() function:

The fread() function takes two parameters: the file handle to read and the number of bytes to read. When a block is read, the pointer in the file moves to the end of that block. And also using the feof() function you can track the completion of a file.

Write a file

To write a file, use the fwrite() function, which writes the following line to the file:

Another fputs() function works similarly:

Working with the file pointer

When opening a file for reading or writing in "w" mode, the pointer in the file is placed at the beginning. When reading data, PHP moves the pointer in the file to the end of the block of data read. However, we can also manually manipulate the pointer in the file and set it to an arbitrary location. To do this you need to use the function fseek, which has the following formal definition:

Int fseek (resource $handle , int $offset [, int $whence = SEEK_SET ])

The $handle parameter represents a file handle. The $offset parameter is the offset in bytes relative to the beginning of the file from which reading/writing will begin. The third optional parameter specifies how the offset is set. It can take three values:

    SEEK_SET : default value, sets the offset in offset bytes relative to the start of the file

    SEEK_CUR : sets the offset in offset bytes relative to the beginning of the current position in the file

    SEEK_END : sets the offset to offset bytes from the end of the file

If the pointer is successfully installed, the fseek() function returns 0, and if the pointer is unsuccessful, it returns -1.

Example of using the function:

$fd = fopen("hello.txt", "w+") or die("could not open file"); $str = "Hello world!"; // line to write fwrite($fd, $str); // write the line to the beginning fseek($fd, 0); // place the file pointer at the beginning fwrite($fd, "Oink"); // write the line at the beginning fseek($fd, 0, SEEK_END); // place the pointer at the end fwrite($fd, $str); // write another line at the end fclose($fd);

In PHP, you often have to deal with creating a file... it's very simple: there is no file on disk, the code was run and the file appeared, then you can read this file into another variable or even any page on the Internet and then write something there... but for this you need to know special functions... more about that in this article...

To create a file in PHP in an executable script, you just need to specify a few functions:

Let's take a look at an example:

$text = "Some kind of text to write to the file";
$fp = fopen("file.txt", "w");
fwrite($fp, $text);
fclose($fp);
?>

Here you should know:

fopen()- the function opens the file for reading or writing and clarifications;

This clarification (the mode parameter of the fopen function) is very important:

  • "r" - open a file in php Only for reading. The cursor is placed at the beginning.
  • "r+" - open a file in php for reading and writing. The cursor is placed at the beginning. !!! - with these two modes r and r+, the files must already be created (otherwise an error will appear Warning: fopen(file.txt) : failed to open stream: No such file or directory in ...), and we only read or we have the opportunity to add.
  • "w" - the file is opened ONLY for writing. The file is truncated to zero length - that is, it is overwritten. What is needed is written and the Cursor is placed at the beginning.
  • "w+" - opens a file for writing AND READING! The rest is the same as in the "w" mode. !!! - in these two modes - if the file has not been created - AN ATTEMPT WILL BE MADE TO CREATE IT!
  • "a" - open the file ONLY for writing. Unlike "w", this option does not overwrite the contents of the file, but places the cursor at the end of the line and appends the content that we wanted to add to the end.
  • "a+" - open the file for writing and reading.

fwrite($fp, $text) - a function for writing to a file in PHP - that is, what is in the $text variable is written to a file that is in the $fp variable;

fclose($fp) - function for closing the file that we wrote to the $fp variable;

Now you can easily create files in php correctly, open them for reading and editing.

Useful PHP additions and functions for working with an open file:

while(!feof($fp))(
$mytext = fgets($fp, 99);
echo $mytext."
";
}

here the condition is met - “until the end of the file is reached, do this” while(!feof($fp))

1. Function fgets($fp, 99) - allows you to divide all content into sections of 99 bytes and further, to see this more clearly we place a tag

This string function fgets(resource handle [, int length]) by default accepts 1024 bytes (1 kilobyte) as the length parameter, if not specified it will be so. This parameter is optional as of PHP 4.2.0 (Returns FALSE in case of error)

Additional functions for opening, writing and creating a file

Function - int readfile(string filename [, bool use_include_path [, resource context]]) - read the file as a whole.

Reads a file and writes the contents to the output buffer. And returns the number of bytes output. In case of an error, it will return if the dog is not used - @readfile.

Something like this will happen:

At the end of the word there is a tag
.

b. Function - array file(string filename [, int use_include_path [, resource context]]), does the same as the readfile function, with one exception it adds the contents of the file to an array:

This way you can read any pages on the Internet: $lines = file("http://site/"); and iterate through the array using the foreach function;

3a. string function file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] - allows you to get the contents as a single string.

It's more versatile PHP function to read a file, similar to the file function, only the contents are returned in a string, not in an array, and you can set conditions - which byte to start with - offset and where to end - maxlen. On failure, it will return FALSE.

Important!!!- in this case, the function replaces 3 at once: fopen(), fread() and fclose() and thus gets rid of the mark.

3b. int function file_put_contents(string filename, mixed data [, int flags [, resource context]]) - identical to sequential calls to the functions fopen(), fwrite() and fclose() - returns the number of bytes written.

$Vdata = file_get_contents("textfile.txt");

But now I need to load the PHP file.

I'm guessing you want to get PHP generated content, if it is true:

$Vdata = file_get_contents("http://YOUR_HOST/YOUR/FILE.php");

Otherwise, if you want to get source PHP file , this is the same as the .txt file:

$Vdata = file_get_contents("path/to/YOUR/FILE.php");

Ob_start(); include "yourfile.php"; $myvar = ob_get_clean();

If you are using http:// as suggested by eyel, you will only be able to read the output of the PHP script. You can only read PHP script, if it's on the same server as your script. Then you can use something like

$Vdata = file_get_contents("/path/to/your/file.php");

If you want to download a file without running it through a web server, the following should work.

$string = eval(file_get_contents("file.php"));

The contents of the file will then be downloaded. The PHP file must be fully formed with tagsFor eval to evaluate it.

In theory you could just use fopen and then use stream_get_contents.

$stream = fopen("file.php","r"); $string = stream_get_contents($stream); fclose($stream);

Alternatively, you can start output buffering, do include/require, and then stop buffering. With ob_get_contents() you can simply get the stuff that was output by another PHP file into a variable.

file_get_contents() will not work if your server disabled allow_url_fopen. Most shared web hosts are disabled by default due to security risks. Besides, in PHP6 option allow_url_fopen will no longer exist and all functions will function as if it were permanently disabled. So this is a very bad method to use.

Your the best option use if you are accessing the file via http is cURL

Every programmer should be able to work with files correctly. This article is aimed at beginner PHP programmers, but the “collection of recipes” will also be useful for advanced users.

Working with files is divided into 3 stages:

  1. Opening a file.
  2. Data manipulation.
  3. Closing the file.

I. Opening a file

To open a file in the PHP environment, use the function fopen(). The required parameters for this function are the file name and file mode.

$fp = fopen("counter.txt", "r");

According to the PHP documentation, the following types of file modes are distinguished:

  1. r – open the file for read only.
  2. r+ - opens a file for reading and writing at the same time.
  3. w – creating a new one empty file. If such a file already exists at the time of the call, it is destroyed.
  4. w+ - similar to r+, only if such a file exists at the time of calling, its contents are deleted.
  5. a – opens existing file in write mode, the pointer is shifted to the last byte of the file (to the end of the file).
  6. a+ - opens a file in read-write mode, with the pointer shifted to the last byte of the file (to the end of the file). The contents of the file are not deleted.

Note: There may be one more optional parameter at the end of any of the lines: b or t . If b is specified, the file is opened in binary read/write mode. If t , then the line feed translation mode is set for the file, i.e. it is perceived as textual.

To demonstrate, consider the following scenario:

//Opens a file in different modes
$fp = fopen("counter.txt", "r"); // Binary mode
$fp = fopen("counter.txt", "rt"); // Text mode
$fp = fopen("http://www.yandex.ru", "r");// Opens an HTTP connection for reading
$fp = fopen("ftp://user: [email protected]", "w"); //Open an FTP connection indicating the login and password
?>

II. File Data Manipulation

You can write data to a file using PHP using the function fwrite(). This function takes 2 required parameters and 1 optional one. The required parameters are the file descriptor and the file mode:

$fp = fopen("counter.txt", "a"); // Open the file in write mode
$mytext = "We need to write this line\r\n"; // Source string
$test = fwrite($fp, $mytext); // Write to file
if ($test) echo "The data was successfully entered into the file.";
else echo "Error writing to file.";
fclose($fp); //Close the file
?>

To read a file line by line, use the function fgets(). The function takes 2 required parameters:


if ($fp)
{
while (!feof($fp))
{
$mytext = fgets($fp, 999);
echo $mytext."
";
}
}

fclose($fp);
?>

Note: In this example, the value 999 specifies the number of characters that will be read until the pointer reaches the end of file (EOF).

In order to read the file as a single whole, you need to use the function readfile(), which takes 1 required parameter. The function opens a file, displays its contents in a browser window, and then closes the file:

echoreadfile("counter.txt");
?>

You can also use the fpassthru() function which takes 1 required parameter. Before using this feature, you must open the file in Read mode. When the file is finished reading, the function automatically closes the file (and the file descriptor becomes invalid).

$fp = fopen("counter.txt", "r"); // Open the file in read mode
if ($fp) echo fpassthru($fp);
elseecho "Error opening file";
?>

Very often there are situations when it is necessary to read the contents of a site into an array. This feature involves using the function file(). When this function is called, each line of the file will be stored in a separate element of the specified array.

Note: The function should not be used file() to binary files (binary-safe), because It is not secure in terms of reading binary files, and if it encounters an end-of-file (EOF) character somewhere, it does not guarantee that you will read the entire binary file.

$file_array = file("counter.txt"); // Read the file into the $file_array
// Working with array data
?>

Note: Working with arrays is described in detail, authors: Mukhametshin D.F., Simdyanov I.V.

At the end of the article, you will find a good “cookbook” on arrays that provides solutions to many problems that a web programmer encounters every day.

Let's imagine a situation where a file needs to be read character by character. To do this we can use the function fgetc(). The function takes a single parameter. The function is useful if we need to find any character or the number of identical characters.

$fp = fopen("counter.txt", "r"); // Open the file in read mode
if ($fp)
{
while(!feof($fp))
{
$char = fgetc($fp);
if ($char == "c") $i = $i + 1;// Find the character "c"
}
echo "Number of 'c' letters in file: ". $i;
}
else echo "Error opening file";
?>

III. Closing a file

The file is closed using the function fclose(), which takes 1 required parameter.

$fp = fopen("counter.txt", "r");
if ($fp)
{
echo "The file is open";
fclose($fp); // Closing the file
}
?>

Collection of recipes

1) We need to check whether this or that file exists. To do this we will use the function file_exists().

myfile("counter.txt"); // Use the myfile function, passing the file name as an argument

function myfile($name) //Create a function to check the existence of a file
{
if (file_exists($name)) echo "The file exists";

}
?>

Note: Function file_exists does not check files on the remote web server. For proper operation functions, the file with the script must be located on the same server as the file being checked.

2) Determine the file size using the function filesize()

myfile("counter.txt");

function myfile($name) //Create a function to check the existence of a file and determine the file size
{
if (file_exists($name)) echo "File size: ".filesize($name)." bytes";
else echo "File does not exist";
}
?>

3) Create a temporary file using the function tmpfile()

$myfile = tmpfile();
fwrite($myfile, "This line is written to a temporary file."); // Write to a temporary file
fseek($myfile, 0); // Set the file pointer
echo fread($myfile, 1024); // output the contents of the file
?>

4) You need to determine the number of lines in the file. To do this we use the function count()

$fp = file("counter.txt");
echo "Number of lines in file: ".count($fp);
?>

5) We need to use a file locking mechanism

$fp = fopen("counter.txt", "a");
flock($fp, LOCK_EX); // Lock the file for writing
fwrite($fp, "Line to write");
flock($fp, LOCK_UN); // Unlock
fclose($fp);
?>

6) We need to remove a certain line from the file

$num_stroka = 5; //Delete line 5 from the file
$file = file("counter.txt"); // Read the entire file into an array

for($i = 0; $i< sizeof($file); $i++)
if($i == $num_stroka) unset($file[$i]);

$fp = fopen("counter.txt", "w");
fputs($fp, implode("", $file));
fclose($fp);
?>

7) Determining the file type. Using the function

downloads $_ (8)

I need to load a PHP file into a variable. For example include();

I loaded a simple HTML file like this:

$Vdata = file_get_contents("textfile.txt");

But now I need to load the PHP file.

Answers

If your file has a return statement:

"Afeganistão", "ZA" => "África do Sul", ... "ZW" => "Zimbabué");

You can get this variable like this:

$data = include $filePath;

Alternatively, you can start output buffering, do include/require, and then stop buffering. With ob_get_contents() you can simply get the stuff that was output by another PHP file into a variable.

If you want to download a file without running it through a web server, the following should work.

$string = eval(file_get_contents("file.php"));

The contents of the file will then be downloaded. The PHP file must be fully formed with tagsFor eval to evaluate it.

I'm guessing you want to get PHP generated content, if it is true:

$Vdata = file_get_contents("http://YOUR_HOST/YOUR/FILE.php");

Otherwise, if you want to get PHP file source code, this is the same as the .txt file:

$Vdata = file_get_contents("path/to/YOUR/FILE.php");

In theory you could just use fopen and then use stream_get_contents.

$stream = fopen("file.php","r"); $string = stream_get_contents($stream); fclose($stream);

If you are using http:// as suggested by eyel, you will only be able to read the output of the PHP script. You can only read a PHP script if it is on the same server as your script. Then you can use something like

$Vdata = file_get_contents("/path/to/your/file.php");

Here's how I do it (there are many ways):

  1. Converting data to JSON
  2. Call AJAX to receive the file JSON
  3. Conversion JSON to object Javascript

STEP 1

connect_error) ( die("Connection failed: " . $conn->connect_error); ) $sql = "SELECT id, name ,image FROM phone";

$result = $conn->query($sql);

while($row =$result->fetch_assoc())( $v=$row; ) echo json_encode($v);

$conn->close(); ?>