All file operations of PHP foundation 3

Keywords: PHP Back-end

Common operations of all files in PHP

File operation

Write string to file

$str = "abed, I see a silver light,
It's suspected to be frost on the ground.
look at the bright moon,
Bow your head and think of your hometown."; # It must be enclosed in double quotation marks. Only in this way \ r\n can it be parsed
file_put_contents('./test.txt', $str);
Conclusions and knowledge points:
1. All writes are empty and overwritten
2.  Wrapping in file is\r\n
3. \r:The enter cursor moves to the front of the current line
4. \n:Wrap moves the cursor down one line
5. Press the Enter key on the keyboard to do two steps. The first step is to move the cursor to the front of the current line, and the second step is to move down one line
6. \r\n Are special characters and must be placed in double quotation marks

Read the entire file into a string

//Method 1:
echo file_get_contents('./test.txt'), '<br>';//Read the entire file into a string
//Method 2:
readfile('./test.txt');
echo '<br>';

Open file and operate

/*
 * fopen(Address, mode) open file
 * pattern:
 * r:Read, w: write, a: append
 */
 # Open file
$fp = fopen('./test.txt', 'w');//Open file return file pointer (file address)
var_dump($fp);
echo '<br>';
for ($i = 1; $i <= 10; $i++)
    fputs($fp, 'A pair of turtledoves are cooing' . "\n"); //write file
fclose($fp); //Close file

Open file read

$fp = fopen('./test.txt', 'r');//Open file read
while ($line = fgets($fp)) {
    echo $line . '<br>';
}
fclose($fp);

Open file append

# Open file append
$fp = fopen('./test.txt', 'a');
fputs($fp, 'On the river island' . "\n");
fclose($fp);
Knowledge points:
1. Open the file, return the file pointer,(The file pointer is the file address),Resource type
2. Open file write and append operations. If the file does not exist, create a new file
3. If you open a file to read, an error will be reported if the file does not exist
4. fputs()Write a line, fgets()Read a line, fclose()Close file

Judgment related to documents

# Is it a file
echo is_file('./test.txt') ? 'It's a file' : 'Not a file', '<br>';
# Determine whether a folder or file exists
echo file_exists('./test.txt') ? 'File exists' : 'file does not exist', '<br>';

Delete operation

# Delete operation
$path = './test.txt';
if (file_exists($path)):
    if (is_dir($path))
        rmdir($path);
    elseif(is_file($path))
        unlink($path);//unlink is to delete a file
endif;

Binary file operation

Knowledge points:
1. Binary file read[ fread(field name pointer,file size)]
2. There are two kinds of file storage, character stream and binary stream
3. The binary stream is read according to the file size
$path='./clk.jpg';
$fp=fopen($path,'r');
header('Content-Type:image/jpeg');//Tell the browser that the following code is parsed through jpg pictures
echo fread($fp,filesize($path)); # Binary read
# file_get_contents() can also perform binary reading
header('Content-Type:image/jpeg');
echo file_get_contents($path);
Summary:
1. The text stream has a clear terminator, while the binary stream does not have a clear terminator. Judge whether the file has been read through the file size
2. file_get_contents()Both character stream and binary stream can be read

The difference between GET and POST is the corresponding request

Knowledge points:
1. Visually: get You can see the parameters in the address bar when submitting, post The submission cannot see the parameters in the address bar
2. Security: get unsafe,post security
3. Submission principle: get Submission is the submission of parameters one by one, post Submission means that all parameters are submitted as a whole
4. Submitted data size: get Generally, the submission does not exceed 255 bytes,post The size of the submission depends on the server
5. stay php.ini Can be set in post Submitted size post_max_size=8M
6. Flexibility: get It is very flexible. Parameters can be passed as long as there is page Jump, post Inflexible, post Form participation is required for submission

Jump mode

html jump

<a href="index.php?name=tom&age=20">Jump</a>

js jump

<script type="text/javascript">
location.href='index.php?name=tom&age=20';
location.assign('index.php?name=tom&age=20');
location.replace('index.php?name=tom&age=20');
</script>

php jump

header('Location:index.php?name=tom&age=20')

Similarities and differences between post, get and request Submission requests

HTML page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="servers.php" method="post">
    chinese:<input type="text" name="ch"><br>
    mathematics:<input type="text" name="math"><br>
    <input type="submit" value="Submit" name="button"><br><br>
