목차
Request URL
Simple PHP Proxy response
백엔드 개발 PHP 튜토리얼 简略的php代理 Simple PHP Proxy

简略的php代理 Simple PHP Proxy

Jun 13, 2016 am 11:57 AM
gt json lt the url

简单的php代理 Simple PHP Proxy

实例:http://www.ikeepstudying.com/tools/proxy/

?

index.php

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script type="text/javascript" language="javascript">// I want to use json2.js because it allows me to format stringified JSON with// pretty indents, so let's nuke any existing browser-specific JSON parser.window.JSON = null;</script><script type="text/javascript" src="/js/jquery-1.8.2.min.js"></script><script type="text/javascript" src="http://benalman.com/code/projects/php-simple-proxy/shared/json2.js"></script><script>	(function($){$(document).ready(function(e)	{		// Handle form submit.		$('#params').submit(function(){			var proxy = 'proxy.php', url = proxy + '?' + $('#params').serialize();						// Update some stuff.			$('#request').html( $('<a/>').attr( 'href', url ).text( url ) );			$('#response').html( 'Loading...' );						// Test to see if HTML mode.			if ( /mode=native/.test( url ) ) 			{			  	// Make GET request.			  	$.get( url, function(data)			  	{			  		$('#response')			  		.html( '<pre class='brush:php;toolbar:false;'>' )			  		.find( 'pre' )			  		.text( data );			  	});			} 			else 			{			  	// Make JSON request.				$.getJSON( url, function(data)				{			  		$('#response')			  		.html( '<pre class="brush:js"/>' )			  		.find( 'pre' )					.text( JSON.stringify( data, null, 2 ) );			  	});			}						// Prevent default form submit action.			return false;		});	  	  	// Submit the form on page load if ?url= is passed into the example page.	  	if ( $('#url').val() !== '' ) $('#params').submit();	  	  	// Disable AJAX caching.	  	$.ajaxSetup({ cache: false });	  	  	// Disable dependent checkboxes as necessary.	  	$('input:radio').click(function(){			var that = $(this),	  		c1 = 'dependent-' + that.attr('name'),	  		c2 = c1 + '-' + that.val();				that.closest('form')		  	.find( '.' + c1 + ' input' )			.attr( 'disabled', 'disabled' )		    .end()		  	.find( '.' + c2 + ' input' )			.removeAttr( 'disabled' );	 	});	  	  	// Clicking sample remote urls should populate the "Remote URL" box.	  	$('#sample a').click(function(){			$('#url').val( $(this).attr( 'href' ) );	    	return false;	  	});			});})($staff)</script> <form action="" method="get" id="params">  <div>    <label>      <b>Remote URL</b>      <input type="text" value="" name="url" class="text" id="url" style="width:90%" />    </label>  </div>  <p id="sample">    ..or try these sample Remote URLs:    <a href="http://github.com/">GitHub</a>,    <a href="http://github.com/cowboy/php-simple-proxy/raw/master/examples/simple/json_sample.js">a sample JSON (not JSONP) request</a>,    <a href="http://github.com/omg404errorpage">a 404 error page</a>  </p>  <div>    <label>      <input type="radio" disabled="disabled" value="native" name="mode">      Native <i>(disabled by default)</i>    </label>  </div>  <div>    <label>      <input type="radio" disabled="disabled" checked="checked" value="json" name="mode">      JSON    </label>  </div>  <div class="dependent-mode dependent-mode-json indent">    <div>      <label>        <input type="checkbox" checked="checked" value="1" name="full_headers">        Full Headers      </label>    </div>    <div>      <label>        <input type="checkbox" checked="checked" value="1" name="full_status">        Full Status      </label>    </div>  </div>  <input type="submit" value="Submit" name="submit" class="submit"></form><h3 id="Request-URL">Request URL</h3><p id="request">N/A, click Submit!</p><h3 id="Simple-PHP-Proxy-response">Simple PHP Proxy response</h3><div id="response">N/A, click Submit!</div>
로그인 후 복사

