>  기사  >  백엔드 개발  >  PHP에서 게시물 요청을 보내는 방법

PHP에서 게시물 요청을 보내는 방법

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼원래의
2019-09-27 16:03:3436251검색

PHP에서 게시물 요청을 보내는 방법

이 글에서는 주로 PHP가 게시물 요청을 보내는 세 가지 방법을 소개하며, 필요한 친구는 게시물 제출 데이터를 참조할 수 있습니다. 다음 .

관련 권장 사항: "php 입문 튜토리얼"

방법 1: file_get_content 버전

/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_post($url, $post_data) {
  
  $postdata = http_build_query($post_data);
  $options = array(
    'http' => array(
      'method' => 'POST',
      'header' => 'Content-type:application/x-www-form-urlencoded',
      'content' => $postdata,
      'timeout' => 15 * 60 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  
  return $result;
}
  
//使用方法
$post_data = array(
  'username' => 'stclair2201',
  'password' => 'handan'
);
send_post('http://www.jb51.net', $post_data);
추천 매뉴얼 : php 완전 자율 학습 매뉴얼

방법 2: 소켓 버전

<?php
/**
 * Socket版本
 * 使用方法:
 * $post_string = "app=socket&version=beta";
 * request_by_socket(&#39;chajia8.com&#39;, &#39;/restServer.php&#39;, $post_string);
 */
function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {
  $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
  if (!$socket) die("$errstr($errno)");
  fwrite($socket, "POST $remote_path HTTP/1.0");
  fwrite($socket, "User-Agent: Socket Example");
  fwrite($socket, "HOST: $remote_server");
  fwrite($socket, "Content-type: application/x-www-form-urlencoded");
  fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
  fwrite($socket, "Accept:*/*");
  fwrite($socket, "");
  fwrite($socket, "mypost=$post_string");
  fwrite($socket, "");
  $header = "";
  while ($str = trim(fgets($socket, 4096))) {
    $header .= $str;
  }
  
  $data = "";
  while (!feof($socket)) {
    $data .= fgets($socket, 4096);
  }
  
  return $data;
}
?>

방법 3: 컬 버전

<?php
/**
 * Curl版本
 * 使用方法:
 * $post_string = "app=request&version=beta";
 * request_by_curl(&#39;http://www.jb51.net/restServer.php&#39;, $post_string);
 */
function request_by_curl($remote_server, $post_string) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $remote_server);
  curl_setopt($ch, CURLOPT_POSTFIELDS, &#39;mypost=&#39; . $post_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "jb51.net&#39;s CURL Example beta");
  $data = curl_exec($ch);
  curl_close($ch);
  
  return $data;
}
?>
추천 관련 글:
1.POST() 메소드 사용 예제 요약(php)
2.게시 요청을 시뮬레이션하기 위한 PHP의 세 가지 일반적인 용도#🎜🎜 #
관련 동영상 추천: 1.
丁古九典(4)_PHP 동영상 튜토리얼
#🎜 🎜#

위 내용은 PHP에서 게시물 요청을 보내는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.