</form>
<!--Hyperlink jump submission data-->
<a href="servers.php?ch=85&math=99">Jump</a>
<br><br>
<!--js Submit data jump-->
<input type="submit" name="button" onclick="location.href='servers.php?ch=66&math=22'">
</body>
</html>

PHP page

How the server submits data knowledge points:
1. Get the value corresponding to the name by name
2. $_POST:Array type, saved POST Submitted value
3. $_GET:Array type, saved GET Submitted value
4. $_REQUEST:Array type, saved GET and POST Submitted value
if (!empty($_POST)) {
    echo 'This is post Submitted data', '<br>';
    echo 'chinese:' . $_POST['ch'] . '<br>';
    echo 'mathematics:' . $_POST['math'] . '<br>';
}
echo '<hr>';
if (!empty($_GET)) {
    echo 'This is get Submitted data', '<br>';
    echo 'chinese:' . $_GET['ch'] . '<br>';
    echo 'mathematics:' . $_GET['math'] . '<br>';
}
echo '<hr>';
//Both get and post submitted data can be obtained
echo 'This is request' . '<br>';
echo 'chinese:' . $_REQUEST['ch'] . '<br>';
echo 'mathematics:' . $_REQUEST['math'] . '<br>';

Notes on using request

Knowledge points:
1. In a request, both get Again post,get and post The name is the same, this time through $_REQUEST The obtained data will be overwritten
2. Overwrite depends on the configuration of the configuration file, request_order='GP',Get first get,Re acquisition post

example

if (!empty($_POST)){
    echo 'Name:'.$_REQUEST['username'];
}
echo "<form method='post' action='?username=berry'>
full name:<input type='text' name='username'><br>
<input type='submit' name='button' value='Submit'>
</form>";

POST form exercise

Transmission of check box values

# Transmission of check box values
if (isset($_POST['button'])) {
    print_r($_POST['hobby']);
    echo $_POST['hobby'][0];
}
echo "<form method='post' action=''>
Hobbies:
<input type='checkbox' name='hobby[]' value='Mountain climbing'>Mountain climbing
<input type='checkbox' name='hobby[]' value='run'>run
<input type='checkbox' name='hobby[]' value='shuttlecock'>shuttlecock
<input type='checkbox' name='hobby[]' value='drink'>drink
<input type='submit' value='Submit' name='button'>
</form>";
Knowledge points:
1. If the form is submitted to this page, you need to judge whether there is post Submit
2. The name of the submission form element of the array needs to contain[],Is the check box

Submit data exercises to the server

if (isset($_POST['button'])){
    echo 'full name:'.$_POST['username'].'<br>';
    echo 'password:'.$_POST['pwd'].'<br>';
    echo 'Gender:'.$_POST['sex'].'<br>';
    echo 'Hobbies:'.isset($_POST['username'])?implode(',',$_POST['hobby']):'No hobbies'.'<br>';
    echo 'Native place:'.$_POST['jiguan'].'<br>';
    echo 'Leaving a message.'.$_POST['words'].'<br>';
}
echo '<form action="" method="post">
    full name:<input type="text" name="username"><br>
    password:<input type="password" name="pwd"><br>
    Gender:<input type="radio" name="sex" value="1" checked="checked">male
    <input type="radio" name="sex" value="0"> female<br>
    Hobbies:
    Hobbies:
    <input type=\'checkbox\' name=\'hobby[]\' value=\'Mountain climbing\'>Mountain climbing
    <input type=\'checkbox\' name=\'hobby[]\' value=\'run\'>run
    <input type=\'checkbox\' name=\'hobby[]\' value=\'shuttlecock\'>shuttlecock
    <input type=\'checkbox\' name=\'hobby[]\' value=\'drink\'>drink
    <br>
    Native place:
    <select name="jiguan">
        <option value="021">Shanghai</option>
        <option value="022">Hubei</option>
        <option value="033">Nanjing</option>
    </select><br>
    Leaving a message.<textarea name="words" rows="10" cols="40"></textarea><br>
    <input type="submit" name="button" value="Submit">
</form>';

Knowledge points about $_FILES

File domain

# File domain
echo '<input type="file" name="image">';

enctype attribute of the form

Knowledge points:
 By default, the form transfer is a character stream and cannot transfer a binary stream. You can set the form's enctype Property to pass composite data.
 enctype The value of the property is:
 1. application/x-www-form-urlencoded:By default, it means that formatted text data is passed
 2. multipart/form-data: Composite form data(character string,file)This value must be set for file upload
 3. text/plain:It is used to deliver unformatted text data to the server, mainly user e-mail

