0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでURLが存在しているか確認する

0
Posted at

概要

タイトルのとおり、あるURLが存在しているかを確認したいときに使った方法です。

コード

file_get_contents に引数をつけて、最初の1バイトだけ読み込んで判断しています。

if(@file_get_contents('https://xxx/xxx/xxx', NULL, NULL, 0, 1)){
	//ファイルあり処理
}else{
	//ファイルなし処理
}

参考

おまけ PHPでファイルダウンロード

<?php
//ダウンロード元URL
$url = 'https://xxx/xxx/xxx';
//保存ファイル名
$filename = 'saved.zip';
if(@file_get_contents($url, NULL, NULL, 0, 1)){
	//ダウンロード処理
	header('Content-Type: application/force-download');
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	readfile($url);
}else{
	//ファイルなし処理
	header('Content-Type: text/html; charset=UTF-8');
	echo 'エラーが発生しました。ファイルが存在しません。';
}

URL先のファイルサイズの取得はできていませんので、ダウンロード中のパーセンテージでの進捗はとれません。

これをいれればよさげですが、未検証です。
http://www.muzin.org/wp/webprogramming/php/file-size_52/

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?