Php http request cross domain

Php cross domain http post request code example

So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url). Solution 3: Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

Form Cross domain POST request using PHP

Add this at the beginning of your PHP file:

header("access-control-allow-origin: *"); 

More info on cross domain policy here.

I think you need to prevent the default function of the submit button using .preventDefault() because as I look on your code you want to submit your form using ajax

and please use .ajax() so that you can set your ajax request to a cross-domain request

Your input element must set up the name attribute as name=»name» .

You can gather more informations from the jQuery API Documention:
http://api.jquery.com/
http://api.jquery.com/serialize/

Form Cross domain POST request using PHP, I am trying to send data from a form to a php file so I can store it in a database, but its not working The code for the form is not on the same server as the php file, because the form will be Usage exampleheader(«access-control-allow-origin: *»);Feedback

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server’s response to a clients request. CSRF attacks don’t care about the response, they care about a side-effect , or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Читайте также:  Java install path windows

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

And a good documentation from Mozilla: here

PHP cross domain requests, I am a green programmer and I was originally trying to make cross domain requests in JS. I quickly learned that this is not allowed. POST to my PHP the request-payload & request-headers PHP: POST to Other Domain’s URL the request-payload & request-headers Other Domain: Process Request and send …

Handle cross-domain AJAX POST request in WordPress plugin

This method in insecure. You should be using the WP rest API for accepting cross-domain requests. Also, you should be adding auth 1.0 that comes shipped with the WP rest API. Here is a link showing you how to add your own endpoint to the rest api https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

And here is link showing you how to secure your api with authentication with auth 1.0. https://wordpress.org/plugins/rest-api-oauth1/

You need to create a function in PHP to make the API call to your server and add it to the wp_ajax and wp_ajax_nopriv hooks.

add_action( 'wp_ajax_your_ajax_function', 'your_ajax_function' ); add_action( 'wp_ajax_nopriv_your_ajax_function', 'your_ajax_function' ); function your_ajax_function() < $url = 'http://www.google.com'; // url to your rest API if ( isset( $_POST['data'] ) ) < $response = wp_remote_post( $url, array( 'data' =>$_POST['data'] ) ); if ( is_wp_error( $response ) ) < echo $response->get_error_message(); exit; > else < wp_send_json( $response ); >> > 

To make sure you have access to the correct ajax path, localize the path for ajax for use in javascript:

add_action( 'wp_enqueue_scripts', 'localize_ajax' ); function localize_ajax()

Note: change jquery to your javascript file and/or make sure you create your function once jquery has been enqueued on the page.

Next, create your function in javascript that calls your ajax function passing the user value in the data field and attach it to some event listener:

