Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Pobieranie token
Forum PHP.pl > Forum > PHP
janmaniek
Witam, mógłby mi ktoś pomóc z funkcją preg_match, bo robię skrypt i potrzebuję aby, token był automatycznie pobierany ze strony.

Tutaj jest ta funkcja (jak mam tak zrobione to nie chce dziłać) :
  1. protected function extractTokenFromLoginForm($html) {
  2. // <input type="hidden" name="t" value="UJygzfv9DLLCS-is7cLwgG7z" />
  3. //
  4. if (!preg_match('#<input name="t" value="([A-Za-z0-9_-]+)" type="hidden">#', $html, $matches))
  5. throw new Exception('Cannot extract login CSRF token.', self::CODE_SCRAPING_LOGIN);
  6. return $matches[1];
  7. }


A tutaj jest przykładowy token :
  1. <input name="t" value="c6XEy2NJYmyitA7wVgSYgmfs" type="hidden">
Pyton_000
Kod
'#<input name="t" value="([A-Za-z0-9_-]+)" type="hidden"#'
janmaniek
Dalej jest to samo. Bo to jest skrypt na wrzucanie plików na dropboxa i on kiedyś działał a teraz wyskakuje "Cannot extract login CSRF token.".

Jak coś to żeby sprawdzić token wystarczy wejść na stronę www.dropbox.com/login i w kodzie strony będzie linijka <input name="t" value="c6XEy2NJYmyitA7wVgSYgmfs" type="hidden"> w której będzie token.
Pyton_000
Ehhh...
Kod
#<input type="hidden" name="t" value="([\w_-]+)">#
janmaniek
Nadal ten sam błąd, próbowałem też podać ręcznie w kodzie token, ale on chyba się zmienia, a używam na hoście cba.pl.
Pyton_000
Zobacz co dostajesz w $html
janmaniek
tutaj jest funkcja logowania
  1. protected function login() {
  2. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN);
  3. $token = $this->extractTokenFromLoginForm($data);
  4.  
  5. $postData = array(
  6. 'login_email' => (string) $this->email,
  7. 'login_password' => (string) $this->password,
  8. 't' => $token
  9. );
  10. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN, http_build_query($postData));
  11.  
  12. if (stripos($data, 'location: /home') === FALSE)
  13. throw new Exception('Login unsuccessful.', self::CODE_LOGIN_ERROR);
  14.  
  15. $this->loggedIn = TRUE;
  16. }


a tutaj zawartość self::HTTPS_DROPBOX_COM_LOGIN
  1. const HTTPS_DROPBOX_COM_LOGIN = 'https://www.dropbox.com/login';
Pyton_000
No OK a sprawdziłeś jakie dane dostajesz w $data ?
janmaniek
Po zrobieniu tak, nic się nie wyświetla

  1. protected function login() {
  2. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN);
  3. echo $data;
  4. $token = $this->extractTokenFromLoginForm($data);
  5.  
  6. $postData = array(
  7. 'login_email' => (string) $this->email,
  8. 'login_password' => (string) $this->password,
  9. 't' => $token
  10. );
  11. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN, http_build_query($postData));
  12.  
  13. if (stripos($data, 'location: /home') === FALSE)
  14. throw new Exception('Login unsuccessful.', self::CODE_LOGIN_ERROR);
  15.  
  16. $this->loggedIn = TRUE;
  17. }
Pyton_000
ok, to powinno działać
Kod
'/input type="hidden" name="t" value="([A-Za-z0-9_-]*)"/'
janmaniek
Tutaj jest cały kod funkcji odpowiedzialnych za wysyłanie plików

