# 实例技巧

## 合并多个文件

```php
<?php

$fh=fopen('dest.txt','a');

$fh1=fopen('file1.txt','r');
while( ($data=fgets($fh1)) !== false ){
    fwrite($fh,$data);
}
fclose($fh1);

$fh2=fopen('file2.txt','r');
while( ($data=fgets($fh2)) !== false  ){
    fwrite($fh,$data);
}
fclose($fh2);

fclose($fh);
```

## PHP创建网页快捷方式

```php
$Shortcut = "[InternetShortcut]
URL=http://www.baidu.com
IDList=[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2";

file_put_contents('百度.url',$Shortcut);
```

## pack 和 unpack 函数

[在PHP中读取二进制文件](https://blog.zengrong.net/post/1715.html)

[PHP中pack、unpack的详细用法](https://segmentfault.com/a/1190000008305573)

**pack 把数据打包成二进制数据**

```php
//如果指定的长度不够20,则剩余的长度都有空格填满.如abc只填充了3个字符长度,其他17个则以空格填满
$name = pack('A20', 'abc'); 
//有符号短整型(16位，主机字节序)
$age = pack('S', '28');
// 以null填充未满位置
$email = pack('a20', '509129@qq.com');
```

以上共42个字节

合并的写法

```php
$data = pack('A20Sa20', 'abc', '28', '509129@qq.com');
```

**unpack 把二进制数据解包**

必须知道打包时的格式解包

```php
$items=unpack('A20name/Sage/a20email',$data);
print_r($items);
exit;
```

## 判断文件类型

一些时候,后缀名并不能正确判断出文件文类,以下只是一个采用二进制分析文件类型,以作记录

```php
function checkFileType($fileName){
        $file     = fopen($fileName, "rb");
        $bin      = fread($file, 2); //只读2字节
        fclose($file);
        $strInfo  = unpack("C2chars", $bin);// C为无符号整数，网上搜到的都是c，为有符号整数，这样会产生负数判断不正常
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';
        return ($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/);  
}
```

**采用exif\_imagetype系统函数,但是一些特殊的无法判断,比如说word等,这种则需要使用上面的方式**

```php
function checkFileType($fileName){
    $typeCode = exif_imagetype($fileName);
    return $typeCode == IMAGETYPE_JPEG || $typeCode == IMAGETYPE_GIF || $typeCode == IMAGETYPE_PNG;
}
```

**采用pathinfo 获取文件后缀,这种方式并不能正确的判断文件类型.**

```php
function getExtension($filename) {
    return pathinfo($filename, PATHINFO_EXTENSION);
}
echo getExtension($filename);
```

## 文件指针的定位操作

适用于二进制文件

```php
fseek () - 在文件指针中定位
ftell() - 返回文件指针读/写的位置
rewind() - 倒回文件指针的位置
feof - 测试文件指针是否到了文件结束的位置
```

```php
$myfile =fopen('top.png' ,'r');
fseek($myfile,1);
$bytes=fread($myfile,3);
echo($bytes);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phper.shujuwajue.com/phpwen-jian-bian-cheng/shi-li-ji-qiao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