?

proxy.php

<?PHP// Script: Simple PHP Proxy: Get external HTML, JSON and more!//// *Version: 1.6, Last updated: 1/24/2009*// // Project Home - http://benalman.com/projects/php-simple-proxy/// GitHub       - http://github.com/cowboy/php-simple-proxy/// Source       - http://github.com/cowboy/php-simple-proxy/raw/master/ba-simple-proxy.php// // About: License// // Copyright (c) 2010 "Cowboy" Ben Alman,// Dual licensed under the MIT and GPL licenses.// http://benalman.com/about/license/// // About: Examples// // This working example, complete with fully commented code, illustrates one way// in which this PHP script can be used.// // Simple - http://benalman.com/code/projects/php-simple-proxy/examples/simple/// // About: Release History// // 1.6 - (1/24/2009) Now defaults to JSON mode, which can now be changed to//       native mode by specifying ?mode=native. Native and JSONP modes are//       disabled by default because of possible XSS vulnerability issues, but//       are configurable in the PHP script along with a url validation regex.// 1.5 - (12/27/2009) Initial release// // Topic: GET Parameters// // Certain GET (query string) parameters may be passed into ba-simple-proxy.php// to control its behavior, this is a list of these parameters. // //   url - The remote URL resource to fetch. Any GET parameters to be passed//     through to the remote URL resource must be urlencoded in this parameter.//   mode - If mode=native, the response will be sent using the same content//     type and headers that the remote URL resource returned. If omitted, the//     response will be JSON (or JSONP). <Native requests> and <JSONP requests>//     are disabled by default, see <Configuration Options> for more information.//   callback - If specified, the response JSON will be wrapped in this named//     function call. This parameter and <JSONP requests> are disabled by//     default, see <Configuration Options> for more information.//   user_agent - This value will be sent to the remote URL request as the//     `User-Agent:` HTTP request header. If omitted, the browser user agent//     will be passed through.//   send_cookies - If send_cookies=1, all cookies will be forwarded through to//     the remote URL request.//   send_session - If send_session=1 and send_cookies=1, the SID cookie will be//     forwarded through to the remote URL request.//   full_headers - If a JSON request and full_headers=1, the JSON response will//     contain detailed header information.//   full_status - If a JSON request and full_status=1, the JSON response will//     contain detailed cURL status information, otherwise it will just contain//     the `http_code` property.// // Topic: POST Parameters// // All POST parameters are automatically passed through to the remote URL// request.// // Topic: JSON requests// // This request will return the contents of the specified url in JSON format.// // Request:// // > ba-simple-proxy.php?url=http://example.com/// // Response:// // > { "contents": "<html>...</html>", "headers": {...}, "status": {...} }// // JSON object properties:// //   contents - (String) The contents of the remote URL resource.//   headers - (Object) A hash of HTTP headers returned by the remote URL//     resource.//   status - (Object) A hash of status codes returned by cURL.// // Topic: JSONP requests// // This request will return the contents of the specified url in JSONP format// (but only if $enable_jsonp is enabled in the PHP script).// // Request:// // > ba-simple-proxy.php?url=http://example.com/&callback=foo// // Response:// // > foo({ "contents": "<html>...</html>", "headers": {...}, "status": {...} })// // JSON object properties:// //   contents - (String) The contents of the remote URL resource.//   headers - (Object) A hash of HTTP headers returned by the remote URL//     resource.//   status - (Object) A hash of status codes returned by cURL.// // Topic: Native requests// // This request will return the contents of the specified url in the format it// was received in, including the same content-type and other headers (but only// if $enable_native is enabled in the PHP script).// // Request:// // > ba-simple-proxy.php?url=http://example.com/&mode=native// // Response:// // > <html>...</html>// // Topic: Notes// // * Assumes magic_quotes_gpc = Off in php.ini// // Topic: Configuration Options// // These variables can be manually edited in the PHP file if necessary.// //   $enable_jsonp - Only enable <JSONP requests> if you really need to. If you//     install this script on the same server as the page you're calling it//     from, plain JSON will work. Defaults to false.//   $enable_native - You can enable <Native requests>, but you should only do//     this if you also whitelist specific URLs using $valid_url_regex, to avoid//     possible XSS vulnerabilities. Defaults to false.//   $valid_url_regex - This regex is matched against the url parameter to//     ensure that it is valid. This setting only needs to be used if either//     $enable_jsonp or $enable_native are enabled. Defaults to '/.*/' which//     validates all URLs.// // ############################################################################// Change these configuration options if needed, see above descriptions for info.$enable_jsonp    = false;$enable_native   = false;$valid_url_regex = '/.*/';// ############################################################################$url = $_GET['url'];if ( !$url ) {    // Passed url not specified.  $contents = 'ERROR: url not specified';  $status = array( 'http_code' => 'ERROR' );  } else if ( !preg_match( $valid_url_regex, $url ) ) {    // Passed url doesn't match $valid_url_regex.  $contents = 'ERROR: invalid url';  $status = array( 'http_code' => 'ERROR' );  } else {  $ch = curl_init( $url );    if ( strtolower($_SERVER['REQUEST_METHOD']) == 'post' ) {    curl_setopt( $ch, CURLOPT_POST, true );    curl_setopt( $ch, CURLOPT_POSTFIELDS, $_POST );  }    if ( $_GET['send_cookies'] ) {    $cookie = array();    foreach ( $_COOKIE as $key => $value ) {      $cookie[] = $key . '=' . $value;    }    if ( $_GET['send_session'] ) {      $cookie[] = SID;    }    $cookie = implode( '; ', $cookie );        curl_setopt( $ch, CURLOPT_COOKIE, $cookie );  }    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );  curl_setopt( $ch, CURLOPT_HEADER, true );  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );    curl_setopt( $ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT'] );    list( $header, $contents ) = preg_split( '/([\r\n][\r\n])\\1/', curl_exec( $ch ), 2 );    $status = curl_getinfo( $ch );    curl_close( $ch );}// Split header text into an array.$header_text = preg_split( '/[\r\n]+/', $header );if ( $_GET['mode'] == 'native' ) {  if ( !$enable_native ) {    $contents = 'ERROR: invalid mode';    $status = array( 'http_code' => 'ERROR' );  }    // Propagate headers to response.  foreach ( $header_text as $header ) {    if ( preg_match( '/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header ) ) {      header( $header );    }  }    print $contents;  } else {    // $data will be serialized into JSON data.  $data = array();    // Propagate all HTTP headers into the JSON data object.  if ( $_GET['full_headers'] ) {    $data['headers'] = array();        foreach ( $header_text as $header ) {      preg_match( '/^(.+?):\s+(.*)$/', $header, $matches );      if ( $matches ) {        $data['headers'][ $matches[1] ] = $matches[2];      }    }  }    // Propagate all cURL request / response info to the JSON data object.  if ( $_GET['full_status'] ) {    $data['status'] = $status;  } else {    $data['status'] = array();    $data['status']['http_code'] = $status['http_code'];  }    // Set the JSON data object contents, decoding it from JSON if possible.  $decoded_json = json_decode( $contents );  $data['contents'] = $decoded_json ? $decoded_json : $contents;    // Generate appropriate content-type header.  $is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';  header( 'Content-type: application/' . ( $is_xhr ? 'json' : 'x-javascript' ) );    // Get JSONP callback.  $jsonp_callback = $enable_jsonp && isset($_GET['callback']) ? $_GET['callback'] : null;    // Generate JSON/JSONP string  $json = json_encode( $data );    print $jsonp_callback ? "$jsonp_callback($json)" : $json;  }
로그인 후 복사