A w tym oddzielnym pliku co próbowałem pobrać token, to wszystko działa prawidłowo. Nie trzeba było zmieniać tego co napisałeś wyżej.

  1. <?php
  2. /**
  3.  * Dropbox Uploader
  4.  *
  5.  * Copyright (c) 2009 Jaka Jancar
  6.  *
  7.  * Permission is hereby granted, free of charge, to any person obtaining a copy
  8.  * of this software and associated documentation files (the "Software"), to deal
  9.  * in the Software without restriction, including without limitation the rights
  10.  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11.  * copies of the Software, and to permit persons to whom the Software is
  12.  * furnished to do so, subject to the following conditions:
  13.  *
  14.  * The above copyright notice and this permission notice shall be included in
  15.  * all copies or substantial portions of the Software.
  16.  *
  17.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20.  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23.  * THE SOFTWARE.
  24.  *
  25.  * @author Jaka Jancar [jaka@kubje.org] [http://jaka.kubje.org/]
  26.  * @version 1.1.12
  27.  */
  28. class DropboxUploader {
  29. /**
  30.   * Certificate Authority Certificate source types
  31.   */
  32. const CACERT_SOURCE_SYSTEM = 0;
  33. const CACERT_SOURCE_FILE = 1;
  34. const CACERT_SOURCE_DIR = 2;
  35. /**
  36.   * Dropbox configuration
  37.   */
  38. const DROPBOX_UPLOAD_LIMIT_IN_BYTES = 314572800;
  39. const HTTPS_DROPBOX_COM_HOME = 'https://www.dropbox.com/home';
  40. const HTTPS_DROPBOX_COM_LOGIN = 'https://www.dropbox.com/login';
  41. const HTTPS_DROPBOX_COM_UPLOAD = 'https://dl-web.dropbox.com/upload';
  42. /**
  43.   * DropboxUploader Error Flags and Codes
  44.   */
  45. const FLAG_DROPBOX_GENERIC = 0x10000000;
  46. const FLAG_LOCAL_FILE_IO = 0x10010000;
  47. const CODE_FILE_READ_ERROR = 0x10010101;
  48. const CODE_TEMP_FILE_CREATE_ERROR = 0x10010102;
  49. const CODE_TEMP_FILE_WRITE_ERROR = 0x10010103;
  50. const FLAG_PARAMETER_INVALID = 0x10020000;
  51. const CODE_PARAMETER_TYPE_ERROR = 0x10020101;
  52. const CODE_FILESIZE_TOO_LARGE = 0x10020201;
  53. const FLAG_REMOTE = 0x10040000;
  54. const CODE_CURL_ERROR = 0x10040101;
  55. const CODE_LOGIN_ERROR = 0x10040201;
  56. const CODE_UPLOAD_ERROR = 0x10040401;
  57. const CODE_SCRAPING_FORM = 0x10040801;
  58. const CODE_SCRAPING_LOGIN = 0x10040802;
  59. const CODE_CURL_EXTENSION_MISSING = 0x10080101;
  60. protected $email;
  61. protected $password;
  62. protected $caCertSourceType = self::CACERT_SOURCE_SYSTEM;
  63. protected $caCertSource;
  64. protected $loggedIn = FALSE;
  65. protected $cookies = array();
  66.  
  67. /**
  68.   * Constructor
  69.   *
  70.   * @param string $email
  71.   * @param string $password
  72.   * @throws Exception
  73.   */
  74. public function __construct($email, $password) {
  75. // Check requirements
  76. if (!extension_loaded('curl'))
  77. throw new Exception('DropboxUploader requires the cURL extension.', self::CODE_CURL_EXTENSION_MISSING);
  78.  
  79. if (empty($email) || empty($password)) {
  80. throw new Exception((empty($email) ? 'Email' : 'Password') . ' must not be empty.', self::CODE_PARAMETER_TYPE_ERROR);
  81. }
  82.  
  83. $this->email = $email;
  84. $this->password = $password;
  85. }
  86.  
  87. public function setCaCertificateDir($dir) {
  88. $this->caCertSourceType = self::CACERT_SOURCE_DIR;
  89. $this->caCertSource = $dir;
  90. }
  91.  
  92. public function setCaCertificateFile($file) {
  93. $this->caCertSourceType = self::CACERT_SOURCE_FILE;
  94. $this->caCertSource = $file;
  95. }
  96.  
  97. public function upload($source, $remoteDir = '/', $remoteName = NULL) {
  98. if (!is_file($source) or !is_readable($source))
  99. throw new Exception("File '$source' does not exist or is not readable.", self::CODE_FILE_READ_ERROR);
  100.  
  101. $filesize = filesize($source);
  102. if ($filesize < 0 or $filesize > self::DROPBOX_UPLOAD_LIMIT_IN_BYTES) {
  103. throw new Exception("File '$source' too large ($filesize bytes).", self::CODE_FILESIZE_TOO_LARGE);
  104. }
  105.  
  106. if (!is_string($remoteDir))
  107. throw new Exception("Remote directory must be a string, is " . gettype($remoteDir) . " instead.", self::CODE_PARAMETER_TYPE_ERROR);
  108.  
  109. if (is_null($remoteName)) {
  110. # intentionally left blank
  111. } else if (!is_string($remoteName)) {
  112. throw new Exception("Remote filename must be a string, is " . gettype($remoteDir) . " instead.", self::CODE_PARAMETER_TYPE_ERROR);
  113. } else {
  114. $source .= ';filename=' . $remoteName;
  115. }
  116.  
  117. if (!$this->loggedIn)
  118. $this->login();
  119.  
  120. $data = $this->request(self::HTTPS_DROPBOX_COM_HOME);
  121. $token = $this->extractToken($data, self::HTTPS_DROPBOX_COM_UPLOAD);
  122.  
  123. $postData = array(
  124. 'plain' => 'yes',
  125. 'file' => '@' . $source,
  126. 'dest' => $remoteDir,
  127. 't' => $token
  128. );
  129. $data = $this->request(self::HTTPS_DROPBOX_COM_UPLOAD, $postData);
  130. if (strpos($data, 'HTTP/1.1 302 FOUND') === FALSE)
  131. throw new Exception('Upload failed!', self::CODE_UPLOAD_ERROR);
  132. }
  133.  
  134. public function uploadString($string, $remoteName, $remoteDir = '/') {
  135. $exception = NULL;
  136.  
  137. $file = tempnam(sys_get_temp_dir(), 'DBUploadString');
  138. if (!is_file($file))
  139. throw new Exception("Can not create temporary file.", self::CODE_TEMP_FILE_CREATE_ERROR);
  140.  
  141. $bytes = file_put_contents($file, $string);
  142. if ($bytes === FALSE) {
  143. unlink($file);
  144. throw new Exception("Can not write to temporary file '$file'.", self::CODE_TEMP_FILE_WRITE_ERROR);
  145. }
  146.  
  147. try {
  148. $this->upload($file, $remoteDir, $remoteName);
  149. } catch (Exception $exception) {
  150. # intentionally left blank
  151. }
  152.  
  153. unlink($file);
  154.  
  155. if ($exception)
  156. throw $exception;
  157. }
  158.  
  159. protected function login() {
  160. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN);
  161. echo $data;
  162. $token = $this->extractTokenFromLoginForm($data);
  163.  
  164. $postData = array(
  165. 'login_email' => (string) $this->email,
  166. 'login_password' => (string) $this->password,
  167. 't' => $token
  168. );
  169. $data = $this->request(self::HTTPS_DROPBOX_COM_LOGIN, http_build_query($postData));
  170.  
  171. if (stripos($data, 'location: /home') === FALSE)
  172. throw new Exception('Login unsuccessful.', self::CODE_LOGIN_ERROR);
  173.  
  174. $this->loggedIn = TRUE;
  175. }
  176.  
  177. protected function request($url, $postData = NULL) {
  178. $ch = curl_init();
  179. curl_setopt($ch, CURLOPT_URL, (string) $url);
  180. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  181. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
  182. switch ($this->caCertSourceType) {
  183. case self::CACERT_SOURCE_FILE:
  184. curl_setopt($ch, CURLOPT_CAINFO, (string) $this->caCertSource);
  185. break;
  186. case self::CACERT_SOURCE_DIR:
  187. curl_setopt($ch, CURLOPT_CAPATH, (string) $this->caCertSource);
  188. break;
  189. }
  190. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  191. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  192. if (NULL !== $postData) {
  193. curl_setopt($ch, CURLOPT_POST, TRUE);
  194. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  195. }
  196.  
  197. // Send cookies
  198. $rawCookies = array();
  199. foreach ($this->cookies as $k => $v)
  200. $rawCookies[] = "$k=$v";
  201. $rawCookies = implode(';', $rawCookies);
  202. curl_setopt($ch, CURLOPT_COOKIE, $rawCookies);
  203.  
  204. $data = curl_exec($ch);
  205. $error = sprintf('Curl error: (#%d) %s', curl_errno($ch), curl_error($ch));
  206. curl_close($ch);
  207.  
  208. if ($data === FALSE) {
  209. throw new Exception($error, self::CODE_CURL_ERROR);
  210. }
  211.  
  212. // Store received cookies
  213. preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches, PREG_SET_ORDER);
  214. foreach ($matches as $match)
  215. $this->cookies[$match[1]] = $match[2];
  216.  
  217. return $data;
  218. }
  219.  
  220. protected function extractToken($html, $formAction) {
  221. $quot = preg_quote($formAction, '/');
  222. $pattern = '/<form [^>]*' . $quot . '[^>]*>.*?(?:<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is';
  223. if (!preg_match($pattern, $html, $matches))
  224. throw new Exception("Cannot extract token! (form action is '$formAction')", self::CODE_SCRAPING_FORM);
  225. return $matches[1];
  226. }
  227.  
  228. protected function extractTokenFromLoginForm($html) {
  229. // <input type="hidden" name="t" value="UJygzfv9DLLCS-is7cLwgG7z" />
  230. // <input type="hidden" name="t" value="c6XEy2NJYmyitA7wVgSYgmfs" />
  231. if (!preg_match('<input type="hidden" name="t" value="([\w_-]+)" />', $html, $matches))
  232. throw new Exception('Cannot extract login CSRF token.', self::CODE_SCRAPING_LOGIN);
  233.  
  234. echo $matches[1];
  235. return $matches[1];
  236. }
  237.  
  238. }
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.