cURL請求 - kouji6309/SingleMVC GitHub Wiki

SingleMVC ²�ƤF�@�t�C cURL �ާ@�A�Ҳ��~�� Model ��Y�i�ϥΡA�]�t�F�H�U�|�Ӥ�k�G

���\��D�n�O�B�z HTTP/HTTPS ��w�A��l�p FTP/telnet ����w�A���ݦۦ�I�s cURL ������ơC�|�ӬҬ��R�A��k�A�ϥήɥ� self:: �I�s�C�U�������@�ǰ򥻥Ϊk�C

��@�ШD

�ϥ� GET �ШD�A²��ǤJ���}�Y�i�F�Y�� Query �ѼơA�i�[�b�᭱�C

// �@��ШD
$html = self::request('https://www.example.com/');

// ���Ѽ�
$html = self::request('https://www.example.com/', 'GET', [
    'key' => 'value'
]);

�ϥ� POST �Ǹ�ơA�Y�� Query �ѼơA�H���� _GET ��b data �ѼƸ̭��C

// �@��ШD
$html = self::request('https://www.example.com/', 'POST', [
    'key' => 'value'
]);

// URL ���Ѽ�
$html = self::request('https://www.example.com/', 'POST', [
    'key' => 'value',
    '_GET' => [
        'get_key' => 'get_value'
    ]
]);

�Y�ݭn���o HTTP header�A�Ĥ��ӰѼƶǤJ true

$response = self::request('https://www.example.com/', 'GET', [
    'key' => 'value'
], [], true);

request �|�Ǧ^���浲�G�A�Y�n���o cURL ����A�ݧ�� request_async�C

�h�ӽШD

�Y�P�ɭn���h�ӽШD(�����h�����)�A�ݨϥ� request_async �إ� cURL ����A�զX���}�C��A�I�s request_run �Ӱ���C

$chs = [];
for ($i = 1; $i <= 10; $i++) {
    $chs[] = self::request_async('https://www.example.com/api/news', 'GET', [
        'id' => $i
    ]);
}
$result = self::request_run($chs);

�O�_�Ǧ^ HTTP header �O����ɤ~�M�w�A�ҥH request_async �ä��t get_header �ѼơArequest_run �~���C

Cookie �]�w

�@�뱡�p�U�A�C�ӽШD���O�W�ߪ��A�Y�ШD���s��ʡA�Ҧp�ݭn���n�J�A�h�ݭn�� Cookie �x�s�|�� ID�C�ϥΦ��\��ݭn���a���x�s Cookie�A�]���ݭn�]�w COOKIE_DIR�C�q�`�|�w�q�b config.php �̭��C

define('COOKIE_DIR', sys_get_temp_dir());

�x�s Cookie �ɡA�i�H����ɦW�A�]�w�b option ���� Cookie-File�C�O���s�򪺽ШD�ݨϥΦP�@�� Cookie �ɮפ~��C

$cookie_file = 'www.example.com.tmp';

// �Ĥ@�ӽШD
$html = self::request('https://www.example.com/login', 'POST', [
    'username' => 'user', 'password' => '********'
], [
    'Cookie-File' => $cookie_file
]);

// �ĤG�ӽШD
$html = self::request('https://www.example.com/user/info', 'GET', [], [
    'Cookie-File' => $cookie_file
]);

cURL �����Ш즹�����A�i�H�ݨ�L�ج[���Ѫ��\����Ʈw �M�K�X����A�Բӥ\��Ь��o���C