HTTP ストリーム ignore_errors オプション in PHP 5.3

| | コメント(26) | トラックバック(0)

5.3 から HTTP ストリームのコンテキストに ignore_errors オプションが利用できるようになるそうです。

01 Aug 2008, PHP 5.3.0 Alpha 1
- Improved streams:
  . Added "ignore_errors" option to http fopen wrapper. (David Zulke, Sara)

今までは fopen() や file_get_contents() の URL に HTTP ストリームを指定した場合、HTTP レスポンスのステータスコードが(最終的に) 2xx でなければレスポンスボディを取得できませんでした。ところが HTTP の仕様としてレスポンスボディを設定できるステータスコードは 2xx だけではありません。PHP 5.3 からはコンテキストに ignore_errors = true を設定すると、エラーとなっていたステータスコードを無視するようになります。次のコードは HTTP サーバが 404 として用意しているレスポンスボディを取得します。

$context = stream_context_create(array('http' => array('ignore_errors' => true)));
echo file_get_contents('http://www.example.com/not-exists-url', false, $context);

また、REST スタイルな Web API にアクセスして取得に失敗した時に、それが認証が必要だったせいなのか、サービスが存在していなかったのか、リクエストの内容が間違っていたのか、さまざまな状態を判別するのに使えるステータスコードを拾えるようになります。

例として、ハイパーテキスト・コーヒーポット制御プロトコルを実装した HTCPCP サーバに HTTP ストリームを使ってアクセスするコードを上げます。

<php
// なにもしない、なにも足さない、HTCPCP サーバ

switch (strtoupper($_SERVER['REQUEST_METHOD']))
{
    case 'POST':
    case 'BREW':
    case 'WHEN':
        header('HTTP/1.1 418 I\'m a teapot', true, 418);
        header('Content-Type: text/plain', true);
        echo '私は急須だ。';
        break;
    
    default:
        header('HTTP/1.1 501 Not Implemented', true, 501);
        echo '要求されたメソッドは未実装です。';
        break;
}
<php
// HTCPCP サーバに対して BREW メソッドを発行するクライアントプログラム

$coffeepot = 'http://www.example.com/coffeepot.php';
$options = array(
    'http' => array(
        'method' => 'BREW',
        'header' => array('Content-Type: message/coffeepot'),
        'content' => 'start',
        'ignore_errors' => true,
    ),
);
$stream = @fopen($coffeepot, 'rb', false, stream_context_create($options));
$meta = stream_get_meta_data($stream);
preg_match('|\\AHTTP/\\d\\.\\d +(?<status_code>\\d{3}) +(?<reason_phrase>.*)\\E|', $meta['wrapper_data'][0], $captures);
echo $captures['status_code'], '/', $captures['reason_phrase'], PHP_EOL;
fpassthru($stream);
fclose($stream);

結果

418/I'm a teapot
私は急須だ。

怒られちゃいましたね。こんな具合に、Web API をちょっと叩いてみたい時に PEAR::HTTP_Client や Zend_Http_Client 等の外部ライブラリに頼らずともできるようになるのはありがたいです。

トラックバック(0)

このブログ記事を参照しているブログ一覧: HTTP ストリーム ignore_errors オプション in PHP 5.3

このブログ記事に対するトラックバックURL: http://zenith.sakura.ne.jp/mt/mt-tb.cgi/35

コメント(26)

Ok. I believe you are appropriate!

I found your blog site on google and check several of the early posts. Continue to keep up the good work. I just added up your RSS feed to my MSN News Reader. Looking forward to reading through far more from you later on!

I found your blog site on google and check several of the early posts. Continue to keep up the good work. I just added up your RSS feed to my MSN News Reader. Looking forward to reading through far more from you later on

There are many online designer replica handbags store, you should reduce your risk with online shopping. You would better choose the online designer replica handbags from a online store which has a good reputation, high quality materials or parts

chanel カメリア 財布|chanel_as5.innmarketplace.com|chanel カメリア 財布
シャネル 楽天 http://chanel_bir.oliverelectronics.com

DorothyTut :

Absolutely NEW update of SEO/SMM software "XRumer 16.0 + XEvil 3.0":
captchas recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of demo videos about XEvil in YouTube.
Good luck ;)


XRumer20170718

ArleneDub :

Revolutional update of SEO/SMM software "XRumer 16.0 + XEvil":
captchas breaking of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? There are a lot of impessive videos about XEvil in YouTube.
See you later ;)


XRumer20170721

ArleneDub :

Revolutional update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captcha regignizing of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another categories of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of impessive videos about XEvil in YouTube.
See you later!


XRumer20170721

ArleneDub :

Absolutely NEW update of SEO/SMM software "XRumer 16.0 + XEvil":
captcha recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another types of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of introducing videos about XEvil in YouTube.
Good luck!


XRumer20170721

Flossiewed :

Revolutional update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captchas regignizing of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of introducing videos about XEvil in YouTube.
Good luck!


XRumer20170725

Flossiewed :

Revolutional update of SEO/SMM software "XRumer 16.0 + XEvil 3.0":
captcha breaking of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? You can find a lot of introducing videos about XEvil in YouTube.
See you later!


XRumer20170725

Flossiewed :

Revolutional update of SEO/SMM package "XRumer 16.0 + XEvil":
captchas solution of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another size-types of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? You can find a lot of impessive videos about XEvil in YouTube.
See you later!


XRumer20170725

Flossiewed :

Absolutely NEW update of SEO/SMM software "XRumer 16.0 + XEvil":
captchas solution of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another categories of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of impessive videos about XEvil in YouTube.
See you later ;)


XRumer20170725


препараты для похудения которые реально помогают http://диетоника.товар-топ.рф

Carolynfooli :

