我的共享托管不支持postgresqlphp函数,但我需要从postgresql加载一些图像,postgresql远程托管在专用服务器上。
有没有可能在服务器上有一个带有postgresql的PHP脚本,然后共享主机上的另一个PHP脚本会调用postgresql服务器上的脚本,将图像从专用服务器发送到共享主机,但我不希望专用服务器的IP或域被泄露。
这可能吗?如果是,如何?
使用file_get_contents()
:更容易
$img_binary = file_get_contents("https://i.imgur.com/1H9Ht5a.png");
$img_base64 = base64_encode($img_binary);
echo '<img src="data:image/png;base64,' . $img_base64 . '">';
plus:这是一种标准的PHP方法,可能不会在每个PHP环境中激活"cURL"。
小心你的形象类型。将CCD_ 2替换为CCD_。
是的,这是可能的。但是,您需要制作一个JSON API
:为postgresql
提供服务的服务器需要从数据库中获取结果,然后用json_encode()
方法将其编码在json
中,并用echo
返回。
然后,您需要使用CURL
从共享主机发出HTTP请求,下面是一个示例:
function GetContent($url) {
$curl = curl_init();
$ua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl ,CURLOPT_USERAGENT, $ua);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
然后,调用函数:
$sql = json_decode(GetContent('http://urlofyourserver/testJSON.php'));
现在可以在$sql
变量:)
中获得结果
哦,别忘了,在为postgresql服务的服务器上使用$_GET
请求进行密码请求,否则,如果每个人都找到了你的服务器URL,他们就可以访问数据。
例如:http://urlofyourserver/testJSON.php?secret=xxx
您也可以将查询作为get参数传递,但如果您的密码被破解,可能会有风险。
Postgresql服务器示例
$realPass = "blablah";
if(isset($_GET['secret'])) {
$pass = $_GET['secret'];
if($pass === $realPass) {
header('Content-type: application/json');
// do query here and return it as $test var
echo json_encode($test);
}
}
您可以使用php curl
将获取参数get1和get2发送到IP为192.168.2.2 的服务器上的test.php的示例
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://192.168.2.2/test.php?get1=value&get2=value2',
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
));
// Send the request & save response
// The response could be JSON with the results from the database
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
您可以使用PHP在JSON中对结果进行编码和解码,使事情变得更容易。要做到这一点,请使用json_encode()和json_decode()
如果你想了解更多信息,请查看:
- http://codular.com/curl-with-php
- http://php.net/manual/en/curl.examples.php
- http://php.net/manual/en/curl.examples-basic.php
我刚刚想出了另一个更好的主意imho;它在安全性方面也可能更好。
使用一个模拟图像文件的PHP脚本:
// example code for getting binary image data from db
// (PDO and MySQL in this example)
$stmt = $pdo->prepare( "SELECT image_bin FROM image_table WHERE id = :id LIMIT 1" );
$stmt->bindValue(":id", $_GET["id"], PDO::PARAM_INT);
$stmt->execute();
$image_bin = $stmt->fetchColumn();
header('Content-Type: image/png');
echo $image_bin;
在您想要显示图像的页面上,您甚至不需要使用PHP:
<img src="http://myimageserver.com/image.php?id=3425">
在本例中,您只需要使用GET变量id
来定义/决定显示哪个图像。大部分工作都是在远程服务器上完成的,您可以像前面提到的那样使用POSTGRESQL获取所需的图像。