• About
  • Some works
  • Tools I use
web meditation
beautiful inside
Browse: Home / 2011 / December / PHP proxy for cross-domain ajax

PHP proxy for cross-domain ajax

By Oleg Soroka on 27 December 2011

Some time ago I’ve been faced with issue when i should been send REST requests from javascript to another domain. It was connected with REST API of some web service.

I’ve been forced to use PHP proxy. And I want to share my proxy.php

Features

  • sends POST request
  • sends GET request
  • sends DELETE request
  • returns statys from page header

Using

proxy.php?type={GET|DELETE}&url={website_url}
proxy.php?type=POST&url={website_url}&data={data}

<?php
$type = 'GET';
$url = '';
$data = '';

if (isset($_GET['type'])) {
	$type = $_GET['type'];
}

if (isset($_GET['url'])) {
	$url = $_GET['url'];
}

if (isset($_GET['url'])) {
	$data = $_GET['data'];
}

switch ($type) {
    case 'GET':
        GETRequest($url);
        break;
    case 'POST':
        POSTRequest($url, $data);
        break;
    case 'DELETE':
        DELETERequest($url);
        break;
}

function GETRequest($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	// curl_setopt($ch, CURLOPT_HEADER, false); FIXME
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	header("HTTP/1.0 $status");
	curl_close($ch);
	echo $result;	

//	$content = @file_get_contents($url);
//	echo $content;
}

function POSTRequest($url, $data) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, strlen($data));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	header("HTTP/1.0 $status");
	curl_close ($ch);
	echo $result;
}

function DELETEequest($url) {
	$ch = curl_init();
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
	$result = curl_exec($ch);
	curl_close ($ch);
	echo $result;
}
?>

Posted in Hints | Tagged ajax, php, proxy | Leave a response

« Previous Next »

Categories

  • cms
  • css
  • Gatherings
  • Google
  • Hints
  • Wordpress
  • Браузеры
  • Инструменты
  • На манжетах
  • Новости
  • Серфим Internet

Twitter

  • @simalena и уровень любви к WFH +100 =) in reply to simalena 16 hrs ago
  • @SAKrisT выложи парочку фоток in reply to SAKrisT 1 day ago
  • не пропустите Велодень в Харькове! 26 мая!!! http://t.co/XcO6fnvK 1 day ago
  • http://t.co/rxYy3aEN QuickBlox: Авторизация и аутентификация #habr 2 days ago
  • Рассказ и слайд-шоу о буддийском паломничестве «Индия, Непал, Китай», 11 мая http://t.co/mp2HEu6j 1 week ago
  • More updates...

Powered by Twitter Tools

Copyright © 2012 web meditation.

Powered by WordPress. Code is Poetry.