Facebook API - Facebook API를 통해 Facebook 사용자의 프로필 이미지를 얻는 방법(사용자가 애플리케이션을 "허용"할 필요가 없음)
사용자의 Facebook URL(http://facebook.com/users_unique_url))에서 프로필 이미지를 가져오는 CMS 작업을 하고 있습니다.어떻게 하면 좋을까요?Application을 허용할 필요 없이 사용자의 프로필 이미지 URL을 가져오는 Facebook API 호출이 있습니까?
다음 URL에서 데이터를 가져오기만 하면 됩니다.
http://graph.facebook.com/userid_here/picture
userid_here
아이디HTTPS를 사용합니다.
PHP를 할 수 .file_get_contents
해당 URL을 읽고 검색된 데이터를 처리하는 함수입니다.
자원:
http://developers.facebook.com/docs/api
주의: 입력php.ini
OpenSSL 확장이 활성화되어 있는지 확인해야 합니다.file_get_contents
.
표시하는 방법:
50 x 50 픽셀
<img src="//graph.facebook.com/{{fid}}/picture">
200픽셀 폭
<img src="//graph.facebook.com/{{fid}}/picture?type=large">
저장 방법(PHP 사용)
메모: 사용하지 마십시오.아래의 @Forever 코멘트를 참조해 주세요.
$img = file_get_contents('https://graph.facebook.com/'.$fid.'/picture?type=large');
$file = dirname(__file__).'/avatar/'.$fid.'.jpg';
file_put_contents($file, $img);
여기서 $fid는 페이스북 사용자 ID입니다.
메모: "18+"로 표시된 이미지의 경우 18+ 사용자로부터의 유효한 access_token이 필요합니다.
<img src="//graph.facebook.com/{{fid}}/picture?access_token={{access_token}}">
업데이트 2015:
사용자 이름을 사용하여 Graph API v2.0을 쿼리할 수 없습니다. 사용해야 합니다.userId
★★★★★★ 。
갱신:
2012년 8월 말부터 API가 업데이트되어 다양한 크기의 사용자 프로필 사진을 검색할 수 있습니다.선택적 너비 및 높이 필드를 URL 매개 변수로 추가합니다.
https://graph.facebook.com/USER_ID/picture?width=WIDTH&height=HEIGHT
서 ''는WIDTH
★★★★★★★★★★★★★★★★★」HEIGHT
요청된 치수 값입니다.
최소 됩니다.WIDTH
x HEIGHT
가로 세로 비율을 유지하려고 노력하면서요.를 들어 '예'라고 하면,
https://graph.facebook.com/redbull/picture?width=140&height=110
돌아온다
{
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/c0.19.180.142/s148x148/2624_134501175351_4831452_a.jpg",
"width": 148,
"height": 117,
"is_silhouette": false
}
}
갱신 종료
사용자의 프로필 사진을 가져오려면
https://graph.facebook.com/USER_ID/picture
서 ''는USER_ID
에는 사용자 ID 번호 또는 사용자 이름을 지정할 수 있습니다.
특정 크기의 사용자 프로파일 사진을 가져오려면
https://graph.facebook.com/USER_ID/picture?type=SIZE
서 ''는SIZE
square
small
normal
large
사이즈에 따라 다릅니다.
이 콜에서는 선택한 타입 파라미터에 따라 크기가 지정된 단일 이미지로 URL이 반환됩니다.
예를 들어 다음과 같습니다.
https://graph.facebook.com/USER_ID/picture?type=small
는 이미지의 작은 버전으로 URL을 반환합니다.
API는 프로파일이미지의 최대 크기만 지정하고 실제 크기는 지정하지 않습니다.
정사각형:
최대 너비 및 높이 50픽셀.
작은.
최대 너비는 50픽셀, 최대 높이는 150픽셀입니다.
보통의
최대 너비는 100픽셀, 최대 높이는 300픽셀입니다.
큰.
최대 너비는 200픽셀, 최대 높이는 600픽셀입니다.
기본 USER_를 호출하는 경우ID/사진은 정사각형입니다.
명확화
(위의 예와 같이)를 호출하는 경우
https://graph.facebook.com/redbull/picture?width=140&height=110
Facebook SDK 요청 방식 중 하나를 사용하는 경우 JSON 응답이 반환됩니다.그렇지 않으면 이미지 자체가 반환됩니다.JSON을 항상 취득하려면 다음 명령을 추가합니다.
&redirect=false
다음과 같이 합니다.
https://graph.facebook.com/redbull/picture?width=140&height=110&redirect=false
이진 콘텐츠가 아닌 이미지 URL을 가져오려면:
$url = "http://graph.facebook.com/$fbId/picture?type=$size";
$headers = get_headers($url, 1);
if( isset($headers['Location']) )
echo $headers['Location']; // string
else
echo "ERROR";
사용자 이름이 아닌 FACEBOOK ID를 사용해야 합니다. FACEBOOK ID는 여기에서 얻을 수 있습니다.
서버에 풀사이즈 프로파일이미지를 저장하기 위한 심플한 한 줄 코드.
<?php
copy("https://graph.facebook.com/FACEBOOKID/picture?width=9999&height=9999", "picture.jpg");
?>
이것은 openssl이 php.ini에서 활성화 되어 있는 경우에만 작동합니다.
수락된 답변에 코멘트로 추가했지만, 좀 더 긴 설명을 할 가치가 있다고 느꼈습니다.2015년 4월경부터 몇 차례 인상될 예정입니다.
graph api의 V2 이후로는 사용자 이름을 사용하여 허용되는 답변이 더 이상 작동하지 않습니다.따라서 먼저 userid가 필요하며 사용자 이름을 사용하여 이 정보를 얻을 수 없게 되었습니다.게다가 프라이버시상의 이유로, Facebook은 앱 마다의 유저 ID 를 변경하고 있습니다(https://developers.facebook.com/docs/graph-api/reference/v2.2/user/ 및 https://developers.facebook.com/docs/apps/upgrading/ #syslog_v2_0_user_ids 참조).따라서, 사용할 수 있는 유저 ID 를 취득하려면 , 적절한 인증이 필요합니다.엄밀히 말하면 프로파일 사진은 아직 공개되어 있으며 /userid/picture에서 입수할 수 있습니다(https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture 및 이 예제의 사용자:http://graph.facebook.com/v2.2/4/picture?redirect=0) 문서 참조). 단, 사용자의 프로파일만으로는 사용자의 표준 사용자 ID를 알아낼 수 없을 것 같습니다.앱은 그렇게 됩니다.앱과의 상호작용을 승인할 필요가 있습니다.제 사용 사례(FB 프로파일 링크 옆에 프로파일 사진을 표시했을 뿐)는 과잉입니다.
유저명에 근거해 프로파일 사진을 취득하는 방법, 또는 유저 ID(대체 유저 ID도)를 취득해, 프로파일 사진을 취득하는 방법을 알아낸 경우는, 공유해 주세요.한편, 이전 그래프 URL은 2015년 4월까지 계속 작동합니다.
한 가지 방법은 Gamlet이 답변에 게시한 코드를 사용하는 것입니다.
라고 저장하다로 저장하다
curl.php
그런 다음 파일에서 다음을 수행합니다.
require 'curl.php'; $photo="https://graph.facebook.com/me/picture?access_token=" . $session['access_token']; $sample = new sfFacebookPhoto; $thephotoURL = $sample->getRealUrl($photo); echo $thephotoURL;
이걸 올리려고 했는데 자세한 걸 알아내는데 시간이 좀 걸려서...프로필 사진은 공개되어 있지만, 롤할 때 액세스 토큰을 가져오려면 액세스 토큰이 있어야 합니다.
2015년 4월부터 PHP(HTTP GET) 솔루션 작동(PHP 5 SDK 없음):
function get_facebook_user_avatar($fbId){
$json = file_get_contents('https://graph.facebook.com/v2.5/'.$fbId.'/picture?type=large&redirect=false');
$picture = json_decode($json, true);
return $picture['data']['url'];
}
파라미터의 'type'을 변경할 수 있습니다.
정사각형:
최대 너비 및 높이 50픽셀.
작은.
최대 너비는 50픽셀, 최대 높이는 150픽셀입니다.
보통의
최대 너비는 100픽셀, 최대 높이는 300픽셀입니다.
큰.
최대 너비는 200픽셀, 최대 높이는 600픽셀입니다.
그렇게 하는 방법이 있다;)
"http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers" 덕분에:
<?php
/**
* Facebook user photo downloader
*/
class sfFacebookPhoto {
private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
private $curl = null;
private $response_meta_info = array();
private $header = array(
"Accept-Encoding: gzip,deflate",
"Accept-Charset: utf-8;q=0.7,*;q=0.7",
"Connection: close"
);
public function __construct() {
$this->curl = curl_init();
register_shutdown_function(array($this, 'shutdown'));
}
/**
* Get the real URL for the picture to use after
*/
public function getRealUrl($photoLink) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->curl, CURLOPT_URL, $photoLink);
//This assumes your code is into a class method, and
//uses $this->readHeader as the callback function.
curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
$response = curl_exec($this->curl);
if (!curl_errno($this->curl)) {
$info = curl_getinfo($this->curl);
var_dump($info);
if ($info["http_code"] == 302) {
$headers = $this->getHeaders();
if (isset($headers['fileUrl'])) {
return $headers['fileUrl'];
}
}
}
return false;
}
/**
* Download Facebook user photo
*
*/
public function download($fileName) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->curl, CURLOPT_URL, $fileName);
$response = curl_exec($this->curl);
$return = false;
if (!curl_errno($this->curl)) {
$parts = explode('.', $fileName);
$ext = array_pop($parts);
$return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
file_put_contents($return, $response);
}
return $return;
}
/**
* cURL callback function for reading and processing headers.
* Override this for your needs.
*
* @param object $ch
* @param string $header
* @return integer
*/
private function readHeader($ch, $header) {
//Extracting example data: filename from header field Content-Disposition
$filename = $this->extractCustomHeader('Location: ', '\n', $header);
if ($filename) {
$this->response_meta_info['fileUrl'] = trim($filename);
}
return strlen($header);
}
private function extractCustomHeader($start, $end, $header) {
$pattern = '/'. $start .'(.*?)'. $end .'/';
if (preg_match($pattern, $header, $result)) {
return $result[1];
}
else {
return false;
}
}
public function getHeaders() {
return $this->response_meta_info;
}
/**
* Cleanup resources
*/
public function shutdown() {
if($this->curl) {
curl_close($this->curl);
}
}
}
아이디가 도움이 될 것 같아서요.사용자가 새 계정을 만들 때마다 더 높은 ID가 부여됩니다.검색해보니 아이디로 계정 생성일을 추정하는 방법이 있어 metadatascience.com의 Massoud Seifi가 좋은 데이터를 수집했습니다.
다음 기사를 읽어주세요.
다운로드하는 ID는 다음과 같습니다.
블로그 투고 Graph the Picture of a Facebook Graph Object는 다른 형태의 솔루션을 제공할 수 있습니다.Facebook의 Graph API 및 PHP SDK 라이브러리와 함께 튜토리얼의 코드를 사용합니다.
...그리고 file_get_contents를 사용하지 않도록 합니다(결과를 받아들일 준비가 되지 않은 경우 file_get_contents vs curl 참조).
프로필 사진 사이즈가 궁금하신가요?PHP를 사용한 Facebook 로그인 실행 시.Facebook PHP SDK에서 큰 사이즈의 프로파일 사진을 얻을 수 있는 간단한 방법을 알려드리겠습니다.또한 Facebook 프로파일의 커스텀 사이즈 이미지를 얻을 수 있습니다.
다음 코드 줄을 사용하여 프로필 사진 치수를 설정합니다.
$userProfile = $syslog->apis/me?fields= picture.폭(400)높이(400)';
다음 게시물을 확인하십시오.http://www.codexworld.com/how-to-guides/get-large-size-profile-picture-in-facebook-php-sdk/
@Natural Born Camper,
코드 좋네!이러한 프로세스를 위한 클린 컷 코드 기능이 있습니다!
function get_raw_facebook_avatar_url($uid)
{
$array = get_headers('https://graph.facebook.com/'.$uid.'/picture?type=large', 1);
return (isset($array['Location']) ? $array['Location'] : FALSE);
}
Facebook의 아바타 이미지 URL이 원래대로 돌아옵니다.그러면 자유롭게 사용하세요!
URI = https://graph.facebook.com/{}/picture?width=500'.format(uid)
프로필 URI는 온라인 페이스북 ID 검색 도구를 통해 얻을 수 있습니다.
small, normal, large, square 값을 사용하여 type param을 전달할 수도 있습니다.
공식 문서를 참조하십시오.
언급URL : https://stackoverflow.com/questions/2821061/facebook-api-how-do-i-get-a-facebook-users-profile-image-through-the-facebook
'itsource' 카테고리의 다른 글
마법 방법으로 PhpStorm 필드에 액세스 (0) | 2022.09.29 |
---|---|
HttpServletResponse.getOutputStream()/.getWriter()에서 .close()를 호출해야 합니까? (0) | 2022.09.29 |
JRE 1.7 - Java 버전 - 반환: java/lang/NoClassDefFoundError: java/lang/Object (0) | 2022.09.29 |
도커 컨테이너 마리아답 부피 (0) | 2022.09.29 |
Java에서 Double Brace 초기화란 무엇입니까? (0) | 2022.09.29 |