Skip to content

Instantly share code, notes, and snippets.

@mgng mgng/ccctest.js
Last active Dec 20, 2015

Embed
What would you like to do?
コピーされたところをPOSTするやつ
// ccctest.js
$(function(){
var CACHE = null;
$("#ccctest").bind( 'copy', function(){
var copyText = $.selection();
// 連続コピペ対策
if ( CACHE === copyText ) {
return;
}
CACHE = copyText;
$.ajax({
type : 'POST',
url : './post.php',
headers : {
// via: http://d.hatena.ne.jp/hasegawayosuke/20130302/p1
'X-From' : location.href
},
data : {
'copyText' : copyText,
'url' : location.href,
'referrer' : document.referrer
}
})
.done(function(data){
// console.log(data);
})
.fail(function(data){
// alert('失敗したっぽい');
})
.always(function(data){
});
});
});
<?php
// POSTデータ取得
$data = array(
'copyText' => isset( $_POST['copyText'] ) ? $_POST['copyText'] : null,
'url' => isset( $_POST['url'] ) ? $_POST['url'] : null,
'referrer' => isset( $_POST['referrer'] ) ? $_POST['referrer'] : null,
'ipaddr' => getRemoteAddress(),
'error' => null,
);
// 簡易CSRFチェック
if ( ! checkHasegawaCsrf() ) {
header('Not Found', true, 404);
$data['error'] = '不正なアクセスっぽい';
echo json_encode( $data );
exit;
}
//---------------------
// ツイッターにPOST処理するとか
// メールぶんなげる処理とか
//---------------------
header('Content-Type: application/json; charset=UTF-8');
echo json_encode( $data );
/**
* getRemoteAddress
* @return string/null
*/
function getRemoteAddress() {
if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
return $_SERVER['HTTP_CLIENT_IP'];
}
if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
return $_SERVER['REMOTE_ADDR'];
}
return null;
}
/**
* hasegawa CSRF check
* via : http://d.hatena.ne.jp/hasegawayosuke/20130302/p1
* @return boolean
*/
function checkHasegawaCsrf() {
$host = isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : null;
$xFrom = isset( $_SERVER['HTTP_X_FROM'] ) ? $_SERVER['HTTP_X_FROM'] : null;
$origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? $_SERVER['HTTP_ORIGIN'] : null;
// $host がない
if ( $host === null ) {
return false;
}
$server_name = $_SERVER['SERVER_NAME'];
if ( preg_match( '/:\d+\z/', $host ) === 1 ) {
$server_name .= ':' . $_SERVER['SERVER_PORT'];
}
// Host と ServerName が一致しない
if ( $host !== $server_name ) {
return false;
}
// X-From がない
if ( $xFrom === null ) {
return false;
}
$p = parse_url( $xFrom );
$url = "{$p['scheme']}://{$p['host']}" . ( isset( $p['port'] ) ? ":{$p['port']}" : '' );
// origin と X-From が一致しない
if ( $origin !== null && $origin !== $url ) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.