PHP Proxy Script for cross-domain requests

I wrote this php-proxy-script and have been using for different purpose (loading cross-domain data like text, xml, swf, image, etc. or for YouTube REST API  in flash, flex applications).

Often people keep asking about proxy-scripts in forums, now they can download the code and use :)

Download the proxy.php.txt

Usage:-

http://yourserver.com/proxy.php?url=<url_encoded_desitnation_url>[&mimeType=<mimeType>]

Examples:-

To load XML/Text:

http://yourserver.com/proxy.php?url=http%3A//abdulqabiz.com/blog/index.xml

To load a SWF (binary-data):

http://yourserver.com/proxy.php?url=http%3A//abdulqabiz.com/files/some.swf&mimeType=application/x-shockwave-flash

Technorati tags: , ,

  • http://bosky101.blogspot.com Bhasker V Kode

    How about without using curl and relying just on he php fopen. I use this often for tackling any same-origin / cross-domain issues since the fopen can open any remote address ,no strings attached .
    I’ve briefly talked about it over at demo here .
    Keep Clicking,
    Bhasker V Kode,
    returnable.org

  • http://abdulqabiz.com/blog/ Abdul Qabiz

    @Bhaskar: I use both approaches, CURL gives more control over things… I never tried, but can you handle HTTP 30x redirects etc with fopen technique?
    -abdul

  • Jiten

    Thank you, but…. what do I write on my Action Script (SWF File) aaand what do I write exactly on the proxy.php file ? please, just explain with detail this and I will appreciate, tahnks a lot,
    Sw. Jiten

  • http://1stein.org Schimmi

    Do I misunderstand anything or does this proxy script also opens up your server to the world to be, possibly, misused for things like hiding one’s identity, i.e. the IP? I don’t have a good feeling with such a script.

  • http://gskinner.com Lanny

    I had issues with this script (and others) returning 0 for the bytesTotal in flash. Basically, the Content-Length header was absent from the response. By simply adding
    header(“Content-length: “.strlen($response)) before the echo, it resolved the issue. I don’t know if there is a more appropriate fix to account for character encoding, etc, but it seems to work.

  • http://www.abdulqabiz.com/blog Abdul Qabiz

    @Schimmi: Well, if you can add some checks there (like who is referring your script) and allow the access to whitelisted clients (served from your domain)… I think, you can totally make it used applications from same-domain….So it would not be open to world. Yeah above script doesn’t have those things..
    -abdul

  • http://www.abdulqabiz.com/blog Abdul Qabiz

    @Lanny: Thanks for that, I would update it my code also…I need to find a way to return correct content-length for all content-type (text/binary/gzip etc)…
    Thanks
    -abdul

  • Lucas

    God bless you! I was tearing my hair out. Works like a charm – but you knew that…

  • http://www.vibemidia.com John-Henrique

    The PHP proxy script have support of GET and POST solicitations?
    Falopa!

  • http://www.php-learn-it.com Learn PHP

    WOW! thanks for sharing the script. excellent work

  • http://www.templatesoft.com AL

    Here is a ASP Proxy Script.

    <!– Code starts Below this line –>
    <%
    set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
    strURL = Request("url")"
    objHttp.open "GET", strURL, False
    objHttp.Send

    If objHttp.status = 200 Then
        Response.Expires = 90
        Response.ContentType = Request("mimeType")
        Response.BinaryWrite objHttp.responseBody
        set objHttp = Nothing
    End If
    %>
    <!– Code ends above this line –>

    Usage:

    http://yourserver.com/proxy.asp?url=<url_encoded_desitnation_url>&mimeType=<mimeType>

    Example:

    http://yourserver.com/proxy.asp?url=http%3A//www.templatesoft.com/images/16596.jpg&mimeType=image/jpg

     

  • Inder

    Thank you very much for this PHP script…. It really solved my big problem. Once again Thanks

  • http://www.mohitech.com Mohiuddin Khan Inamdar

    Nice script gonna try my hand with it…
    regards..
    mohnkhan
    http://www.mohitech.com

  • http://www.tubeoxy.com Carl

    Will this work with displaying YouTube videos?

  • http://www.abdulqabiz.com/blog Abdul Qabiz
  • Jay

    Thanks for this script.
    It helped me to solve my problem.
    While implementing this, I found out two minor problems and possible solutions
    that I would like to share with you guys:

    1) If current($_POST) is empty (blank), the condition (while) becomes false. The
    subsequent post fields cannot be processed (not included in $postvars).

    while ($element = current($_POST)) {
    $postvars .= key($_POST).’=’.$element.’&';
    next($_POST);
    }

    Solution:
    while ($key = key($_POST)) {
    $postvars .= $key.’=’.urlencode(current ($_POST)).’&';
    next($_POST);
    }

    2) I think urlencode() should be used as shown below:

    $postvars .= $key.’=’.urlencode(current ($_POST)).’&';

    I hope this helps.

  • http://www.profissionaisdeweb.com/ Marcos

    Really tanks for that.

  • http://tekage.com.ar kevin

    sure.. nice code, butt…
    unhappily images are not stored in cache..

  • Eddie

    Hello
    I am using your proxy.php script to grab iGoogle weather in flash. I have php enabled and configured on our IIS 6 server, but nothing loads when going to the page. Do you have any ideas what could be causing this? Thanks

  • CB

    This looks like a simple modification of http://developer.yahoo.com/javascript/samples/proxy/php_proxy_simple.txt but with the original author’s name conveniently removed (and not retained for giving proper credit???)

  • Anthony

    I have changed the source file to point to the proxy.php file in the same directory, and exported the swf. The swf cannot load the data. If i try to look at the proxy.php file directly, i just get errors. Any suggestions?

  • Alex

    Excuse me, but i need a little help. i want to use your proxy for cross-domain request. i tryed it to make a request from a java Requestbuilder with an xml file as content and an POST as method, but my php isnt good and i cant get the content from the request to use ist in your proxy. some advices?

  • Marissa

    I am using this script for flash and google calendar and it works pretty great. the only problem is that it seems to change the sort order of google calendar. the feed I’m trying to get is https://www.google.com/calendar/feeds/doug%40dougmishkin.com/public/full?futureevents=true&orderby=starttime&sortorder=ascending&max-results=5 but it defaults to the orderby default.
    Any ideas?

  • Maria

    You should make this able so that people can get on myspace.com from here.

  • http://www.earspasm.com earspasm

    Totally brilliant, elegant and simple. Thanks so much for your work on this.

  • Avery

    Fantastic. Absolutly fantastic. Thank you so much for this excellent little file.
    Life saver!

  • jaris

    I have tried the script to access a distant flv file. It works, but I have to wait a lot of time to see the video. Have you an idea to have a progressive download of the file.

  • http://abdulqabiz.com/blog/ Abdul Qabiz

    Hi Guys
    Thanks for feedback.
    @jaris Yeah, this script can do better, if tweaked. I can imaging, for progressive video you would need to have logic so it can buffer the output. Unfortunately, I don’t have time right now to add or test that.
    If you figure out the fix, please let me know.
    Thanks
    -abdul

  • jayp

    Thanks!
    I didn’t set mime-type and everything but MSIE worked fine. So if MSIE not working, make sure mime type is specified after url.

    • Eric

      And I had the mime-type specified,
      header(“Content-Type: image/jpeg”);
      but still no images loading in MSIE. Turns out the type has to be pjpeg,
      header(“Content-Type: image/pjpeg”);
      which fortunately also works in the other browsers I checked (FF and Safari)

  • Chris

    Hi I’m trying to use this with Google Calendar and AS3 but its throwing up an IOError. The AS3 causing the problem is:
    var xmlLoader:URLLoader = new URLLoader( new URLRequest(‘proxy.php?url=’+ xmlURL) );
    Any ideas? I have the proxy.php file in the same folder as the swf.
    @Alex: If you’re putting the calendar events into an array, you could try sorting that using myArray.sortOn(‘myProperty’, Array.DESCENDING);

  • TELLO

    Hi Abdul,
    i have problem. I use the script to get XML datas from other domain. I use the url urlencoded like your advice. It works in FireFox perfect, but not in IE. I tested IE 6, 7 and 8, but no result.
    You write it works in IE with mime type after URL. So i need XML, what must i put on the end that it works in IE, because i guess it is my problem…
    THANKS

  • Tibin mathew

    // If it’s a POST, put the POST data in the body
    if ($_POST['https://newport.ingrammicro.com/mustang']) {
    echo(“hai”);
    $postvars = “2.014-01811114-018111MDt8772CG4339pW824D7441″;
    while ($element = current($_POST)) {
    $postvars .= key($_POST).’=’.$element.’&’;
    next($_POST);
    }
    curl_setopt ($session, CURLOPT_POST, true);
    curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
    }

    here in your code its saying if its a post put the post data in the body, is it the html body of my php page or any thing else, plz say about this, where should i give my xml document to post to the url????

  • petkusj

    Hi Abdul,

    I’m trying to get the proxy to work with this simple Flash example:

    var loader:Loader = new Loader();
    var loadercontext:LoaderContext = new LoaderContext();
    loadercontext.checkPolicyFile = true;
    var urlrequest:URLRequest = new URLRequest(“http://www.mydomain.com/scripts/proxy.php”);

    var urlvariables:URLVariables = new URLVariables();
    urlvariables.url = escape(“http://upload.wikimedia.org/wikipedia/en/3/39/The_Tonight_Show_with_Conan_O’Brien-Intertitle.jpg”);
    urlvariables.mimeType = “image/jpeg”;

    urlrequest.data = urlvariables;
    urlrequest.method = URLRequestMethod.POST;
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadHandler);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
    loader.load(urlrequest, loadercontext);
    var shape:Shape = new Shape();
    addChild(shape)

    function errorHandler(e:IOErrorEvent):void {
    ExternalInterface.call(“window.alert”, e.toString());
    }
    function loadHandler(evt:Event):void {
    var bitmapdata:BitmapData = new BitmapData(loader.contentLoaderInfo.width, loader.contentLoaderInfo.height, false);
    bitmapdata.draw(loader);
    shape.graphics.beginBitmapFill(bitmapdata, null, true);
    shape.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
    shape.graphics.endFill();
    }

    with the idea that if I can get this to work, I can get my application to work, but I’m getting an Error #2124, which is telling me that Flash doesn’t understand the file type.

    I’d appreciate any help with this. wikimedia doesn’t use crossdomain.xml files.

    Thanks, Jennifer

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      @Jennifer, I would need to run your code and see what might be going wrong. Did you use any tool like firebug (extention for Firefox) to see if image is getting downloaded at client side?.

    • petkusj

      Hi Abdul,

      Thanks for responding. I’m afraid I get nothing back from the server. You can see the code above in action at http://www.cuculcan.com/testwikimedia.html. Other than Flash returning the error code, that’s it. Firebug error console returns nothing.

      I do know that in the Flash authoring environment I can load that image (without using a proxy) and fill a shape because it doesn’t throw a security error. But, of course, I can’t do it in the browser. So I do know that nothing is wrong with that image.

      Again, any help would be greatly appreciated. If you go to my website — http://www.cuculcan.com/ — you can see how I’m using the background images.

      Thanks,

      Jennifer

    • Alarik

      HI, i had the same problem.
      I tried to load a jpg with the proxy and had the same error 2124.
      The problem, in my case, was that the url I provided to the proxy contained a “space” character (something like: http://www.example.com/Dir One/xx.jpg).
      When the script got the “Dir One” string it did not reencoded so that the requested file was …/Dir One/… instaed of ../Dir%20One/…
      I fixed adding a function in the php script that replaces all the “space” characters with the “%20″ string, and now it works.

      bye

  • Mikkel

    Thanks for sharing, just save me.

  • sxc

    wat a loser

  • http://www.100it.be/ Chris Devriese
  • http://www.100it.be/ Chris Devriese

    I just use this code:

    http://www.proxysite.be/proxy.php?url=actionscriptEscapedUrl

    Works fine for me (for xml-files)

    Regards,
    Chris.

  • Jenny

    This worked like a charm!! You’ve made my life so much easier!!

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      Glad to hear that. BTW! Nice portfolio you have got there. I would touch base with you to see, if we can do some projects together in future.

  • Tamanna Sahney

    hi abdul,
    I am from kanpur too,but right now living in Dubai, so its great to see such good work going on there.I am sorry but I am not able to get ur proxy code here as everything with the word proxy is banned here.if u dont mind cld u mail me the proxy script at my email tamanna.sahney@gmail.com..
    thanxs

  • maria_alex

    hey mate,

    This WPBlog is devoted to Proxy, List Proxy, Proxy Server, Proxies and Free Anonymous Proxy List. It covers info and resources on these topics:

    Proxies, Fresh Proxy, Anonymous Proxy Surfing, Web Proxy Servers and Anonymous Proxy BrowsingAnyone canlook fortons ofinformation, pictures, ebooks andyoutube videosSave this site: http://www.proxyclub.org/blog/ for stuff like Proxy Lists or Online Proxy Server

    I’m very hopeful you will like this website

    Cheers

  • SageT

    Hi. I am working on a project at work (we install ip cameras in our office network). i was able to write a script with tags to view the cameras while putting the ip address of the cameras in the tag.
    if we view it within our office network it works well, however when we go out to the internet, it doesn’t work again, even though the server handling the pages can be reached over the internet, the video doesn’t display..

    Please help out

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      The IP address you put, is it publicly accessible address? When outside of office, are you accessing the page using a domain-name or ip-address?

      Flash Player has security sandbox, which wouldn’t let you communicate with cross-domain, unless a permission is granted via policy files.

  • Daniel

    Abdul, or anyone, try the links below. They translate text into speech via Googles api. Both links are sending the same (Hungarian) word to translate, the first is incorrect, the second is correct but in Flash it works with only Firefox. I believe something in the cURL function is causing a mistranslation of the special characters. In your proxy on top i put the line: header(‘Content-type: text/html; charset=utf-8′); and the mimeType is set to “audio/mpeg”; so i can’t just ‘urldecode’ the resulting text because what is being returned is an audio file.

    http://beta.petzooba.com/proxy.php?url=http://translate.google.com/translate_tts%3Ftl=hu%26q=p%C3%A9lda

    http://translate.google.com/translate_tts?tl=hu&q=p%E9lda

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      I hope, you got it sorted out. I just looked at this comment.

  • Flakr

    Mr. Qabiz, still, I consider your script here the utmost effective, practical processor of non-SSL resources over secure pages. You’ve done a fine job, sir—many thanks: https://www.flakr.com/i.php?mimeType=text/html&u=http%3A%2F%2Fpixabay.com%2Fapi%2F%3Fusername%3Dmc%26key%3D887c30bb5cad45be3abc%26search_term%3Dflower