Little knowledge about $_FILES

Super global variable $_FILES Is a two-dimensional array used to save the file information uploaded by the client to the server. The row of the two-dimensional array is the name of the file and there are five columns
1. $_FILES[]['name']:Uploaded file name
2. $_FILES[]['type']:The type of upload. This type is MIME type
3. $_FILES[]['size']: The size of the file, in bytes
4. $_FILES[]['tmp_name']:Temporary files when uploading files
5. $_FILES[]['error']:Error code value, with 0,1,2,3,4,6,7;0 Indicates correct

$_FILES [] ['error'] details

1. 0: correct
2. 1: File exceeds php.ini Maximum allowed in
3. 2: The file size exceeds the maximum allowed for the form
4. 3: Only some files are uploaded
5. 4: No files uploaded
6. 6: Temporary file not found
7. 7: File write failed

MAX_FILE_SIZE knowledge points

echo '<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2">
<input type="file" name="face">
<input type="submit" name="button" value="upload">
</form>';
# Set the maximum allowed value of 2 bytes for the form. Note that MAX_FILE_SIZE must be above the file field
# MAX_FILE_SIZE indicates the maximum value of files allowed to be uploaded by the form, which is the error when $_FILES['error']=2

Use of move_upload_file()

Explanation:
1. Move the uploaded file to the specified location
2. Function: move_upload_file(Temporary address,Destination address)
if(!empty($_POST)){
    if ($_FILES['face']['error']==0){
        move_uploaded_file($_FILES['face']['tmp_name'],'./'.$_FILES['face']['name']);
    }else{
        echo 'Upload error';
        echo ',Error code:'.$_FILES['face']['error'];
    }
}
echo '<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2158556">
<input type="file" name="face">
<input type="submit" name="button" value="upload">
</form>';
Note: uploading a file with the same name will overwrite the original file

File related configuration

1. post_max_size=8M: Maximum value allowed for the form
2. upload_max_filesize=2M:Allow upload file size
3. upload_tmp_dir=F:\PS\tmp: Specify temporary file address
4. file_uploads=On:Allow file upload
5. max_file_uploads=20:Allow 20 files to be uploaded at the same time

Optimize file upload

method:
Method 1: make the file name through the timestamp
 Method 2: Pass uniqid()Implementation to obtain a unique prefix based on the current time microseconds ID
# Method 1:
$path='clk.jpg';
echo time().rand(100,9999).strrchr($path,'.');# strrchr() finds the last occurrence of the specified character in the string
# Method 2: implemented by uniqid()
$path='clk.jpg';
echo uniqid().strrchr($path,'.'),'<br>';//Generate unique id
echo uniqid('goods_').strrchr($path,'.'),'<br>';//Generates a unique file name with a prefix
echo uniqid('goods_',true).strrchr($path,'.').'<br>';//Generates a unique id with a prefix and a random number

Verify file format

method:
Method 1: determine the file extension(Unrecognized file camouflage)
Method 2: use mime type(Unrecognized file camouflage)
Method 3: php_fileinfo extend(File camouflage can be prevented)
# Method 1: determine the file extension (file camouflage cannot be recognized)
# Compare the suffix of the file with the allowed suffix
if (!empty($_POST)) {
    $allow = array('.jpg', '.png', '.gif');//Allowed file extensions
    $ext = strrchr($_FILES['face']['name'], '.');//Upload file extension
    if (in_array($ext, $allow))
        echo 'Allow upload' . '<br>';
    else
        echo 'Upload not allowed' . '<br>';
}
# Method 2: use mime type (unable to recognize file camouflage)
if (!empty($_POST)) {
    $allow = array('image/jpeg', 'image/png', 'image/gif');//Allowed categories
    $ext = $_FILES['face']['type'];//Upload file category
    if (in_array($ext, $allow))
        echo 'Allow upload' . '<br>';
    else
        echo 'Upload not allowed' . '<br>';
}
# Method 3:
if (!empty($_POST)) {
    //Step 1: create finfo resource
    $info = finfo_open(FILEINFO_MIME_TYPE);
    var_dump($info);
    //Step 2: compare finfo resources with files
    $mime = finfo_file($info, $_FILES['face']['tmp_name']);
    //The third step is to compare whether it is legal
    $allow = array('image/jpeg', 'image/png', 'image/gif');
    echo in_array($mime,$allow)?'legitimate':'wrongful';
}

The html code involved in the three methods

