LoginSignup
9
7

More than 5 years have passed since last update.

PHPでcurlを使えない場合の対処法

Last updated at Posted at 2018-07-23

概要

PHPのコード内でcurlを使うときに、つまずいたのでメモ程度に。
そもそも、PHPには他の言語同様、色々パッケージが存在しているので、その関数が定義されているのかどうかを適宜確認して使うことが必要。

動作環境

~
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.4 LTS"

$ nginx -v
nginx version: nginx/1.14.0

$ php -v
PHP 7.1.19-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Jul  9 2018 13:12:24) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.1.19-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

解決方法

いたってシンプル。
php-curlのパッケージを追加すればイイだけ。

~
$  sudo apt-get install php7.1-curl

以下のコマンドで、自分のPC/サーバーに入っているphpのモジュール一覧を取得することができる。

~
$  php -m
[PHP Modules]
calendar
Core
ctype
curl  #curlが存在することを確認!
date
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
json
libxml
openssl
pcntl
pcre
PDO
pdo_pgsql
pgsql
Phar
posix
readline
Reflection
session
shmop
sockets
SPL
standard
sysvmsg
sysvsem
sysvshm
tokenizer
Zend OPcache
zlib

[Zend Modules]
Zend OPcache

ちなみにphpinfo()内にもcurlの項目ができているのを確認できる。
スクリーンショット 2018-07-23 11.49.51.png

実用例

以下のテスト用のコードを実行してみると、きちんとphp-curlがインストールされている場合、yahooの画面が表示されるはずである。

curl.php
<?php
  $url = "https://www.yahoo.co.jp/";
  $conn = curl_init(); #cURLセッションの初期化
  curl_setopt($conn, CURLOPT_URL, $url); #取得するURLを指定
  curl_setopt($conn, CURLOPT_RETURNTRANSFER, true); #実行結果を文字列で返す。
  $res =  curl_exec($conn);
  var_dump($res);
  curl_close($conn); #セッションの終了
?>

curlコマンドは、APIを叩くときに有効なので、PHPでも実装できるようにしたい。

9
7
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
9
7