?

实例:http://www.ikeepstudying.com/tools/proxy/

原文:http://benalman.com/projects/php-simple-proxy/

?

?

?

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

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? 화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? Dec 29, 2023 pm 02:27 PM

많은 사용자들이 스마트 시계를 선택할 때 Huawei 브랜드를 선택하게 됩니다. 그 중 Huawei GT3pro와 GT4가 가장 인기 있는 선택입니다. 두 제품의 차이점을 궁금해하는 사용자가 많습니다. Huawei GT3pro와 GT4의 차이점은 무엇입니까? 1. 외관 GT4: 46mm와 41mm, 재질은 유리 거울 + 스테인레스 스틸 본체 + 고해상도 섬유 후면 쉘입니다. GT3pro: 46.6mm 및 42.9mm, 재질은 사파이어 유리 + 티타늄 본체/세라믹 본체 + 세라믹 백 쉘입니다. 2. 건강한 GT4: 최신 Huawei Truseen5.5+ 알고리즘을 사용하면 결과가 더 정확해집니다. GT3pro: ECG 심전도, 혈관 및 안전성 추가

e의 NameResolutionError(self.host, self, e) 이유와 해결 방법 e의 NameResolutionError(self.host, self, e) 이유와 해결 방법 Mar 01, 2024 pm 01:20 PM

