我一直在写一段代码,将通过WordPress的wp_remote_request函数发布图像,并且发生了一些我不太理解的奇怪事件。
当我对其进行测试时,它会起作用,然后当我尝试多次但失败时,然后再次尝试并起作用,这是零星的,我无法确定问题所在。其他人以前有这个问题吗?
$boundary = wp_generate_password(24);
$payload = '';
$fileContents = file_get_contents( $file_path );
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($fileContents);
if($fileContents) {
// Upload the file
if ( $file_path ) {
$payload .= '--' . $boundary;
$payload .= "\r\n";
$payload .= 'Content-Disposition: form-data; name="file"; filename="' . basename( $file_path ) . '"' . "\r\n";
$payload .= 'Content-Type: '. $mime_type . "\r\n";
$payload .= "\r\n";
$payload .= $fileContents;
$payload .= "\r\n";
}
$payload .= '--' . $boundary . '--';
$response = wp_remote_request( CFMH_API_URL . '/api/artwork/' . $showId . '/upload', array(
'body' => $payload,
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( get_option('X') . ':' . get_option('X') ),
'content-type' => 'multipart/form-data; boundary=' . $boundary
),
));
// Returns the url of the uploaded file
return ! empty( $response->url ) ? $response->url : '';
}
已解决问题-请勿使用:
$boundary = wp_generate_password(24)
这有时会导致无效边界的使用:
$boundary = hash('sha256', uniqid('', true));