現在の言語: 日本語

戻る

キー判定
ajax

ajaxを使用してhtml側からサーバーにリクエストします。
サーバーではphpで判定した結果をhtml側で受け取ります。
このサンプルではキー判定を使用した画像表示の例となります。

[サンプル]

copy
[test4.html(javascript)]
// まず getkey.php からキーを取得
fetch("http://localhost/img/getkey.php")
.then(res => res.json())
.then(data => {
	console.log("data.key:"+data.key);//getkey.phpから受け取った「password」が返ります
	// 取得したキーをそのまま image.php に渡す
	const url = "http://localhost/img/image.php?file=post.png&key=" + data.key;

	return fetch(url);
})
.then(res => {
	if (!res.ok) throw new Error("アクセス拒否");
	return res.blob();
})
.then(blob => {
	document.getElementById("img").src = URL.createObjectURL(blob);
})
.catch(err => console.error("画像取得失敗:", err));
[.htaccess]
RewriteEngine On
 
# 自分のサイトからの参照のみ許可
# ex.)
# RewriteCond %{HTTP_REFERER} ^https://test\.co\.jp [NC]
RewriteCond %{HTTP_REFERER} ^http://localhost [NC]
RewriteRule ^.*\.(jpe?g|png|gif|bmp)$ - [L]
 
# それ以外(空リファラ含む)は拒否
RewriteRule ^.*\.(jpe?g|png|gif|bmp)$ - [F,L]
 
[getkey.php]
header("Access-Control-Allow-Origin: http://localhost");//ex.)https://test.co.jp
header("Access-Control-Allow-Credentials: true");
 
// 固定キーを返すだけ
header("Content-Type: application/json; charset=utf-8");
echo json_encode(["key" => "password"]);
 
[image.php]
// --- CORS 設定 ---
header("Access-Control-Allow-Origin: http://localhost");//ex.)https://test.co.jp
header("Access-Control-Allow-Credentials: true");
 
// --- アクセス元チェック ---
$origin  = $_SERVER['HTTP_ORIGIN']  ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
 
// --- ここから先は既存のキー判定や画像返却処理 ---
$valid_key = "password"; // 固定キーやトークン判定
$key  = $_GET['key'] ?? '';
$file = basename($_GET['file'] ?? '');
 
if ($key !== $valid_key) {
	header("HTTP/1.1 403 Forbidden");
	exit("Forbidden");
}
 
$path = __DIR__ . "/" . $file;
if (!file_exists($path)) {
	header("HTTP/1.1 404 Not Found");
	exit("Not Found");
}
 
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $path);
finfo_close($finfo);
 
header("Content-Type: $mime");
readfile($path);
exit;
copy
[test4.html(javascript)]
// First, get the key from getkey.php
fetch(“http://localhost/img/getkey.php”)
.then(res => res.json())
.then(data => {
    console.log(“data.key:”+data.key); // Returns the “password” received from getkey.php
	// Pass the retrieved key directly to image.php
    const url = “http://localhost/img/image.php?file=post.png&key=” + data.key;

    return fetch(url);
})
.then(res => {
    if (!res.ok) throw new Error(“Access denied”);
	return res.blob();
})
.then(blob => {
    document.getElementById(“img”).src = URL.createObjectURL(blob);
})
.catch(err => console.error(“Image retrieval failed:”, err));
[.htaccess]
RewriteEngine On
 
# Only allow access from your own site
# ex.)
# RewriteCond %{HTTP_REFERER} ^https://test\.co\.jp [NC]
RewriteCond %{HTTP_REFERER} ^http://localhost [NC]
RewriteRule ^.*\.(jpe?g|png|gif|bmp)$ - [L]
 
# Deny all others (including empty referrers)
RewriteRule ^.*\.(jpe?g|png|gif|bmp)$ - [F,L]
 
[getkey.php]
header(“Access-Control-Allow-Origin: http://localhost”);//ex.)https://test.co.jp
header(“Access-Control-Allow-Credentials: true”);
 
// Only returns the fixed key
header(“Content-Type: application/json; charset=utf-8”);
echo json_encode([“key” => “password”]);
 
[image.php]
// --- CORS Configuration ---
header(“Access-Control-Allow-Origin: http://localhost”);//ex.)https://test.co.jp
header(“Access-Control-Allow-Credentials: true”);
 
// --- Origin check ---
$origin  = $_SERVER[‘HTTP_ORIGIN’]  ?? ‘’;
$referer = $_SERVER[‘HTTP_REFERER’] ?? ‘’;
 
// --- Existing key validation and image return logic starts here ---
$valid_key = “password”; // Fixed key or token check
$key  = $_GET[‘key’] ?? ‘’;
$file = basename($_GET[‘file’] ?? ‘’);
 
if ($key !== $valid_key) {
    header(“HTTP/1.1 403 Forbidden”);
    exit(“Forbidden”);
}
 
$path = __DIR__ . “/” . $file;
if (!file_exists($path)) {
    header(“HTTP/1.1 404 Not Found”);
	exit(“Not Found”);
}
 
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $path);
finfo_close($finfo);
 
header(“Content-Type: $mime”);
readfile($path);
exit;

test4.html
localhost直下に存在するとします。
(1) .htaccess
(2) getkey.php
(3)image.php
(4)post.png
localhost/imgフォルダ直下に存在するとします。

このサンプルではボタンを選択したタイミングとかではなく
htmlを開いたら実行するサンプルになっています。
そのためjavascriptが読み込まれ、実行したタイミングで
http://localhost/img/getkey.php
にアクセスしています。

.then(res => res.json())
response.json()を呼び出すことで、
PHPから送られてきたJSON文字列を
JavaScriptのオブジェクトに自動的にパース(変換)してくれます。

console.log("data.key:"+data.key);//getkey.phpから受け取った「password」が返ります
const url = "http://localhost/img/image.php?file=post.png&key=" + data.key;
getkey.phpから受け取ったキーをURLに組み込みfetchを使用してimage.phpを実行します。
fetchは指定されたURLに対していHTTPリクエストを非同期で送信し
サーバーからデータ(リソース)を取得するAPIです。

document.getElementById("img").src = URL.createObjectURL(blob);
サーバーのURLから送信されたデータを受け取り
srcプロパティに設定して画面に表示しています。
このサンプルではphp側で画像の生データを準備したものを受け取りsrcプロパティに設定して
画面に画像を表示させています。




戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。