오류의 원인은 urllib3 라이브러리의 예외 유형인 NameResolutionError(self.host,self,e)frome입니다. 이 오류의 원인은 DNS 확인에 실패했기 때문입니다. 해결을 찾을 수 없습니다. 이는 입력한 URL 주소가 정확하지 않거나 DNS 서버를 일시적으로 사용할 수 없기 때문에 발생할 수 있습니다. 이 오류를 해결하는 방법 이 오류를 해결하는 방법은 여러 가지가 있습니다. 입력한 URL 주소가 올바른지 확인하고 액세스할 수 있는지 확인하십시오. DNS 서버를 사용할 수 있는지 확인하십시오. 명령줄에서 "ping" 명령을 사용해 볼 수 있습니다. DNS 서버를 사용할 수 있는지 테스트하려면 프록시 뒤에 있는 경우 호스트 이름 대신 IP 주소를 사용하여 웹사이트에 액세스해 보세요.

2개월 만에 휴머노이드 로봇 '워커S' 옷 개기 가능 2개월 만에 휴머노이드 로봇 '워커S' 옷 개기 가능 Apr 03, 2024 am 08:01 AM

기계력 보고서 편집자: 우신(Wu Xin) 국내판 휴머노이드 로봇+대형 모델팀이 옷 접기 등 복잡하고 유연한 재료의 작업 작업을 처음으로 완료했습니다. OpenAI 멀티모달 대형 모델을 접목한 Figure01이 공개되면서 국내 동종업체들의 관련 진전이 주목받고 있다. 바로 어제, 중국의 "1위 휴머노이드 로봇 주식"인 UBTECH는 Baidu Wenxin의 대형 모델과 긴밀하게 통합되어 몇 가지 흥미로운 새로운 기능을 보여주는 휴머노이드 로봇 WalkerS의 첫 번째 데모를 출시했습니다. 이제 Baidu Wenxin의 대형 모델 역량을 활용한 WalkerS의 모습은 이렇습니다. Figure01과 마찬가지로 WalkerS는 움직이지 않고 책상 뒤에 서서 일련의 작업을 완료합니다. 인간의 명령을 따르고 옷을 접을 수 있습니다.

golang WebSocket과 JSON의 결합: 데이터 전송 및 파싱 구현 golang WebSocket과 JSON의 결합: 데이터 전송 및 파싱 구현 Dec 17, 2023 pm 03:06 PM