function yourFunction() < jQuery.ajax( < method: 'POST', url: ajaxurl, data: < 'action' : 'your_ajax_function', 'data' : 'test' >, success: function( response ) < // do what you want with your response console.log( response ); >>); > 

This will return back the response from your API call, so use response to populate your results in the DOM.

Html — Cross Domain Form POSTing, This includes devices on your local network, such as Printers and Routers. There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit () method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

Simple ajax POST with cross domain request

Try adding crossDomain: true and xhrFields: < withCredentials: true >to the request:

$( document ).ready(function() < $('.btnEnviar').click(function()< $.ajax(< type: 'POST', url: 'http://xxxxx.xxx/subscribers/subscribeEmail', datatype: 'jsonp', async: true, xhrFields: < withCredentials: true >, crossDomain: true, success:function()< try< alert("ok"); >catch (e) < alert(e); >> >); >); >); 

Php — Send cross domain request with post method, How to send cross domain request from Javascript with Post method to Php file with large request data? I have tried with $.ajax , $.post but have same issue as alerting POST failed. Here is my HTML

Читайте также:  Rfc php что такое

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP Proxy for Cross Domain Requests

License

softius/php-cross-domain-proxy

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Formerly known as «PHP Cross Domain (AJAX) Proxy»

PHP CORS Proxy is a simple php script that allows cross domain requests. It can be used to access resources from third party websites when it’s not possible to enable CORS on target website i.e. when you don’t own that website.

Note: Please check whether this solution is indeed necessary by having a look on how you can enable CORS on your server.

  • Acts as a reverse proxy: request headers and data are propagated from proxy to server. Similarly, response headers and data are propagated from proxy to client.
  • Provides support for all methods GET, POST, PUT, DELETE.
  • Provides also support for HTTPS.
  • Requests can be filtered against a list of trusted domains or URLs.
  • External configuration (Work in progress)
  • Error handling i.e. when server is not available (Work in progress)
  • Debugging mode (Work in progress)

PHP Cors Proxy works with PHP 5.3+ or above.

PHP CORS Proxy is licensed under GPL-3.0. See LICENCE.txt file for further details.

Using composer

composer require softius/cors-proxy 

Manual installation

The proxy is indentionally limited to a single file. All you have to do is to place proxy.php under the public folder of your application.

For security reasons don’t forget to define all the trusted domains / URLs into top section of proxy.php file:

$valid_requests = array( 'http://www.domainA.com/', 'http://www.domainB.com/path-to-services/service-a' );

Note: There is currently ongoing work to allow configuration outside the proxy.php

It is possible to initiate a cross domain request either by providing the X-Proxy-URL header or by passing a special GET parameter. The former method is strongly suggested since it doesn’t modify the request query. Also, the request looks more clear and easier to understand.

Читайте также:  Text file reading in javascript

It is possible to specify the target URL by using the X-Proxy-URL header, which might be easier to set with your JavaScript library. For example, if you wanted to automatically use the proxy for external URL targets, for GET and POST requests:

$.ajaxPrefilter(function(options, originalOptions, jqXHR)  if (options.url.match(/^https?:/))  options.headers['X-Proxy-URL'] = options.url; options.url = '/proxy.php'; > >);

The following example uses curl

curl -v -H "X-Proxy-URL: http://cross-domain.com" http://yourdomain.com/proxy.php 

In order to make a cross domain request, just make a request to http://www.yourdomain.com/proxy.php and specify the target URL by using the csurl (GET) parameter. Obviously, you can add more parameters according to your needs; note that the rest of the parameters will be used in the cross domain request. For instance, if you are using jQuery:

$('#target').load( 'http://www.yourdomain.com/proxy.php',  csurl: 'http://www.cross-domain.com/', param1: value1, param2: value2 > );

The following example uses curl

curl -v "http://yourdomain.com/proxy.php?csurl=http://www.cross-domain.com/¶m1=value1¶m2=value2" 

Источник

Кроссдоменные запросы (CORS) простая реализация

Несколько раз у меня уже возникала мысль о реализации кроссдоменных запросов между своими сервисами, однако толково настроить получалось плохо. Давайте уже наконец-то разберемся в этой теме.

Для начала, рассмотрим пример:

У вас есть сайт «А», на пример, реализованный на Laravel и vue.js, который реализует определенную логику работы с какими-либо данными. Сейчас вы, в рамках одного сервиса (в данном случае, несколько микро сервисов решающих разные задачи для одного большого проекта), создаете сайт «Б», которому необходимо работать с той же базой данных и использовать часть функционала сайта «А».

Как решить этот вопрос? Естественно вы можете повторно реализовать необходимый функционал на сайте «Б» и подключиться к базе сайта «А». Но в этом есть свои существенные минусы, как минимум это:

  1. Вы, в рамках одной системы, дублируете код, который вы написали ранее.
  2. Вы используете прямой доступ к БД из двух разных мест, это существенно усложнит поиск ошибок, если такие возникнут и такой подход считается далеко не «лучшей практикой».

Так же, у вас есть ещё один вариант реализации (да, это первое, что пришло вам в голову) — jsonp. Но особенности этого метода заключаются в некоторой сложности реализации:

  1. Высокие требования к безопасности данного подхода
  2. Требования к изменению кода уже написанного ранее для сайта «А».
  3. Метод позволят только получить данные, если вам, к примеру требуется отправить информацию методом POST, при помощи jsonp вы этого сделать не сможете.
  4. Уязвимость к инъекциям — вы должны полностью доверять серверу, от которого получаете данные, ведь вы будете выполнять весь код, который вам от него приходит.

Но есть вариант лучше, проще, так как не требует внесения изменений на сайте «А» и является более безопасным подходом, это кроссдоменные запросы или CORS — Cross-origin resource sharing (в переводе: совместное использование ресурсов между разными источниками).

Суть метода очень проста: для того, чтобы серверу «А» получить или отправить данные на сервер «Б», достаточно на сервере «Б» установить «разрешение» на получение и ответ на запросы с сервера «А». Делается это следующим образом: в заголовках ответа на сервере «Б» вам необходимо установить следующие записи:

Источник

Оцените статью