Indonesian (Bahasa Indonesia) translation by Dika Budiaji (you can also view the original English article)
OAuth bisa menjadi konsep yang sulit untuk kepala Anda di sekitar pada awalnya, tetapi dengan Twitter API sekarang membutuhkan itu, itu adalah sesuatu yang Anda butuhkan untuk memahami sebelum membuat aplikasi Twitter. Tutorial ini akan memperkenalkan Anda ke OAuth, dan memandu Anda melalui proses menciptakan aplikasi dasar.
Pengenalan
Dalam tutorial ini, kita akan membangun sebuah aplikasi sederhana yang memungkinkan pengguna untuk menerapkan efek yang berbeda untuk twitter avatar mereka. Untuk bekerja dengan Twitter API, kita harus menggunakan OAuth untuk otorisasi aplikasi kami untuk membuat request atas nama pengguna.
Flow aplikasi kami akan menjadi sesuatu seperti ini:
- Pengguna diminta untuk terhubung dengan Twitter.
- Pengguna disajikan daftar Tinjauan avatar untuk memilih.
- Berdasarkan pilihan, pengguna disajikan layar konfirmasi menampilkan asli dan baru avatar untuk perbandingan. Pengguna juga ditawarkan pilihan untuk mengirim tweet.
- Setelah pengguna memilih, app membuat dan upload avatar diubah ke Twiter dan halaman yang ditampilkan.
Setup
Untuk memulai, kita harus mengatur direktori source kami. Kami membutuhkan lib
direktori untuk file PHP perpustakaan (class) kami, direktori tmp
untuk menjaga file-file sementara (ini harus bisa writable oleh server), sebuah direktori css
untuk stylesheet dan img
direktori untuk gambar.
Berikut adalah directory tree Anda akan terlihat seperti:
- Tutorial
- css
- img
- lib
- tmp (writable)
Mendaftar aplikasi Anda
Untuk menggunakan OAuth, Anda akan memerlukan apa yang disebut consumer key dan secret untuk mengidentifikasi aplikasi Anda. Untuk mendapatkan ini, Anda harus mendaftar aplikasi dengan Twitter dengan mengikuti langkah-langkah berikut.
Pergi ke halaman pendaftaran, log in jika diperlukan. Anda akan disambut oleh form yang digambarkan di bawah ini:



Mengisi form dengan rincian yang berkaitan dengan aplikasi Anda. Dalam kasus kami, jenis aplikasi Browser dan kita perlu untuk menetapkan default Callback URL. URL ini bisa apa saja selama ini adalah format berlaku. Kami akan mengganti callback dalam kode kita, sehingga tidak kritis bahwa itu adalah URL yang nyata. Jenis Default akses harus Read & Write untuk kenyamanan.
Setelah Anda mendaftar dan menyetujui syarat-syarat, Anda akan disajikan dengan informasi aplikasi baru Anda. Rincian penting yang kita butuhkan adalah Consumer Key dan Consumer Secret, yang seharusnya terlihat seperti ini:



Download tmhOAuth Perpustakaan
Kami akan membuat penggunaan perpustakaan untuk menangani semua rincian di balik membuat request OAuth. Dalam tutorial ini, kita akan menggunakan @themattharris' tmhOAuth Perpustakaan, yang mendukung meng-upload file.
- Download tmhOAuth dari GitHub
- Ekstrak tmhOAuth.php ke direktori lib yang kita buat sebelumnya
Otentikasi
Otentikasi dengan OAuth pada dasarnya adalah proses tiga langkah. Untuk yang lebih dalam kedalaman penjelasan, Lihat Halaman ini pada otentikasi di Twitter, tapi di sini adalah ringkasan:
- App memperoleh token request: langkah pertama adalah untuk aplikasi kami untuk mengidentifikasi itu sendiri ke Twitter (menggunakan consumer key nya) dan mendapatkan token request. Kita harus menyimpan token permintaan ini untuk nanti.
- Pengguna mengotorisasi app on Twitter: pengguna sekarang harus dikirim ke Twitter untuk memberi kami app akses ke account mereka. Setelah itu, pengguna akan dikirim kembali ke URL callback yang ditetapkan oleh app.
- App pertukaran request token untuk token akses: sekarang bahwa aplikasi kami telah disetujui, itu dapat bertukar token request dari langkah 1 token akses. Setelah kita memiliki token access, aplikasi kami gratis untuk berinteraksi dengan Twitter API pada nama pengguna.
Jadi mari kita mulai dengan beberapa kode. Kami akan menangani semua tugas otentikasi kelas yang disebut TwitterApp
. Mulai dengan kode berikut dalam file baru bernama lib/TwitterApp.php:
<?php class TwitterApp { /** * This variable holds the tmhOAuth object used throughout the class * * @var tmhOAuth An object of the tmhOAuth class */ public $tmhOAuth; /** * User's Twitter account data * * @var array Information on the current authenticated user */ public $userdata; /** * Authentication state * * Values: * - 0: not authed * - 1: Request token obtained * - 2: Access token obtained (authed) * * @var int The current state of authentication */ protected $state; /** * Initialize a new TwitterApp object * * @param tmhOAuth $tmhOAuth A tmhOAuth object with consumer key and secret */ public function __construct(tmhOAuth $tmhOAuth) { // save the tmhOAuth object $this->tmhOAuth = $tmhOAuth; } }
Di sini kami telah membuat tiga properti dan constructor yang sederhana. Properti $tmhOAuth
akan menjadi sebuah objek tmhOAuth, yang akan digunakan di seluruh class. Properti $userdata
akan mengadakan suatu objek yang berisi info tentang pengguna seperti nama pengguna Twitter dan status mereka. Properti $state
terus melacak yang keadaan saat ini otentikasi.
Konstruktor hanya menerima sebuah objek tmhOAuth ke dan assign ke properti $tmhOAuth.
Langkah 1: Mendapatkan request Token
Berikut adalah metode untuk mendapatkan request token:
/** * Obtain a request token from Twitter * * @return bool False if request failed */ private function getRequestToken() { // send request for a request token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/request_token", ""), array( // pass a variable to set the callback 'oauth_callback' => $this->tmhOAuth->php_self() )); if($this->tmhOAuth->response["code"] == 200) { // get and store the request token $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); $_SESSION["authtoken"] = $response["oauth_token"]; $_SESSION["authsecret"] = $response["oauth_token_secret"]; // state is now 1 $_SESSION["authstate"] = 1; // redirect the user to Twitter to authorize $url = $this->tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $response["oauth_token"]; header("Location: ' . $url); exit; } return false; }
Untuk memahami bagian pertama, Anda perlu tahu tentang metode tmhOAuth::request()
. Metode ini memungkinkan kita untuk membuat request HTTP diaktifkan OAuth, dan memiliki penggunaan berikut:
tmhOAuth::request ($method $url [$params [, $useauth [, $multipart]]])
-
string $method
- request method untuk digunakan (GET, POST, dll.) -
string $url
- URL untuk mengakses -
array $params
(opsional) - array asosiatif parameter untuk menyertakan dalam request -
bool $useauth
(opsional, default true) - adalah otentikasi diperlukan? -
bool $multipart
(opsional, standar false) - Set ke true untuk upload file
Untuk $url
parameter, kami membuat menggunakan metode tmhOAuth::url()
untuk kerajinan URL berdasarkan metode API yang dipanggil:
tmhOAuth::url ($request [, $format])
-
string $request
- metode api (tanpa ekstensi) -
string $format
(opsional, default ' json ")-respon yang dikehendaki format (JSON, XML, dll.)
Sekarang bahwa Anda sudah familiar dengan metode tersebut, kita harus membuat request POST metode API oauth/request_token. Ini akan kembali OAuth data dalam format khusus, jadi kita perlu untuk mengatur format menjadi kosong ketika kita menggunakan metode tmhOAuth::url().
Kita juga perlu untuk memasukan variabel yang disebut oauth_callback
, yang mana pengguna akan mengembalikan setelah otorisasi di Twitter. Kami akan menggunakan metode tmhOAuth::php_self()
untuk merujuk ke Halaman ini. Berikut adalah kode lagi:
// send request for a request token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/request_token", ""), array( // pass a variable to set the callback 'oauth_callback' => $this->tmhOAuth->php_self() ));
Sekali kita melakukan request, respon disimpan sebagai array dalam properti tmhOAuth::response
, dengan potongan key data berikut :
-
code
- kode Respon HTTP -
response
- data aktual yang dikembalikan -
headers
- respon header
Jadi bagian selanjutnya dari kode kami memeriksa kode respon (200 berarti sukses), dan kemudian menempatkan oauth_token
dan oauth_token_secret
yang kami terima ke dalam variabel sesi karena kita akan membutuhkannya nanti. Ini diekstrak dari data respon yang menggunakan tmhOAuth::extract_params()
metode, yang mengembalikan array data yang terkandung dalam respon. Kami juga mengatur variabel sesi authstate
sinyal bahwa kita berada pada tahap berikutnya otentikasi. Berikut adalah kode:
if($this->tmhOAuth->response["code"] == 200) { // get and store the request token $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); $_SESSION["authtoken"] = $response["oauth_token"]; $_SESSION["authsecret"] = $response["oauth_token_secret"]; // state is now 1 $_SESSION["authstate"] = 1; }
Setelah selesai, kita sekarang harus mengarahkan pengguna ke URL oauth/authorize, termasuk oauth_token
dalam GET parameter. Berikut adalah kode lagi:
// redirect the user to Twitter to authorize $url = $this->tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $response["oauth_token"]; header("Location: ' . $url); exit;
Langkah 2: Mendapatkan akses Token
Berikut adalah metode untuk bertukar token request kami untuk token akses:
/** * Obtain an access token from Twitter * * @return bool False if request failed */ private function getAccessToken() { // set the request token and secret we have stored $this->tmhOAuth->config["user_token"] = $_SESSION["authtoken"]; $this->tmhOAuth->config["user_secret"] = $_SESSION["authsecret"]; // send request for an access token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/access_token", ""), array( // pass the oauth_verifier received from Twitter 'oauth_verifier' => $_GET["oauth_verifier"] )); if($this->tmhOAuth->response["code"] == 200) { // get the access token and store it in a cookie $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); setcookie("access_token", $response["oauth_token"], time()+3600*24*30); setcookie("access_token_secret", $response["oauth_token_secret"], time()+3600*24*30); // state is now 2 $_SESSION["authstate"] = 2; // redirect user to clear leftover GET variables header("Location: ' . $this->tmhOAuth->php_self()); exit; } return false; }
Hal pertama yang kita lakukan adalah mengatur user_token
dan user_secret
dalam array tmhOAuth::config
untuk token request kami memperoleh sebelumnya.
// set the request token and secret we have stored $this->tmhOAuth->config["user_token"] = $_SESSION["authtoken"]; $this->tmhOAuth->config["user_secret"] = $_SESSION["authsecret"];
Bagian selanjutnya adalah di mana kita membuat request POST untuk oauth/access_token. Kami memasukan oauth_verifier
yang kami terima dalam variabel mendapatkan sebagai parameter dalam permintaan ini.
// send request for an access token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/access_token", ""), array( // pass the oauth_verifier received from Twitter 'oauth_verifier' => $_GET["oauth_verifier"] ));
Twitter akan merespon dengan token akses dan secret, yang kita akan perlu untuk disimpan untuk setiap request nanti. Jadi berikutnya sepotong kode mengambil ini dan menyimpan masing-masing dalam cookie, kemudian menetapkan state ke 2.
if($this->tmhOAuth->response["code"] == 200) { // get the access token and store it in a cookie $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); setcookie("access_token", $response["oauth_token"], time()+3600*24*30); setcookie("access_token_secret", $response["oauth_token_secret"], time()+3600*24*30); // state is now 2 $_SESSION["authstate"] = 2; // redirect user to clear leftover GET variables header("Location: ' . $this->tmhOAuth->php_self()); exit; }
Redirect pada akhir untuk menghapus parameter URL yang ditinggalkan oleh Twitter yang ada, dan memungkinkan cookie yang diterapkan.
Langkah 3: Memverifikasi Token akses
Dengan kami token akses yang diperoleh, kita harus memeriksa untuk memastikan hal ini berlaku. Berikut adalah metode untuk melakukannya:
/** * Verify the validity of our access token * * @return bool Access token verified */ private function verifyAccessToken() { $this->tmhOAuth->config["user_token"] = $_COOKIE["access_token"]; $this->tmhOAuth->config["user_secret"] = $_COOKIE["access_token_secret"]; // send verification request to test access key $this->tmhOAuth->request("GET", $this->tmhOAuth->url("1/account/verify_credentials")); // store the user data returned from the API $this->userdata = json_decode($this->tmhOAuth->response["response"]); // HTTP 200 means we were successful return ($this->tmhOAuth->response["code"] == 200); }
Kode ini harus cukup akrab dengan sekarang. Semua yang kita lakukan di sini adalah mengatur user_token
dan user_secret
dan membuat sebuah GET request untuk 1/account/verify_credentials. Jika Twitter merespon dengan kode 200, maka token akses sah.
Detail lain untuk dicatat adalah bahwa ini adalah dimana kita mengisi properti $userdata
dengan data yang dikembalikan oleh request Twitter ini. Data ini dalam JSON format, jadi kami menggunakan json_decode()
untuk mengkonversi ke obyek PHP. Berikut adalah baris lagi:
// store the user data returned from the API $this->userdata = json_decode($this->tmhOAuth->response["response"]);
Langkah 4: Mengikat semuanya bersama-sama
Dengan kami OAuth komponen di yang sudah ada, saatnya untuk mengikat semuanya bersama-sama. Kita perlu metode menghadapi publik untuk memungkinkan kode klien kami untuk memulai proses otentikasi, dan di sini adalah:
/** * Authenticate user with Twitter * * @return bool Authentication successful */ public function auth() { // state 1 requires a GET variable to exist if($this->state == 1 && !isset($_GET["oauth_verifier"])) { $this->state = 0; } // Step 1: Get a request token if($this->state == 0) { return $this->getRequestToken(); } // Step 2: Get an access token elseif($this->state == 1) { return $this->getAccessToken(); } // Step 3: Verify the access token return $this->verifyAccessToken(); }
Sebagian besar metode auth()
yang harusnya jelas. Berdasarkan state, itu mengeksekusi metode yang tepat untuk tahap otentikasi. Jika state adalah 1, oauth_verifier
mendapatkan variabel harus ada, jadi metode juga memeriksa itu.
Kita sekarang harus membuat metode publik untuk mengetahui jika kami dikonfirmasi. Metode isAuthed()
ini mengembalikan true jika keadaan 2:
/** * Check the current state of authentication * * @return bool True if state is 2 (authenticated) */ public function isAuthed() { return $this->state == 2; }
Kami juga dapat menggunakan metode untuk menghapus pengguna otentikasi. Metode endSession()
ini menetapkan keadaan ke 0 dan menghapus cookie yang mengandung token akses:
/** * Remove user's access token cookies */ public function endSession() { $this->state = 0; $_SESSION["authstate"] = 0; setcookie("access_token", "", 0); setcookie("access_token_secret", "", 0); }
Inisialisasi
Sekarang kita perlu menambahkan beberapa hal untuk metode __construct()
kami untuk mencari tahu yang menyatakan otentikasi aplikasi ini di atas inisialisasi. Juga, karena kode kita menggunakan variabel session, kita harus memastikan sesi dimulai dengan kode ini:
// start a session if one does not exist if(!session_id()) { session_start(); }
Ini bagian berikutnya adalah mana kita menentukan state. state dimulai pada 0; Jika ada cookie ditetapkan berisi token akses, state dianggap 2; gagal itu, negara diatur ke variabel session authstate
jika ada. Berikut adalah kode:
// determine the authentication status // default to 0 $this->state = 0; // 2 (authenticated) if the cookies are set if(isset($_COOKIE["access_token"], $_COOKIE["access_token_secret"])) { $this->state = 2; } // otherwise use value stored in session elseif(isset($_SESSION["authstate"])) { $this->state = (int)$_SESSION["authstate"]; }
Jika keadaan 1, yang berarti kita berada dalam proses otentikasi. Sehingga kita dapat pergi ke depan dan melanjutkan proses saat ini:
// if we are in the process of authentication we continue if($this->state == 1) { $this->auth(); }
Jika state 2, kami harus memverifikasi token akses. Jika otentikasi gagal, kode ini membersihkan cookie dan me-reset state:
// verify authentication, clearing cookies if it fails elseif($this->state == 2 && !$this->auth()) { $this->endSession(); }
Inilah konstruktor baru dengan perubahan yang dibuat:
/** * Initialize a new TwitterApp object * * @param tmhOAuth $tmhOAuth A tmhOAuth object with consumer key and secret */ public function __construct(tmhOAuth $tmhOAuth) { // save the tmhOAuth object $this->tmhOAuth = $tmhOAuth; // start a session if one does not exist if(!session_id()) { session_start(); } // determine the authentication status // default to 0 $this->state = 0; // 2 (authenticated) if the cookies are set if(isset($_COOKIE["access_token"], $_COOKIE["access_token_secret"])) { $this->state = 2; } // otherwise use value stored in session elseif(isset($_SESSION["authstate"])) { $this->state = (int)$_SESSION["authstate"]; } // if we are in the process of authentication we continue if($this->state == 1) { $this->auth(); } // verify authentication, clearing cookies if it fails elseif($this->state == 2 && !$this->auth()) { $this->endSession(); } }
Mengirim Tweet
Sekarang bahwa semua kode otorisasi lengkap, kita dapat menambahkan beberapa fungsi umum class kami. Berikut adalah metode untuk mengirim tweet melalui Twitter API:
/** * Send a tweet on the user's behalf * * @param string $text Text to tweet * @return bool Tweet successfully sent */ public function sendTweet($text) { // limit the string to 140 characters $text = substr($text, 0, 140); // POST the text to the statuses/update method $this->tmhOAuth->request("POST", $this->tmhOAuth->url("1/statuses/update"), array( 'status' => $text )); return ($this->tmhOAuth->response["code"] == 200); }
sendTweet()
metode menerima string, membatasi untuk 140 karakter, dan kemudian mengirimkan request POST 1/statuses/update. Pola ini harus cukup akrab dengan sekarang.
Full TwitterApp Class
<?php class TwitterApp { /** * This variable holds the tmhOAuth object used throughout the class * * @var tmhOAuth An object of the tmhOAuth class */ public $tmhOAuth; /** * User's Twitter account data * * @var array Information on the current authenticated user */ public $userdata; /** * Authentication state * * Values: * - 0: not authed * - 1: Request token obtained * - 2: Access token obtained (authed) * * @var int The current state of authentication */ protected $state; /** * Initialize a new TwitterApp object * * @param tmhOAuth $tmhOAuth A tmhOAuth object with consumer key and secret */ public function __construct(tmhOAuth $tmhOAuth) { // save the tmhOAuth object $this->tmhOAuth = $tmhOAuth; // start a session if one does not exist if(!session_id()) { session_start(); } // determine the authentication status // default to 0 $this->state = 0; // 2 (authenticated) if the cookies are set if(isset($_COOKIE["access_token"], $_COOKIE["access_token_secret"])) { $this->state = 2; } // otherwise use value stored in session elseif(isset($_SESSION["authstate"])) { $this->state = (int)$_SESSION["authstate"]; } // if we are in the process of authentication we continue if($this->state == 1) { $this->auth(); } // verify authentication, clearing cookies if it fails elseif($this->state == 2 && !$this->auth()) { $this->endSession(); } } /** * Authenticate user with Twitter * * @return bool Authentication successful */ public function auth() { // state 1 requires a GET variable to exist if($this->state == 1 && !isset($_GET["oauth_verifier"])) { $this->state = 0; } // Step 1: Get a request token if($this->state == 0) { return $this->getRequestToken(); } // Step 2: Get an access token elseif($this->state == 1) { return $this->getAccessToken(); } // Step 3: Verify the access token return $this->verifyAccessToken(); } /** * Obtain a request token from Twitter * * @return bool False if request failed */ private function getRequestToken() { // send request for a request token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/request_token", ""), array( // pass a variable to set the callback 'oauth_callback' => $this->tmhOAuth->php_self() )); if($this->tmhOAuth->response["code"] == 200) { // get and store the request token $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); $_SESSION["authtoken"] = $response["oauth_token"]; $_SESSION["authsecret"] = $response["oauth_token_secret"]; // state is now 1 $_SESSION["authstate"] = 1; // redirect the user to Twitter to authorize $url = $this->tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $response["oauth_token"]; header("Location: ' . $url); exit; } return false; } /** * Obtain an access token from Twitter * * @return bool False if request failed */ private function getAccessToken() { // set the request token and secret we have stored $this->tmhOAuth->config["user_token"] = $_SESSION["authtoken"]; $this->tmhOAuth->config["user_secret"] = $_SESSION["authsecret"]; // send request for an access token $this->tmhOAuth->request("POST", $this->tmhOAuth->url("oauth/access_token", ""), array( // pass the oauth_verifier received from Twitter 'oauth_verifier' => $_GET["oauth_verifier"] )); if($this->tmhOAuth->response["code"] == 200) { // get the access token and store it in a cookie $response = $this->tmhOAuth->extract_params($this->tmhOAuth->response["response"]); setcookie("access_token", $response["oauth_token"], time()+3600*24*30); setcookie("access_token_secret", $response["oauth_token_secret"], time()+3600*24*30); // state is now 2 $_SESSION["authstate"] = 2; // redirect user to clear leftover GET variables header("Location: ' . $this->tmhOAuth->php_self()); exit; } return false; } /** * Verify the validity of our access token * * @return bool Access token verified */ private function verifyAccessToken() { $this->tmhOAuth->config["user_token"] = $_COOKIE["access_token"]; $this->tmhOAuth->config["user_secret"] = $_COOKIE["access_token_secret"]; // send verification request to test access key $this->tmhOAuth->request("GET", $this->tmhOAuth->url("1/account/verify_credentials")); // store the user data returned from the API $this->userdata = json_decode($this->tmhOAuth->response["response"]); // HTTP 200 means we were successful return ($this->tmhOAuth->response["code"] == 200); } /** * Check the current state of authentication * * @return bool True if state is 2 (authenticated) */ public function isAuthed() { return $this->state == 2; } /** * Remove user's access token cookies */ public function endSession() { $this->state = 0; $_SESSION["authstate"] = 0; setcookie("access_token", "", 0); setcookie("access_token_secret", "", 0); } /** * Send a tweet on the user's behalf * * @param string $text Text to tweet * @return bool Tweet successfully sent */ public function sendTweet($text) { // limit the string to 140 characters $text = substr($text, 0, 140); // POST the text to the statuses/update method $this->tmhOAuth->request("POST", $this->tmhOAuth->url("1/statuses/update"), array( 'status' => $text )); return ($this->tmhOAuth->response["code"] == 200); } }
Aplikasi kami
Sekarang bahwa kita memiliki class yang menangani semua tugas-tugas OAuth, kita sekarang dapat menambah itu dengan fungsi khusus untuk aplikasi kita. Ini termasuk kemampuan untuk mendapatkan, mengubah dan menetapkan pengguna avatar.
Kita akan extend class TwitterApp dengan class TwitterAvatars. Mulai dengan kode berikut dalam file baru bernama lib/TwitterAvatars.php:
<?php class TwitterAvatars extends TwitterApp { /** * The path to our temporary files directory * * @var string Path to store image files */ public $path; /** * These are all the GD image filters available in this class * * @var array Associative array of image filters */ protected $filters = array( 'grayscale' => IMG_FILTER_GRAYSCALE, 'negative' => IMG_FILTER_NEGATE, 'edgedetect' => IMG_FILTER_EDGEDETECT, 'embossed' => IMG_FILTER_EMBOSS, 'blurry' => IMG_FILTER_GAUSSIAN_BLUR, 'sketchy' => IMG_FILTER_MEAN_REMOVAL ); /** * Initialize a new TwitterAvatars object * * @param tmhOAuth $tmhOAuth A tmhOAuth object with consumer key and secret * @param string $path Path to store image files (default 'tmp") */ public function __construct(tmhOAuth $tmhOAuth, $path = 'tmp") { // call the parent class' constructor parent::__construct($tmhOAuth); // save the path variable $this->path = $path; } }
Seperti yang Anda lihat, class yang diperpanjang memasukan $path
properti untuk menunjuk ke mana file sementara gambar akan pergi, properti $filters
memegang array filter gambar dan konstruktor tambahan dengan parameter untuk mengatur path. Karena kita override konstruktor asli, kita harus secara eksplisit memanggil constructor induk dengan parent::__construct().
Sekarang kita dapat mulai menambahkan metode kami.
Men-download
Jelas, kami akan memerlukan kemampuan untuk men-download gambar untuk memanipulasi mereka. Di sini adalah metode download()
generik yang menerima URL dan mengembalikan data di lokasi tersebut. Metode membuat cURL basic request.
/** * Download data from specified URL * * @param string $url URL to download * @return string Downloaded data */ protected function download($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $ret = curl_exec($ch); curl_close($ch); return $ret; }
Menemukan URL
Sekarang bahwa kita dapat men-download file, kita perlu menemukan lokasi file yang kita butuhkan. Ada dua gambar yang berbeda kami tertarik, standar ukuran thumbnail dan gambar berukuran penuh asli. Jadi, kita akan menciptakan sebuah metode untuk mendapatkan setiap URL.
Untuk mendapatkan standar ukuran thumbnail, kami akan memanggil users/profile_image/: screen_name API metode yang menanggapi dengan redirect ulang 302 gambar avatar user tertentu. Ini berarti URL akan ditemukan di header lokasi. Berikut adalah metode:
/** * Get the URL to the standard sized avatar * * @return string The URL to the image file */ protected function getImageURL() { // request user's 'bigger' profile image $this->tmhOAuth->request("GET", $this->tmhOAuth->url("1/users/profile_image/" . $this->userdata->screen_name), array( 'screen_name' => $this->userdata->screen_name, 'size' => 'bigger' )); if($this->tmhOAuth->response["code"] == 302) { // the direct URL is in the Location header return $this->tmhOAuth->response["headers"]["location"]; } throw new Exception("Error locating image"); }
Perhatikan bahwa kita membuat sebuah GET request dengan tmhOAuth, memasukan parameter screen_name
dan size
, kemudian kembali isi dari Location header.
Ada tidak ada metode API untuk mendapatkan image ukuran penuh, sehingga untuk metode kami berikutnya kami akan menipu sedikit dan mengedit URL. Data pengguna berisi bidang profile_image_url
yang mengarah pada sesuatu seperti avatar_normal.jpg, dan gambar asli dapat ditemukan di avatar.jpg tanpa akhiran. Jadi metode mendapatkan URL, menghilangkan akhiran ukuran dan kembali URL yang telah dimodifikasi:
/** * Get the URL to the full sized avatar * * @return string The URL to the image file */ protected function getOriginalImageURL() { // get the regular sized avatar $url = $this->userdata->profile_image_url; // save the extension for later $ext = strrchr($url, '."); // strip the "_normal' suffix and add back the extension return substr($url, 0, strrpos($url, "_")) . $ext; }
Membaca gambar
Sekarang bahwa kita dapat mencari dan men-download gambar, kita perlu cara untuk membacanya. Kita akan menggunakan GD library untuk memanipulasi gambar, sehingga metode ini akan mengkonversi data gambar mentah menjadi sumber gambar GD.
/** * Convert raw image data to a GD resource * * @param string $data Binary image data to parse * @return resource A GD image resource identifier */ protected function readImage($data) { // read in the original image $src = imagecreatefromstring($data); if(!$src) { throw new Exception("Error reading image"); } // get the dimensions $width = imagesx($src); $height = imagesy($src); // create a blank true color image of the same size $img = imagecreatetruecolor($width, $height); // copy the original image to this new canvas imagecopy($img, $src, 0, 0, 0, 0, $width, $height); // discard the source image imagedestroy($src); return $img; }
Untuk menggambarkan apa yang terjadi di atas:
- Data gambar dikonversi menjadi resource GD yang menggunakan fungsi
imagecreatefromstring().
- Dimensi gambar yang direkam menggunakan
imagesx()
danimagesy().
- Gambar kosong warna benar baru dengan dimensi yang sama dibuat menggunakan
imagecreatetruecolor().
- Gambar asli disalin ke gambar baru yang menggunakan fungsi
imagecopy().
Hasil ini dalam versi benar warna gambar asli terlepas dari modus warna asli. - Sumber gambar aslinya dihancurkan dengan menggunakan
imagedestroy()
dan menghandel untuk gambar baru dikembalikan.
Menyimpan gambar
Sekarang bahwa kita dapat men-download gambar dan menciptakan sumber daya GD, kita membutuhkan sebuah metode untuk menyimpan gambar ke sistem file. Berikut adalah metode yang menyimpan gambar disediakan sebagai PNG file dengan nama tertentu menggunakan imagepng():
/** * Save a GD image resource to a PNG file * * @param resource $img GD image resource identifier * @param string $name Name of the image * @return string Path to the saved image */ protected function saveImage($img, $name) { $path = $this->path . "/' . $name . '.png'; imagepng($img, $path); imagedestroy($img); return $path; }
Menghasilkan Previews
Sekarang bahwa kita memiliki semua potongan bahwa kekuatan aplikasi kami, kita dapat mulai menempatkan mereka bersama-sama. Dalam flow aplikasi kami, kami akan memberikan pengguna pilihan preview untuk memilih dari. Berikut adalah metode untuk menghasilkan preview-Preview:
/** * Generate previews for each image filter * * @return array Associative array of image previews */ public function generatePreviews() { // we need valid user info to know whose avatar to handle if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } $username = $this->userdata->screen_name; // cache the raw data to use $data = $this->download($this->getImageURL()); // copy the original image $img = $this->readImage($data); $this->saveImage($img, $username . "_orig"); // array to hold the list of previews $images = array(); // loop through each filter to generate previews foreach($this->filters as $filter_name => $filter) { $img = $this->readImage($data); imagefilter($img, $filter); $images[$filter_name] = $this->saveImage($img, $username . "_' . $filter_name); } return $images; }
Hal pertama yang kita lakukan adalah periksa bahwa pengguna diotentikasi dan kemudian ambil nama pengguna untuk menggunakan kemudian dalam nama file.
// we need valid user info to know whose avatar to handle if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } $username = $this->userdata->screen_name;
Kemudian kita download gambar pengguna menggunakan metode getImageURL()
dan download()
yang kami telah menciptakan. Data ini akan digunakan berulang kali untuk setiap pratinjau sehingga kita simpan dalam variabel $data.
// cache the raw data to use $data = $this->download($this->getImageURL());
Berikutnya, kita menyimpan salinan dimodifikasi dengan akhiran _orig. Ini adalah untuk perbandingan visual kemudian.
// copy the original image $img = $this->readImage($data); $this->saveImage($img, $username . "_orig");
Bagian terakhir dari metode adalah dimana kita loop melalui filter gambar yang tercantum dalam properti $filters,
menghasilkan gambar untuk tiap filter. Dalam setiap iterasi, kita membuat gambar dan menerapkan fungsi imagefilter(),
yang menerima salah satu konstanta yang kami telah terdaftar dalam $filters array.
Maka untuk setiap gambar yang kita simpan, kami menambahkan path ke array asosiatif (menggunakan nama filter sebagai key) yang metode ini mengemballikan di akhir.
// array to hold the list of previews $images = array(); // loop through each filter to generate previews foreach($this->filters as $filter_name => $filter) { $img = $this->readImage($data); imagefilter($img, $filter); $images[$filter_name] = $this->saveImage($img, $username . "_' . $filter_name); } return $images;
Bagian selanjutnya dari flow aplikasi kami meminta pengguna untuk mengkonfirmasi pilihan mereka, jadi kita perlu cara untuk mencari preview tertentu. Berikut adalah metode sederhana untuk mendapatkan path ke gambar berdasarkan pilihan yang dimasukan sebagai parameter, defaulting ke gambar asli:
/** * Get the path to a previously generated preview * * @param string $filter The image filter to get the preview for * @return string The path to the preview file or null if not found */ public function getPreview($filter = 'orig") { if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } $path = $this->path . "/' . $this->userdata->screen_name . "_' . $filter . '.png'; if(file_exists($path)) { return $path; } return null; }
Mengubah Avatar
Tahap akhir flow aplikasi kami adalah benar-benar mengubah avatar pengguna. Pertama kita perlu sebuah metode untuk mendapatkan image ukuran penuh dan menerapkan filter tertentu untuk itu. Berikut ini adalah:
/** * Process the user's full avatar using one of the filters * * @param string $filter The filter to apply to the image * @return string Path to the output file */ protected function processImage($filter = "grayscale") { // make sure the filter exists $filter = strtolower($filter); if(!array_key_exists($filter, $this->filters)) { throw new Exception("Unsupported image filter"); } $username = $this->userdata->screen_name; // get the full sized avatar $data = $this->download($this->getOriginalImageURL()); $img = $this->readImage($data); // apply the filter to the image imagefilter($img, $this->filters[$filter]); // save the image and return the path return $this->saveImage($img, $username . "_' . $filter . "_full"); }
Itu seharusnya mudah untuk mengikuti karena hal ini sangat mirip dengan metode generatePreviews().
Ini menerima parameter untuk menentukan sebuah gambar filter dan memeriksa bahwa itu ada. Kemudian download gambar asli dan berlaku filter untuk itu, mengembalikan pada gambar yang dihasilkan sebagai nilai kembalian.
Sekarang kita perlu metode yang benar-benar mengirim gambar yang dihasilkan untuk Twitter, memperbarui pengguna avatar. Metode ini memanggil metode processImage()
untuk membuat gambar dan upload ke Twitter melalui metode API 1/account/update_profile_image:
/** * Update user's avatar with a filtered version * * @param string $filter The filter to use * @return bool Operation successful */ public function commitAvatar($filter) { if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } // generate the image and get the path $path = $this->processImage($filter); if(file_exists($path)) { // send a multipart POST request with the image file data $this->tmhOAuth->request("POST", $this->tmhOAuth->url("1/account/update_profile_image"), array( // format: @local/path.png;type=mime/type;filename=file_name.png 'image' => '@' . $path . ';type=image/png;filename=' . basename($path) ), true, true); return ($this->tmhOAuth->response["code"] == 200); } return false; }
Bagian yang rumit di sini adalah request POST sebenarnya tmhOAuth, yang merupakan multipart request yang mengandung data gambar mentah. Untuk melakukan ini, kita harus menetapkan parameter terakhir metode tmhOAuth::request()
menjadi true
, dan memasukan variable image
dalam format khusus:
@[path_to_image]; type = [mime_type]; filename = [file_name]
Sebagai contoh, jika kita ingin meng-upload tmp/username_grayscale_full.png, nilai akan @tmp/username_grayscale_full.png;type=image/png;filename=username_grayscale_full.png.
Di sini adalah bagian dari kode lagi:
// send a multipart POST request with the image file data $this->tmhOAuth->request("POST", $this->tmhOAuth->url("1/account/update_profile_image"), array( // format: @local/path.png;type=mime/type;filename=file_name.png 'image' => '@' . $path . ';type=image/png;filename=' . basename($path) ), true, true);
Membersihkan
Efek samping dari semua manipulasi file ini adalah banyak file-file sementara yang tertinggal. Berikut adalah metode untuk membersihkan direktori sementara:
/** * Delete leftover image files */ public function cleanupFiles() { // file to track when we last checked $flag = $this->path . "/.last_check'; $time = time(); // have we checked within the last hour? if(!file_exists($flag) || $time - filemtime($flag) > 3600) { // get an array of PNG files in the directory $files = glob($this->path . "/*.png"); // loop through files, deleting old files (12+ hours) foreach($files as $file) { if($time - filemtime($file) > 60*60*12) { unlink($file); } } // update the timestamp of our flag file touch($flag); } }
Ini hanya loop melalui PNG file, menghapus file-lebih dari 12 jam. Juga memeriksa berapa lama sudah sejak kami memeriksa menggunakan stempel waktu di berkas .last_check, memungkinkan kita untuk membatasi memeriksa satu per jam. Dengan cara ini kita dapat memanggil metode ini pada setiap request tanpa membuang-buang sumber daya.
Catatan: Kami membuat penggunaan fungsi
glob() dalam PHP, yang adalah cara mudah untuk mendapatkan array file pattern.
Full TwitterAvatars Class
&?php class TwitterAvatars extends TwitterApp { /** * The path to our temporary files directory * * @var string Path to store image files */ public $path; /** * These are all the GD image filters available in this class * * @var array Associative array of image filters */ protected $filters = array( 'grayscale' => IMG_FILTER_GRAYSCALE, 'negative' => IMG_FILTER_NEGATE, 'edgedetect' => IMG_FILTER_EDGEDETECT, 'embossed' => IMG_FILTER_EMBOSS, 'blurry' => IMG_FILTER_GAUSSIAN_BLUR, 'sketchy' => IMG_FILTER_MEAN_REMOVAL ); /** * Initialize a new TwitterAvatars object * * @param tmhOAuth $tmhOAuth A tmhOAuth object with consumer key and secret * @param string $path Path to store image files (default 'tmp") */ public function __construct(tmhOAuth $tmhOAuth, $path = 'tmp") { // call the parent class' constructor parent::__construct($tmhOAuth); // save the path variable $this->path = $path; } /** * Download data from specified URL * * @param string $url URL to download * @return string Downloaded data */ protected function download($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $ret = curl_exec($ch); curl_close($ch); return $ret; } /** * Get the URL to the standard sized avatar * * @return string The URL to the image file */ protected function getImageURL() { // request user's 'bigger' profile image $this->tmhOAuth->request("GET", $this->tmhOAuth->url("1/users/profile_image/' . $this->userdata->screen_name), array( 'screen_name' => $this->userdata->screen_name, 'size' => 'bigger' )); if($this->tmhOAuth->response["code"] == 302) { // the direct URL is in the Location header return $this->tmhOAuth->response["headers"]["location"]; } throw new Exception("Error locating image"); } /** * Get the URL to the full sized avatar * * @return string The URL to the image file */ protected function getOriginalImageURL() { // get the regular sized avatar $url = $this->userdata->profile_image_url; // save the extension for later $ext = strrchr($url, '."); // strip the "_normal' suffix and add back the extension return substr($url, 0, strrpos($url, "_")) . $ext; } /** * Convert raw image data to a GD resource * * @param string $data Binary image data to parse * @return resource A GD image resource identifier */ protected function readImage($data) { // read in the original image $src = imagecreatefromstring($data); if(!$src) { throw new Exception("Error reading image"); } // get the dimensions $width = imagesx($src); $height = imagesy($src); // create a blank true color image of the same size $img = imagecreatetruecolor($width, $height); // copy the original image to this new canvas imagecopy($img, $src, 0, 0, 0, 0, $width, $height); // discard the source image imagedestroy($src); return $img; } /** * Save a GD image resource to a PNG file * * @param resource $img GD image resource identifier * @param string $name Name of the image * @return string Path to the saved image */ protected function saveImage($img, $name) { $path = $this->path . "/' . $name . '.png'; imagepng($img, $path); imagedestroy($img); return $path; } /** * Generate previews for each image filter * * @return array Associative array of image previews */ public function generatePreviews() { // we need valid user info to know whose avatar to handle if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } $username = $this->userdata->screen_name; // cache the raw data to use $data = $this->download($this->getImageURL()); // copy the original image $img = $this->readImage($data); $this->saveImage($img, $username . "_orig"); // array to hold the list of previews $images = array(); // loop through each filter to generate previews foreach($this->filters as $filter_name => $filter) { $img = $this->readImage($data); imagefilter($img, $filter); $images[$filter_name] = $this->saveImage($img, $username . "_' . $filter_name); } return $images; } /** * Get the path to a previously generated preview * * @param string $filter The image filter to get the preview for * @return string The path to the preview file or null if not found */ public function getPreview($filter = 'orig") { if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } $path = $this->path . "/' . $this->userdata->screen_name . "_' . $filter . '.png'; if(file_exists($path)) { return $path; } return null; } /** * Process the user's full avatar using one of the filters * * @param string $filter The filter to apply to the image * @return string Path to the output file */ protected function processImage($filter = 'grayscale") { // make sure the filter exists $filter = strtolower($filter); if(!array_key_exists($filter, $this->filters)) { throw new Exception("Unsupported image filter"); } $username = $this->userdata->screen_name; // get the full sized avatar $data = $this->download($this->getOriginalImageURL()); $img = $this->readImage($data); // apply the filter to the image imagefilter($img, $this->filters[$filter]); // save the image and return the path return $this->saveImage($img, $username . "_' . $filter . "_full"); } /** * Update user's avatar with a filtered version * * @param string $filter The filter to use * @return bool Operation successful */ public function commitAvatar($filter) { if(!$this->isAuthed()) { throw new Exception("Requires oauth authorization"); } // generate the image and get the path $path = $this->processImage($filter); if(file_exists($path)) { // send a multipart POST request with the image file data $this->tmhOAuth->request("POST", $this->tmhOAuth->url("1/account/update_profile_image"), array( // format: @local/path.png;type=mime/type;filename=file_name.png 'image' => '@' . $path . ';type=image/png;filename=' . basename($path) ), true, true); return ($this->tmhOAuth->response["code"] == 200); } return false; } /** * Delete leftover image files */ public function cleanupFiles() { // file to track when we last checked $flag = $this->path . "/.last_check'; $time = time(); // have we checked within the last hour? if(!file_exists($flag) || $time - filemtime($flag) > 3600) { // get an array of PNG files in the directory $files = glob($this->path . "/*.png"); // loop through files, deleting old files (12+ hours) foreach($files as $file) { if($time - filemtime($file) > 60*60*12) { unlink($file); } } // update the timestamp of our flag file touch($flag); } } }
Front End
Kami memiliki komponen semua aplikasi bersama-sama, jadi sekarang semua yang kita butuhkan adalah interface pengguna. Semua kode di sini akan masuk ke file index.php di direktori root. Kita akan mulai dengan termasuk Perpustakaan dan pengaturan konfigurasi:
<?php // include our libraries include 'lib/tmhOAuth.php'; include 'lib/TwitterApp.php'; include 'lib/TwitterAvatars.php'; // set the consumer key and secret define("CONSUMER_KEY", 'qSkJum23MqlG6greF8Z76A"); define("CONSUMER_SECRET", 'Bs738r5UY2R7e5mwp1ilU0voe8OtXAtifgtZe9EhXw"); ?>
Catatan: Pastikan untuk menggantikan CONSUMER_KEY
dan CONSUMER_SECRET
dengan punya anda sendiri.
Kami akan menempatkan kode kita dalam try-catch blok sehingga kami dapat menangani kesalahan, menetapkan pesan mereka ke variabel $error
.
try { } catch(Exception $e) { // catch any errors that may occur $error = $e; }
Dalam blok try block kita dapat mulai menulis kode kita, mulai dengan inisialisasi objek TwitterAvatars yang disebut $ta
dengan object tmhOAuthyang dikonfigurasi:
// our tmhOAuth settings $config = array( 'consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET ); // create a new TwitterAvatars object $ta = new TwitterAvatars(new tmhOAuth($config));
Kita dapat membersihkan file lama sementara saat ini:
// check for stale files $ta->cleanupFiles();
Selanjutnya kami memeriksa apakah pengguna diotentikasi atau, gagal, jika pengguna telah meminta otentikasi, dalam hal kita mulai proses dengan memanggil metode auth():
// check our authentication status if($ta->isAuthed()) { } // did the user request authorization? elseif(isset($_POST["auth"])) { // start authentication process $ta->auth(); }
Jika pengguna diotentikasi, kita perlu memeriksa jika pilihan telah dipilih, sebaliknya kita akan menghasilkan Preview:
// check our authentication status if($ta->isAuthed()) { // has the user selected an option? if(isset($_POST["filter"])) { } // generate previews if the user has not chosen else { // $previews will be a list of images $previews = $ta->generatePreviews(); } }
Jika opsi ini dipilih, kita perlu untuk mendapatkan path untuk gambar lama dan baru untuk menampilkan:
// has the user selected an option? if(isset($_POST["filter"])) { // get the image paths for display $original = $ta->getPreview(); $newimage = $ta->getPreview($_POST["filter"]); }
Akhirnya, kami memeriksa apakah pengguna telah mengkonfirmasi pilihan mereka dan menerapkan perubahan. Kami juga mengirim tweet jika diminta dan menetapkan variabel $success
ke true
:
// has the user selected an option? if(isset($_POST["filter"])) { // is the user sure? if(isset($_POST["confirm"])) { // change the user's avatar $ta->commitAvatar($_POST["filter"]); // tweet if the user chose to if(isset($_POST["tweet"])) { $ta->sendTweet("I just updated my avatar using Avatar Effects..."); } $success = true; } // get the image paths for display $original = $ta->getPreview(); $newimage = $ta->getPreview($_POST["filter"]); }
Berikut adalah apa yang kita miliki sejauh ini:
<?php // include our libraries include 'lib/tmhOAuth.php'; include 'lib/TwitterApp.php'; include 'lib/TwitterAvatars.php'; // set the consumer key and secret define("CONSUMER_KEY", 'qSkJum23MqlG6greF8Z76A"); define("CONSUMER_SECRET", 'Bs738r5UY2R7e5mwp1ilU0voe8OtXAtifgtZe9EhXw"); try { // our tmhOAuth settings $config = array( 'consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET ); // create a new TwitterAvatars object $ta = new TwitterAvatars(new tmhOAuth($config)); // check for stale files $ta->cleanupFiles(); // check our authentication status if($ta->isAuthed()) { // has the user selected an option? if(isset($_POST["filter"])) { // is the user sure? if(isset($_POST["confirm"])) { // change the user's avatar $ta->commitAvatar($_POST["filter"]); // tweet if the user chose to if(isset($_POST["tweet"])) { $ta->sendTweet("I just updated my avatar using Avatar Effects..."); } $success = true; } // get the image paths for display $original = $ta->getPreview(); $newimage = $ta->getPreview($_POST["filter"]); } // generate previews if the user has not chosen else { // $previews will be a list of images $previews = $ta->generatePreviews(); } } // did the user request authorization? elseif(isset($_POST["auth"])) { // start authentication process $ta->auth(); } } catch(Exception $e) { // catch any errors that may occur $error = $e; } ?>
HTML
Setelah kode PHP yang kami akan menampilkan HTML yang sesuai, yang dimulai dengan template ini, yang menetapkan judul dan judul utama:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Twitter Avatar Effects</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1>Twitter Avatar Effects</h1> </body> </html>
Berikut adalah dimana kami menampilkan sebuah form dengan input gambar untuk setiap preview:
<?php if(isset($previews)): ?> <h2>Choose your weapon...</h2> <form action="index.php" method="post"> <?php foreach($previews as $filter => $path): ?> <input type="image" src="<?php echo $path; ?>" alt="<?php echo ucfirst($filter); ?>" width="73" height="73" name="filter" value="<?php echo $filter; ?>"> <?php endforeach; ?> </form> <p>Select one of the images above to change your Twitter avatar.</p>
Berikut adalah halaman sukses:
<?php elseif(isset($success)): ?> <h2>Success! Your Twitter avatar is now:</h2> <img src="<?php echo $newimage; ?>" alt="Your Avatar" width="73" height="73"> <p><a href="http://twitter.com/<?php echo $ta->userdata->screen_name; ?>">Go see it</a></p>
Berikut adalah halaman konfirmasi, di mana kita menunjukkan perbandingan dan menawarkan kesempatan untuk membatalkan:
<?php elseif(isset($newimage)): ?> <h2>Are you sure?</h2> <img src="<?php echo $original; ?>" alt="Original" width="73" height="73"> <span class="arrow">⇒</span> <img src="<?php echo $newimage; ?>" alt="<?php echo ucfirst($_POST["filter"]); ?>"> <form action="index.php" method="post"> <input type="hidden" name="filter" value="<?php echo $_POST["filter"]; ?>"> <input type="submit" name="confirm" value="Confirm"> <a href="index.php">Cancel</a> <p><label>Tweet about your new avatar? <input type="checkbox" name="tweet" value="true"></label></p> </form>
Dicatat bahwa formulir konfirmasi termasuk filter yang dipilih dalam bidang tersembunyi.
Jika ada kesalahan, kami menunjukkan ini:
<?php elseif(isset($error)): ?> <p>Error. <a href="index.php">Try again?</a></p>
Tampilan default adalah tombol "Connect to Twitter" sebagai masukan gambar (download salah satu gambar dari bagian bawah halaman ini ke direktori img):
<?php else: ?> <form action="index.php" method="post"> <input type="image" src="img/sign-in-with-twitter-l.png" alt="Connect to Twitter" name="auth" value="1"> </form> <p>Connect to Twitter to use this app.</p> <?php endif; ?>
Inilah bagian HTML lengkap:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Twitter Avatar Effects</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1>Twitter Avatar Effects</h1> <?php if(isset($previews)): ?> <h2>Choose your weapon...</h2> <form action="index.php" method="post"> <?php foreach($previews as $filter => $path): ?> <input type="image" src="<?php echo $path; ?>" alt="<?php echo ucfirst($filter); ?>" width="73" height="73" name="filter" value="<?php echo $filter; ?>"> <?php endforeach; ?> </form> <p>Select one of the images above to change your Twitter avatar.</p> <?php elseif(isset($success)): ?> <h2>Success! Your Twitter avatar is now:</h2> <img src="<?php echo $newimage; ?>" alt="Your Avatar" width="73" height="73"> <p><a href="http://twitter.com/<?php echo $ta->userdata->screen_name; ?>">Go see it</a></p> <?php elseif(isset($newimage)): ?> <h2>Are you sure?</h2> <img src="<?php echo $original; ?>" alt="Original" width="73" height="73"> <span class="arrow">⇒</span> <img src="<?php echo $newimage; ?>" alt="<?php echo ucfirst($_POST["filter"]); ?>"> <form action="index.php" method="post"> <input type="hidden" name="filter" value="<?php echo $_POST["filter"]; ?>"> <input type="submit" name="confirm" value="Confirm"> <a href="index.php">Cancel</a> <p><label>Tweet about your new avatar? <input type="checkbox" name="tweet" value="true"></label></p> </form> <?php elseif(isset($error)): ?> <p>Error. <a href="index.php">Try again?</a></p> <?php else: ?> <form action="index.php" method="post"> <input type="image" src="img/sign-in-with-twitter-l.png" alt="Connect to Twitter" name="auth" value="1"> </form> <p>Connect to Twitter to use this app.</p> <?php endif; ?> </body> </html>
CSS
Berikut adalah beberapa dasar CSS untuk membuat antarmuka terlihat bagus, disimpan dalam css/style.css:
html { background-color: #eee; text-align: center; font-family: "Lucida Grande",Verdana, sans-serif; font-size: 16px; color: #224; } body { width: 700px; margin: 30px auto; background-color: #acf; padding: 10px; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; } p { font-size: 1em; } h1 { font-size: 2em; } h2 { font-size: 1.6em; } .arrow { font-size: 4em; font-weight: bold; }
Hasil
Berikut adalah video yang merinci bagaimana aplikasi selesai kita harus:
Kesimpulan
Jika Anda telah mengikuti tutorial ini semua jalan melalui itu, Anda harus memiliki pemahaman yang cukup baik tentang OAuth dan apa yang dibutuhkan untuk menciptakan sebuah aplikasi Twitter web sederhana. Menggunakan Twitter API mudah setelah Anda memahami konsep-konsep dasar - terutama jika Anda menggunakan perpustakaan seperti tmhOAuth untuk menangani hal kecil.
Contoh sederhana yang kita buat dalam tutorial ini dapat dengan mudah dimodifikasi atau menambah untuk melakukan sesuatu. Jadi jika Anda memiliki ide bagus untuk sebuah aplikasi Twitter baru yang keren, merasa bebas untuk menggunakan ini sebagai dasar.
Terima kasih untuk membaca. Jika Anda memiliki pertanyaan atau komentar tentang tutorial ini, silahkan post!