golangWebSocket과 JSON의 결합: 데이터 전송과 파싱의 실현 현대 웹 개발에서 실시간 데이터 전송은 점점 더 중요해지고 있습니다. WebSocket은 양방향 통신을 달성하는 데 사용되는 프로토콜입니다. 기존 HTTP 요청-응답 모델과 달리 WebSocket을 사용하면 서버가 클라이언트에 데이터를 적극적으로 푸시할 수 있습니다. JSON(JavaScriptObjectNotation)은 간결하고 읽기 쉬운 데이터 교환을 위한 경량 형식입니다.

MySQL5.7과 MySQL8.0의 차이점은 무엇입니까? MySQL5.7과 MySQL8.0의 차이점은 무엇입니까? Feb 19, 2024 am 11:21 AM

MySQL5.7과 MySQL8.0은 서로 다른 두 가지 MySQL 데이터베이스 버전입니다. 두 버전 사이에는 몇 가지 주요 차이점이 있습니다. 성능 개선: MySQL8.0은 MySQL5.7에 비해 성능이 일부 향상되었습니다. 여기에는 더 나은 쿼리 최적화 프로그램, 더 효율적인 쿼리 실행 계획 생성, 더 나은 인덱싱 알고리즘 및 병렬 쿼리 등이 포함됩니다. 이러한 개선 사항은 쿼리 성능과 전반적인 시스템 성능을 향상시킬 수 있습니다. JSON 지원: MySQL 8.0에는 JSON 데이터의 저장, 쿼리 및 인덱싱을 포함하여 JSON 데이터 유형에 대한 기본 지원이 도입되었습니다. 이를 통해 MySQL에서 JSON 데이터를 보다 편리하고 효율적으로 처리하고 조작할 수 있습니다. 트랜잭션 기능: MySQL8.0은 원자와 같은 몇 가지 새로운 트랜잭션 기능을 도입합니다.

PHP 배열을 JSON으로 변환하기 위한 성능 최적화 팁 PHP 배열을 JSON으로 변환하기 위한 성능 최적화 팁 May 04, 2024 pm 06:15 PM

PHP 배열을 JSON으로 변환하기 위한 성능 최적화 방법은 다음과 같습니다. JSON 확장 및 json_encode() 함수를 사용하여 문자 이스케이프를 방지하고 버퍼를 사용하여 JSON 인코딩 결과 캐싱을 고려합니다. JSON 인코딩 라이브러리.

Pandas 사용 튜토리얼: JSON 파일 읽기를 위한 빠른 시작 Pandas 사용 튜토리얼: JSON 파일 읽기를 위한 빠른 시작 Jan 13, 2024 am 10:15 AM

빠른 시작: JSON 파일을 읽는 Pandas 방법, 특정 코드 예제가 필요합니다. 소개: 데이터 분석 및 데이터 과학 분야에서 Pandas는 중요한 Python 라이브러리 중 하나입니다. 풍부한 기능과 유연한 데이터 구조를 제공하며, 다양한 데이터를 쉽게 처리하고 분석할 수 있습니다. 실제 애플리케이션에서는 JSON 파일을 읽어야 하는 상황에 자주 직면합니다. 이 기사에서는 Pandas를 사용하여 JSON 파일을 읽고 특정 코드 예제를 첨부하는 방법을 소개합니다. 1. 팬더 설치

Jackson 라이브러리의 주석은 JSON 직렬화 및 역직렬화를 어떻게 제어합니까? Jackson 라이브러리의 주석은 JSON 직렬화 및 역직렬화를 어떻게 제어합니까? May 06, 2024 pm 10:09 PM

Jackson 라이브러리의 주석은 JSON 직렬화 및 역직렬화를 제어합니다. 직렬화: @JsonIgnore: 속성 무시 @JsonProperty: 이름 지정 @JsonGetter: get 메서드 사용 @JsonSetter: set 메서드 사용 역직렬화: @JsonIgnoreProperties: @JsonProperty 속성 무시: 이름 지정 @JsonCreator: 생성자 사용 @JsonDeserialize: 사용자 정의 논리

See all articles