-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupload.php
executable file
·225 lines (181 loc) · 7.65 KB
/
upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
<?php
header('Content-type: application/rtf');
header('Content-Disposition: attachment; filename="file.rtf"');
// Pasta onde o arquivo vai ser salvo
$_UP['pasta'] = 'uploads/';
// Tamanho máximo do arquivo (em Bytes)
$_UP['tamanho'] = 1024 * 1024 * 2; // 2Mb
// Array com as extensões permitidas
$_UP['extensoes'] = array('jpg', 'png', 'gif','tif','pdf','bmp');
// Renomeia o arquivo? (Se true, o arquivo será salvo como .jpg e um nome único)
$_UP['renomeia'] = false;
// Array com os tipos de erros de upload do PHP
$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';
// Verifica se houve algum erro com o upload. Se sim, exibe a mensagem do erro
if ($_FILES['arquivo']['error'] != 0) {
die("Não foi possível fazer o upload, erro:" . $_UP['erros'][$_FILES['arquivo']['error']]);
exit; // Para a execução do script
}
// Caso script chegue a esse ponto, não houve erro com o upload e o PHP pode continuar
// Faz a verificação da extensão do arquivo
$extensao = strtolower(end(explode('.', $_FILES['arquivo']['name'])));
if (array_search($extensao, $_UP['extensoes']) === false) {
echo "Por favor, envie arquivos com as seguintes extensões: jpg, png ou gif";
exit;
}
// Faz a verificação do tamanho do arquivo
if ($_UP['tamanho'] < $_FILES['arquivo']['size']) {
echo "O arquivo enviado é muito grande, envie arquivos de até 2Mb.";
exit;
}
// O arquivo passou em todas as verificações, hora de tentar movê-lo para a pasta
// Primeiro verifica se deve trocar o nome do arquivo
if ($_UP['renomeia'] == true) {
// Cria um nome baseado no UNIX TIMESTAMP atual e com extensão .jpg
$nome_final = md5(time()).'.jpg';
} else {
// Mantém o nome original do arquivo
$nome_final = $_FILES['arquivo']['name'];
}
// Depois verifica se é possível mover o arquivo para a pasta escolhida
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] . $nome_final)) {
// Upload efetuado com sucesso, exibe uma mensagem e um link para o arquivo
//echo "Upload efetuado com sucesso!";
//echo '<a href="' . $_UP['pasta'] . $nome_final . '">Clique aqui para acessar o arquivo</a>';
// 1. Send image to Cloud OCR SDK using processImage call
// 2. Get response as xml
// 3. Read taskId from xml
// To create an application and obtain a password,
// register at http://cloud.ocrsdk.com/Account/Register
// More info on getting your application id and password at
// http://ocrsdk.com/documentation/faq/#faq3
// Name of application you created
$applicationId = 'serverocr';
// Password should be sent to your e-mail after application was created
$password = 'wOPEQpQbM/ATjPGkIau/l3a1';
$fileName = $nome_final;
// Get path to file that we are going to recognize
$local_directory=dirname(__FILE__).'/uploads/';
$filePath = $local_directory.'/'.$fileName;
if(!file_exists($filePath))
{
die('File '.$filePath.' not found.');
}
if(!is_readable($filePath) )
{
die('Access to file '.$filePath.' denied.');
}
// Recognizing with English language to rtf
// You can use combination of languages like ?language=english,russian or
// ?language=english,french,dutch
// For details, see API reference for processImage method
$url = 'http://cloud.ocrsdk.com/processImage?language=english&exportFormat=rtf';
// Send HTTP POST request and ret xml response
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_USERPWD, "$applicationId:$password");
curl_setopt($curlHandle, CURLOPT_POST, 1);
curl_setopt($curlHandle, CURLOPT_USERAGENT, "PHP Cloud OCR SDK Sample");
curl_setopt($curlHandle, CURLOPT_FAILONERROR, true);
$post_array = array();
if((version_compare(PHP_VERSION, '5.5') >= 0)) {
$post_array["my_file"] = new CURLFile($filePath);
} else {
$post_array["my_file"] = "@".$filePath;
}
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $post_array);
$response = curl_exec($curlHandle);
if($response == FALSE) {
$errorText = curl_error($curlHandle);
curl_close($curlHandle);
die($errorText);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
// Parse xml response
$xml = simplexml_load_string($response);
if($httpCode != 200) {
if(property_exists($xml, "message")) {
die($xml->message);
}
die("unexpected response ".$response);
}
$arr = $xml->task[0]->attributes();
$taskStatus = $arr["status"];
if($taskStatus != "Queued") {
die("Unexpected task status ".$taskStatus);
}
// Task id
$taskid = $arr["id"];
// 4. Get task information in a loop until task processing finishes
// 5. If response contains "Completed" staus - extract url with result
// 6. Download recognition result (text) and display it
$url = 'http://cloud.ocrsdk.com/getTaskStatus';
$qry_str = "?taskid=$taskid";
// Check task status in a loop until it is finished
// Note: it's recommended that your application waits
// at least 2 seconds before making the first getTaskStatus request
// and also between such requests for the same task.
// Making requests more often will not improve your application performance.
// Note: if your application queues several files and waits for them
// it's recommended that you use listFinishedTasks instead (which is described
// at http://ocrsdk.com/documentation/apireference/listFinishedTasks/).
while(true)
{
sleep(5);
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url.$qry_str);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_USERPWD, "$applicationId:$password");
curl_setopt($curlHandle, CURLOPT_USERAGENT, "PHP Cloud OCR SDK Sample");
curl_setopt($curlHandle, CURLOPT_FAILONERROR, true);
$response = curl_exec($curlHandle);
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
// parse xml
$xml = simplexml_load_string($response);
if($httpCode != 200) {
if(property_exists($xml, "message")) {
die($xml->message);
}
die("Unexpected response ".$response);
}
$arr = $xml->task[0]->attributes();
$taskStatus = $arr["status"];
if($taskStatus == "Queued" || $taskStatus == "InProgress") {
// continue waiting
continue;
}
if($taskStatus == "Completed") {
// exit this loop and proceed to handling the result
break;
}
if($taskStatus == "ProcessingFailed") {
die("Task processing failed: ".$arr["error"]);
}
die("Unexpected task status ".$taskStatus);
}
// Result is ready. Download it
$url = $arr["resultUrl"];
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
// Warning! This is for easier out-of-the box usage of the sample only.
// The URL to the result has https:// prefix, so SSL is required to
// download from it. For whatever reason PHP runtime fails to perform
// a request unless SSL certificate verification is off.
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curlHandle);
curl_close($curlHandle);
// Let user donwload rtf result
header('Content-Disposition: attachment; filename="file.rtf"');
echo $response;
} else {
// Não foi possível fazer o upload, provavelmente a pasta está incorreta
echo "Não foi possível enviar o arquivo, tente novamente";
}