トップへ(mam-mam.net/)

HTTP and HTTPS Requests in PHP Using file_get_contents and cURL — Sample Source Code Collection

Japanese

HTTP and HTTPS Requests in PHP Using file_get_contents and cURL — Sample Source Code Collection

You can perform HTTP and HTTPS requests in PHP using file_get_contents or cURL.

Things to Check First

When using file_get_contents for HTTP requests
The following setting in php.ini must be enabled:
allow_url_fopen = On
When using cURL for HTTP requests
cURL must be installed.
Also make sure the following line exists in your php.ini:
extension=curl
When making HTTPS requests
OpenSSL must be installed.
Also confirm that your php.ini contains:
extension=php_openssl

Making Requests with file_get_contents

GET Request

$options=[
  'http'=>[
    'method' => 'GET',
    'timeout'=>10, //Timeout in seconds
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

POST Request

//Data to send via POST
$data=['a'=>'ABCDEFG','b'=>'1'];
//Convert character encoding if required by the destination
mb_convert_variables('UTF-8', 'UTF-8', $data);
//Build query string
$data = http_build_query($data, "", "&");
$options=[
  'http'=>[
    'method' => 'POST',
    'timeout'=>10, //Timeout in seconds
    'header' => 'Content-Type: application/x-www-form-urlencoded'."\r\n".
                'Content-Length: '.strlen($data)."\r\n".
                'Cache-Control: no-cache',
    'content' => $data,
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

GET Request with Basic Authentication

$options=[
  'http'=>[
    'method' => 'GET',
    'timeout'=>10, //Timeout in seconds
    'header'=>'Authorization: Basic '.base64_encode('UserName'.':'.'Password')."\r\n"
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

GET Request to an HTTPS Site with an Invalid Certificate

$options=[
  'http'=>[
    'method' => 'GET',
    'timeout'=>10, //Timeout in seconds
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ],
  'ssl'=>[
    'verify_peer'=>false,
    'verify_peer_name'=>false,
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

GET Request to an HTTPS Site with an Invalid Certificate (Using a Server Certificate File)

$options=[
  'http'=>[
    'method' => 'GET',
    'timeout'=>10, //Timeout in seconds
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ],
  'ssl'=>[
    'verify_peer'=>true,
    'cafile'=>'/home/hoge.csr', //Server certificate file
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

When a Client Certificate Is Required for a GET Request

Use a client certificate that has been converted to PEM format.

$options=[
  'http'=>[
    'method' => 'GET',
    'timeout'=>10, //Timeout in seconds
    'ignore_errors' => true, //Retrieve content even if status code is 4xx or 5xx
  ],
  'ssl'=>[
    'verify_peer'=>false,
    'verify_peer_name'=>false,
    'local_cert', '/home/hoge.pem', //Client certificate (PEM format)
    'passphrase'=>'PassPhrase',
  ]
];
$context=stream_context_create($options);
//Specify the URL you want to request
$url='https://mam-mam.net/';
$res=file_get_contents($url,false,$context);
//Extract the HTTP response code from the first response header line
preg_match('/^HTTP\/1\.[0|1|x] ([0-9]+) (.*)$/',$http_response_header[0],$matches);
$http_response_code=$matches[1];  //HTTP response code
$http_response_text=$matches[2];  //HTTP response text
if($res){echo $res;}else{echo "error\n";}

Making Requests with cURL

GET Request

mb_internal_encoding("UTF-8");
$ch = curl_init();
//Set GET parameters
$get_param = '?get1='.curl_escape($ch,'GET Value1').'&get2='.curl_escape($ch,'GET Value2');
//Basic authentication (if required)
$hds = ["Authorization: Basic ".base64_encode('user name'.':'.'password'),];
//Specify the URL you want to request
$url='https://mam-mam.net/';
curl_setopt($ch, CURLOPT_URL, $url.$get_param);
curl_setopt($ch, CURLOPT_HTTPGET, true);          //Use GET method
curl_setopt($ch, CURLOPT_HTTPHEADER, $hds);       //Basic auth header
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //Do not verify server certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  //Do not check SAN/Common Name
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   //Return response as string
curl_setopt($ch, CURLOPT_TIMEOUT, 10);            //Timeout (seconds)
//Set User-Agent if needed
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X)');
$res = curl_exec($ch);

POST Request

mb_internal_encoding("UTF-8");
//Set POST data
$content = http_build_query(array('post1' => 'POST Value2', 'post2' => 'POST Value2'));
$ch = curl_init();
//Basic authentication (if required) and Content-Length header
$hds = [
  "Authorization: Basic ".base64_encode('ユーザー'.':'.'パスワード'),
  "Content-length: " . strlen($content),
];
//Specify the URL you want to request
$url='https://mam-mam.net/';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);             //Use POST method
curl_setopt($ch, CURLOPT_HTTPHEADER, $hds);       //Basic auth + Content-Length
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //Do not verify server certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  //Do not check SAN/Common Name
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   //Return response as string
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);   //Set POST data
curl_setopt($ch, CURLOPT_TIMEOUT, 10);            //Timeout (seconds)
//Set User-Agent if needed
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X)');
$res = curl_exec($ch);

PHP | Samples