튜토리얼
php는 원격 사진을 수집하여 로컬에 저장합니다
2024-03-23 23:27:30
저자:admin
/**
* 원격 사진 수집
* @param string $url 원격 파일 주소
* @param string $filename 저장된 파일 이름(비어 있으면 임의로 생성된 파일 이름, 그렇지 않으면 원본 파일 이름)
* @param array $fileType 허용되는 파일 형식
* @param string $dirName 파일이 저장된 경로
* @param int $type 원격으로 파일을 얻는 방법
* @return json 파일 이름과 파일 저장 경로를 반환합니다.
*/
함수 download_image($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif', 'png'), $type = 1)
{
if ($url == '')
{
거짓을 반환;
}
//파일의 원본 파일 이름을 가져옵니다.
$defaultFileName = 기본 이름($url);
// 파일 형식 가져오기
$suffix = substr(strrchr($url, '.'), 1);
if (!in_array($suffix, $fileType))
{
거짓을 반환;
}
//저장 후 파일명 설정
$fileName = $fileName == '' ? 시간() . 랜드(0, 9) . '.' . $접미사: $기본파일이름;
// 원격 파일 리소스 얻기
if($유형)
{
$ch = 컬_초기화();
$타임아웃 = 30;
컬_setopt($ch, CURLOPT_URL, $url);
컬_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
컬_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file = 컬_exec($ch);
컬_닫기($ch);
}
그렇지 않으면
{
ob_start();
파일 읽기($url);
$file = ob_get_contents();
ob_end_clean();
}
//파일 저장 경로 설정
$dir이름 = $dir이름;
if (!file_exists($dirName))
{
mkdir($dirName, 0777, true);
}
// 파일 저장
$res = fopen($dirName . '/' . $fileName, 'a');
fwrite($res, $file);
fclose($res);
반환 배열(
'파일이름' => $파일이름,
'saveDir' => $dir이름
);
}