Home Backend Development PHP Tutorial php-curl封装[避免下传文件二义性Bug]

php-curl封装[避免下传文件二义性Bug]

Jun 13, 2016 pm 01:13 PM
behavior curl define request

php-curl封装[避免上传文件二义性Bug]

由于php的curl在curl_setopt($curl, CURLOPT_POSTFIELDS, xxx)时, 当xxx为数组时, 如果值的第一个字符是@, 则认为是文件上传, 当同时需要上传文件, 也需要提交可能首字符为@的其他普通数据时, 存在冲突. 因此, 在api_common.php中的post数据的设置进行了封装


<?php /**
 * php-curl库封装
 * author: selfimpr
 * blog: http://blog.csdn.net/lgg201
 * mail: lgg860911@yahoo.com.cn
 */

define('API_CURL_UPLOAD_FILE',							'__file');

#支持的请求方法
define('REQUEST_METHOD_GET',							'GET');
define('REQUEST_METHOD_POST',							'POST');
define('REQUEST_METHOD_HEAD',							'HEAD');

#请求行为
define('REQUEST_BEHAVIOR_ALLOW_REDIRECT',				'allow_redirect');
define('REQUEST_BEHAVIOR_MAX_REDIRECT',					'max_redirect');
define('REQUEST_BEHAVIOR_USER_AGENT',					'user_agent');
define('REQUEST_BEHAVIOR_AUTOREFERER',					'autoreferer');
define('REQUEST_BEHAVIOR_UPLOAD',						'upload');
define('REQUEST_BEHAVIOR_CONNECTTIMEOUT',				'connecttimeout');
define('REQUEST_BEHAVIOR_DNS_CACHE_TIMEOUT',			'dns_cache_timeout');
define('REQUEST_BEHAVIOR_TIMEOUT',						'timeout');
define('REQUEST_BEHAVIOR_ENCODING',						'encoding');
define('REQUEST_BEHAVIOR_ERROR_HANDLER',				'error_handler');
define('REQUEST_BEHAVIORS',								'behaviors');
$GLOBALS[REQUEST_BEHAVIORS]	= array(
	REQUEST_BEHAVIOR_ALLOW_REDIRECT				=> TRUE, 
	REQUEST_BEHAVIOR_MAX_REDIRECT				=> 5, 
	REQUEST_BEHAVIOR_USER_AGENT					=> 'curl-lib', 
	REQUEST_BEHAVIOR_AUTOREFERER				=> TRUE, 
	REQUEST_BEHAVIOR_UPLOAD						=> FALSE, 
	REQUEST_BEHAVIOR_CONNECTTIMEOUT				=> 3, 
	REQUEST_BEHAVIOR_DNS_CACHE_TIMEOUT			=> 3600, 
	REQUEST_BEHAVIOR_TIMEOUT					=> 3, 
	REQUEST_BEHAVIOR_ENCODING					=> 'gzip', 
	REQUEST_BEHAVIOR_ERROR_HANDLER				=> '__default_curl_error_handler', 
);

define('MULTIPART_FORM_DATA_HEAD_FMT',				'Content-Type: multipart/form-data; boundary=----------------------------%s');
define('MULTIPART_FORM_DATA_BODY_STRING',			"------------------------------%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n");
define('MULTIPART_FORM_DATA_BODY_FILE',				"------------------------------%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: application/octet-stream\r\n\r\n%s\r\n");
define('MULTIPART_FORM_DATA_BODY_END',				"------------------------------%s--\r\n\r\n");

#响应键值
define('RESP_CODE',									'resp_code');
define('RESP_BODY',									'resp_body');
define('RESP_HEADER',								'resp_header');

#HTTP 1xx状态验证
define('HTTP_1XX_RESP',								'/^HTTP\/1.[01] 1\d{2} \w+/');

#默认错误处理的错误消息
define('E_CURL_ERROR_FMT',								'curl "%s" error[%d]: %s');

