Ask Your Question
0

Need a PHP Script to wrap an API of a different domain?

asked 2023-05-05 10:59:50 +0000

wagner gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-05 11:01:05 +0000

wagner gravatar image

Here's an updated PHP script that will act as a proxy, accepting query parameters from the client, making an API call with those parameters, and returning the same result:

<?php

function buildUrl($base, $params) {
    $queryString = http_build_query($params);
    return $base . '?' . $queryString;
}

function fetchUrl($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $content = curl_exec($ch);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    return [$content, $contentType];
}

$baseUrl = 'THE_API_END_POINT';
$params = $_GET;
$url = buildUrl($baseUrl, $params);
list($content, $contentType) = fetchUrl($url);

header("Content-Type: $contentType");
echo $content;

Replace THE_API_END_POINT by the API end point you want to wrap.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

1 follower

Stats

Asked: 2023-05-05 10:59:50 +0000

Seen: 18 times

Last updated: May 05 '23