Absolutely NEW update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captcha recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another types of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of demo videos about XEvil in YouTube.
You read it - then IT WORKS!
See you later ;)


XRumer201708

Carolynfooli :

Revolutional update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captcha solving of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another categories of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? There are a lot of introducing videos about XEvil in YouTube.
You read it - then IT WORKS!
Good luck!


XRumer201708

Carolynfooli :

Absolutely NEW update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captchas recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another categories of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? You can find a lot of demo videos about XEvil in YouTube.
You read it - then IT WORKS!
Good luck!


XRumer201708

Где дешево купить Сиалис в Северной столице

Различные неприятности с потенцией, рано или поздно, начинают посещать каждого мужчину, вне зависимости от его возраста и суммарного количества у него вредных привычек. К всеобщему счастью современная медицина уже довольно давно смогла создать эффективные лекарства для решения интимных проблем, первым препаратом этого типа стала пресловутая Виагра. Но в обычных аптеках этот препарат стоит так много, что наши взрослые мужики выбирают отказ от нормального секса, вместо покупки подобных препаратов.

К большому счастью в сети появилась хорошая интернет аптека, что торгует нормальным Сиалисом по вполне маленьким ценам, речь идёт о ресурсе сиалис-спб.рф тут вы можете купить [url=http://сиалис-спб.рф/]сиалис 5мг цена спб[/url] по самой низкой в стране стоимости.

Не взирая на то, что указанная аптека ориентируется на Петербург, она доставляет лекарства по всей стране, пакуя их в специальные посылочки с наложенным платежом. Сиалис продаётся в фирменных коробочках, а маленький ценник обусловлен отсутствием длинной цепочки перепродавцов, как в случае работы с государственными аптеками.

Все покупки в этой сетевой-аптеке на миллион процентов анонимны, данные клиента нужны исключительно для отправки посылки, и после они стираются и нигде не хранятся. Для пущей анонимности все пачки упаковываются в темные пакеты, дабы вы не попадали в сомнительные ситуации в почтовых отделениях.

Сиалис — это хороший препарат для усиления потенции, основой для которого служит действующее вещество Тадалафил, а оно работает в десять раз эффективнее тупой Виагры и обладает малым числом побочных действий со стороны сердечной и сосудистой систем. Сиалис выпускается фармацевтической корпорацией Centurion и проходит все уровни тестирования на безопасность.

Carolynfooli :

Revolutional update of SEO/SMM package "XRumer 16.0 + XEvil":
captchas recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another size-types of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? There are a lot of impessive videos about XEvil in YouTube.
You read it - then IT WORKS!
Good luck!


XRumer201708

Carolynfooli :

Absolutely NEW update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captchas recognition of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? There are a lot of impessive videos about XEvil in YouTube.
You read it - then IT WORKS!
See you later ;)


XRumer201708

Carolynfooli :

Absolutely NEW update of SEO/SMM software "XRumer 16.0 + XEvil":
captchas breaking of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another types of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? You can find a lot of impessive videos about XEvil in YouTube.
You read it - then IT WORKS!
Good luck ;)


XRumer201708

Carolynfooli :

Revolutional update of SEO/SMM software "XRumer 16.0 + XEvil 3.0":
captcha regignizing of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another types of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

Interested? You can find a lot of demo videos about XEvil in YouTube.
You read it - then IT WORKS!
See you later ;)


XRumer201708

Carolynfooli :

Absolutely NEW update of SEO/SMM package "XRumer 16.0 + XEvil 3.0":
captcha regignizing of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another subtypes of captcha,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM programms: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? You can find a lot of introducing videos about XEvil in YouTube.
You read it - then IT WORKS!
Good luck!


XRumer201708

Carolynfooli :

Absolutely NEW update of SEO/SMM package "XRumer 16.0 + XEvil":
captchas solution of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
and more than 8400 another types of captchas,
with highest precision (80..100%) and highest speed (100 img per second).
You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other programms.

Interested? You can find a lot of introducing videos about XEvil in YouTube.
You read it - then IT WORKS!
See you later!


XRumer201708

Leeannoweva :

SEO / SMMソフトウェア "XRumer 16.0 + XEvil 3.0"の革新的なアップデート:
Google、Facebook、Bing、Hotmail、SolveMedia、Yandex、
さらに8400種類以上のキャプチャ、
最高精度(80..100%)と最高速度(毎秒100イグジット)を備えています。
XEvil 3.0は、XRumer、GSA SER、ZennoPoster、Srapebox、Senukeなど100以上の他のプログラマに最も人気のあるSEO / SMMプログラムに接続できます。

興味がある? YouTubeでXEvilに関するビデオを紹介しています。
あなたはそれを読んで - 次にそれは働く!
がんばろう ;)


XRumer201708c

Leeannoweva :

SEO / SMMソフトウェア "XRumer 16.0 + XEvil 3.0"の革新的なアップデート:
Google、Facebook、Bing、Hotmail、SolveMedia、Yandex、
さらに8400種類以上のキャプチャ、
最高精度(80..100%)と最高速度(毎秒100イグジット)を備えています。
XEvil 3.0は、XRumer、GSA SER、ZennoPoster、Srapebox、Senukeなど100以上の他のプログラマに最も人気のあるSEO / SMMプログラムに接続できます。

興味がある? YouTubeでXEvilに関するビデオを紹介しています。
あなたはそれを読んで - 次にそれは働く!
がんばろう ;)


XRumer201708c

コメントする


画像の中に見える文字を入力してください。

このブログ記事について

このページは、zenithが2008年8月13日 19:23に書いたブログ記事です。

ひとつ前のブログ記事は「デスクトップバトン」です。

次のブログ記事は「get_called_class() in PHP 5.3」です。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。

Powered by Movable Type 4.12