echo '<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2158556">
<input type="file" name="face">
<input type="submit" name="button" value="upload">
</form>';
Precautions for method 3:
1. stay php.ini Middle opening php_info extend extension=php_fileinfo.dll
2. Attention, on fileinfo After extension, you can use finfo_*The function of.

Summary of validation format

1. The extension can be verified
2. You can verify the type of file
3. adopt file_info extend(Can prevent camouflage)

Examples of file upload

function check($file){
    if ($file['error']!=0){
        switch ($file['error']){
            case 1:
                return 'File size exceeds php.ini Maximum allowed in,The maximum value is:'.ini_get('upload_max_filesize');
            case 2:
                return 'The file size exceeds the maximum allowed for the form';
            case 3:
                return 'Only some files are uploaded';
            case 4:
                return 'No files uploaded';
            case 6:
                return 'Temporary file not found';
            case 7:
                return 'File write failed';
            default:
                return 'unknown error';
        }
    }
    # 2. Validation format
    $info=finfo_open(FILEINFO_MIME_TYPE);
    $mime=finfo_file($info,$file['tmp_name']);
    $allow=array('image/jpeg', 'image/png', 'image/gif');
    if (!in_array($mime,$allow)){
        return 'Upload only'.implode(',',$allow).'format';
    }
    # 3. Verify size
    $size=283558845;
    if ($file['size']>$size){
        return 'File size cannot exceed'.number_format($size/1024,1).'K';
    }
    # 4. Verify whether it is an HTTP upload
    if (!is_uploaded_file($file['tmp_name'])){
        return 'File is not HTTP_POST Uploaded';
    }
    return null;
}
# Modify the time zone. In php.ini, modify date.timezone=RPC
# Convert timestamp to format
echo date('Y-m-d H:i:s',time());//Convert the time stamp to the format of year, month, day, hour, minute and second
# If there is no time function, it also represents the timestamp of the current time
# Note: you can execute php without the involvement of Apache
if (isset($_POST['button'])){
    if (check($_FILES['face'])){
        echo check($_FILES['face']);
    }else{
        //File upload: the uploaded file is saved in the file of the day
        $foldername=date('Y-m-d');
        $folderpath="./upload/{$foldername}";//Folder path
        echo file_exists($folderpath);
        if (!file_exists($folderpath)){
            mkdir($folderpath,0777,true);
        }
        $filename=uniqid('',true).strrchr($_FILES['face']['name'],'.');//file name
        $filepath="{$folderpath}/{$filename}";//File path
        if(move_uploaded_file($_FILES['face']['tmp_name'],$filepath))
            echo 'Upload succeeded';
        else
            echo 'Upload failed'.'<br>';
    }
}
echo '<form method="post" enctype="multipart/form-data" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2158556">
<input type="file" name="face">
<input type="submit" name="button" value="upload">
</form>';

In fact, this is only a relatively safe file upload, which can be bypassed by hackers in many ways:
1. File name case bypass (for example, file names such as ASP and PHP bypass blacklist detection)
2. List bypass: attack with a list that is not in the blacklist, such as no cer or asa in the blacklist
3.: $data bypass
4. htaccess file: cooperate with the list to bypass. Uploading a custom. htaccess can easily bypass the detection
5. Space bypass
6. Cooperate to resolve vulnerabilities
7. Double suffix bypass
8. mime bypass
9.% 00,0x00,0x0a truncation
10. Special file name test.php. Or test.asp_

Parsing vulnerability:

Apache parsing vulnerability

test.php.aaa.bbb.ccc any suffix that is not in the blacklist and not in the Apache resolved whitelist
Apache will start parsing from the last position until it encounters an extension that can be resolved

IIS parsing vulnerability

  1. IIS6.0 has two parsing vulnerabilities when parsing asp format:
    • If the directory name ends with. asp,. asa,. cer,. cdx strings, all files in this directory will be parsed according to asp. eg: "test.asp/1.jpg"
    • As long as the file name contains. asp,. asa,. cer,. cdx, it will be parsed by asp first (/ xx.asp;.jpg /xx.asp:.jpg)
  2. IIS7.0/7.5 is a parsing vulnerability similar to Nginx when parsing php. For any file name, as long as the string "/ arbitrary file name. php" is appended to the URL, it will be parsed in the way of php
  3. Nginx < = 0.8.37 parsing vulnerability: when fast CGI is closed, adding% 00.php to a file path (/ xx.jpg) will parse / xx.jpg%00.php into a PHP file.

Posted by pjoshi on Wed, 20 Oct 2021 12:15:47 -0700