#默认的curl错误处理
function __default_curl_error_handler($curl, $url, $errno, $errstr) {
	trigger_error(sprintf(E_CURL_ERROR_FMT, $url, $errno, $errstr), E_USER_ERROR);
}
#切换CURL请求方法
function __method_switch($curl, $method) {
	switch ( $method) {
		case REQUEST_METHOD_POST:
			__curl_setopt($curl, CURLOPT_POST, TRUE);
			break;
		case REQUEST_METHOD_HEAD:
			__curl_setopt($curl, CURLOPT_NOBODY, TRUE);
			break;
		case REQUEST_METHOD_GET:
			__curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
			break;
		default:
			break;
	}
}
#设置默认头信息
function __default_header_set($curl) {
	__curl_setopt($curl, CURLOPT_RETURNTRANSFER,			TRUE);
	__curl_setopt($curl, CURLOPT_HEADER,					TRUE);
	__curl_setopt($curl, CURLOPT_FOLLOWLOCATION,			(bool)curl_behavior(REQUEST_BEHAVIOR_ALLOW_REDIRECT));
	__curl_setopt($curl, CURLOPT_MAXREDIRS,					(int)curl_behavior(REQUEST_BEHAVIOR_MAX_REDIRECT));
	__curl_setopt($curl, CURLOPT_USERAGENT,					(string)curl_behavior(REQUEST_BEHAVIOR_USER_AGENT));
	__curl_setopt($curl, CURLOPT_AUTOREFERER,				(bool)curl_behavior(REQUEST_BEHAVIOR_AUTOREFERER));
	__curl_setopt($curl, CURLOPT_UPLOAD,					(bool)curl_behavior(REQUEST_BEHAVIOR_UPLOAD));
	__curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,			(int)curl_behavior(REQUEST_BEHAVIOR_CONNECTTIMEOUT));
	__curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT,			(int)curl_behavior(REQUEST_BEHAVIOR_DNS_CACHE_TIMEOUT));
	__curl_setopt($curl, CURLOPT_TIMEOUT,					(int)curl_behavior(REQUEST_BEHAVIOR_TIMEOUT));
	__curl_setopt($curl, CURLOPT_ENCODING,					(string)curl_behavior(REQUEST_BEHAVIOR_ENCODING));
}
#设置用户自定义头信息
function __custom_header_set($curl, $headers = NULL) {
	if ( empty($headers) ) return ;
	if ( is_string($headers) ) 
		$headers	= explode("\r\n", $headers);
	#类型修复
	foreach ( $headers as &$header ) 
		if ( is_array($header) ) 
			$header	= sprintf('%s: %s', $header[0], $header[1]);
	__curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
#设置请求body
function __datas_set($curl, $datas = NULL) {
	if ( empty($datas) ) return ;
	if ( is_array($datas) ) {
		$custom_body		= FALSE;
		$uniqid				= uniqid();
		$custom_body_str	= '';
		foreach ( $datas as $name => $data ) {
			if ( is_array($data) && array_key_exists(API_CURL_UPLOAD_FILE, $data) ) {
				$file	= $data[API_CURL_UPLOAD_FILE];
				if ( file_exists($file) ) {
					$custom_body		= TRUE;
					$custom_body_str	.= sprintf(MULTIPART_FORM_DATA_BODY_FILE, 
										$uniqid, $name, 
										$file, file_get_contents($file));
				}
			} else {
				$custom_body_str		.= sprintf(MULTIPART_FORM_DATA_BODY_STRING, 
										$uniqid, $name, $data);
			}
		}
		if ( $custom_body ) {
			curl_setopt($curl, CURLOPT_HTTPHEADER, array(sprintf(MULTIPART_FORM_DATA_HEAD_FMT, $uniqid)));
			$datas				= $custom_body_str . sprintf(MULTIPART_FORM_DATA_BODY_END, $uniqid);
		}
	}
	__curl_setopt($curl, CURLOPT_POSTFIELDS, $datas);
}
#对curl_setopt的封装
function __curl_setopt($curl, $optname, $optval) {
	curl_setopt($curl, $optname, $optval);
	__curl_error($curl);
}
#curl错误检查处理
function __curl_error($curl) {
	if ( curl_errno($curl) ) {
		$url	= curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
		$errno	= curl_errno($curl);
		$errstr	= curl_error($curl);
		$errh	= curl_behavior(REQUEST_BEHAVIOR_ERROR_HANDLER);
		if ( function_exists($errh) )
			$errh($curl, $url, $errno, $errstr);
	}
}

#api默认行为切换
function curl_behavior($names, $values = NULL) {
	if ( !is_string($names) && !is_array($names) ) return ;
	if ( !is_null($values) ) {
		if ( is_string($names) ) 
			$GLOBALS[REQUEST_BEHAVIORS][$names]	= $values;
		else if ( is_array($names) && !is_array($values) )
			foreach ( $names as $name )
				$GLOBALS[REQUEST_BEHAVIORS][$name]	= $values;
		else if ( is_array($names) && is_array($values) )
			foreach ( $names as $k => $name ) 
				$GLOBALS[REQUEST_BEHAVIORS][$name]	= $values[$k];
	}
	if ( is_string($names) ) {
		$return	= $GLOBALS[REQUEST_BEHAVIORS][$names];
	} else if ( is_array($names) ) {
		$return	= array();
		foreach ( $names as $name ) 
			$return[$name]	= array_key_exists($name, $GLOBALS[REQUEST_BEHAVIORS]) 
							? $GLOBALS[REQUEST_BEHAVIORS][$name]
							: NULL;
	}
	return $return;
}
#请求入口
function curl_request($url, $method, $datas = NULL, $headers = NULL) {
	$curl	= curl_init($url);
	__method_switch($curl, $method);
	__default_header_set($curl);
	__custom_header_set($curl, $headers);
	__datas_set($curl, $datas);
	$response	= curl_exec($curl);
	__curl_error($curl);
	$status_code	= curl_getinfo($curl, CURLINFO_HTTP_CODE);
	$components		= explode("\r\n\r\n", $response);
	$i				= -1;
	while ( ++ $i  $status_code, 
		RESP_HEADER	=> $headers, 
		RESP_BODY	=> $body, 
	);
}
#GET请求
function curl_get($url, $headers = NULL) {
	return curl_request($url, REQUEST_METHOD_GET, NULL, $headers);
}
#POST请求
function curl_post($url, $datas = NULL, $headers = NULL) {
	return curl_request($url, REQUEST_METHOD_POST, $datas, $headers);
}
#HEAD请求
function curl_head($url, $headers = NULL) {
	return curl_request($url, REQUEST_METHOD_HEAD, NULL, $headers);
}
#构造上传文件字段
function curl_post_file($file) {
	return array(
		API_CURL_UPLOAD_FILE	=> $file, 
	);
}
#读取响应码
function curl_resp_code($resp) {
	return $resp[RESP_CODE];
}
#读取响应头
function curl_resp_header($resp) {
	return $resp[RESP_HEADER];
}
#读取响应体
function curl_resp_body($resp) {
	return $resp[RESP_BODY];
}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to realize the mutual conversion between CURL and python requests in python How to realize the mutual conversion between CURL and python requests in python May 03, 2023 pm 12:49 PM

Both curl and Pythonrequests are powerful tools for sending HTTP requests. While curl is a command-line tool that allows you to send requests directly from the terminal, Python's requests library provides a more programmatic way to send requests from Python code. The basic syntax for converting curl to Pythonrequestscurl command is as follows: curl[OPTIONS]URL When converting curl command to Python request, we need to convert the options and URL into Python code. Here is an example curlPOST command: curl-XPOST https://example.com/api

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

PHP8.1 released: Introducing curl for concurrent processing of multiple requests PHP8.1 released: Introducing curl for concurrent processing of multiple requests Jul 08, 2023 pm 09:13 PM

PHP8.1 released: Introducing curl for concurrent processing of multiple requests. Recently, PHP officially released the latest version of PHP8.1, which introduced an important feature: curl for concurrent processing of multiple requests. This new feature provides developers with a more efficient and flexible way to handle multiple HTTP requests, greatly improving performance and user experience. In previous versions, handling multiple requests often required creating multiple curl resources and using loops to send and receive data respectively. Although this method can achieve the purpose

How to handle 301 redirection of web pages in PHP Curl? How to handle 301 redirection of web pages in PHP Curl? Mar 08, 2024 am 11:36 AM

How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

defineHow to define multi-line macros defineHow to define multi-line macros Oct 11, 2023 pm 01:24 PM

define defines a multi-line macro by using `\` to divide `do { \ printf("%d\n", x); \ } while (0)` into multiple lines for definition. In a macro definition, the backslash `\` must be the last character of the macro definition and cannot be followed by spaces or comments. When using `\` for line continuation, be careful to keep the code readable and make sure there is a `\` at the end of each line.

What does php request mean? What does php request mean? Jul 07, 2021 pm 01:49 PM

The Chinese meaning of request is "request". It is a global variable in PHP and is an array containing "$_POST", "$_GET" and "$_COOKIE". The "$_REQUEST" variable can obtain data and COOKIE information submitted by POST or GET.

what is linux curl what is linux curl Apr 20, 2023 pm 05:05 PM

In Linux, curl is a very practical tool for transferring data to and from the server. It is a file transfer tool that uses URL rules to work under the command line; it supports file upload and download, and is a comprehensive transfer tool. . Curl provides a lot of very useful functions, including proxy access, user authentication, ftp upload and download, HTTP POST, SSL connection, cookie support, breakpoint resume and so on.

See all articles