api file
Code (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
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
<?php
*
*/
// this line starts the server session - that means the server will "remember" the user
// between different API calls - ie. once the user is authorized, he will stay logged in for a while
session_start();
// the requre lines include the lib and api source files
require("lib.php");
require("api.php");
// this instructs the client (in this case the iPhone app)
// that the server will output JSON data
header("Content-Type: application/json");
// the iPhone app sends over what "command" of the API it wants executed
// the tutorial covers "login","register","upload", "logout" and "stream"
// so using a switch statement for this taks makes most sense
// the functions you call inside the switch are found in the api.php file
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']);
break;
case "register":
register($_POST['username'], $_POST['password']);
break;
case "upload":
upload($_SESSION['IdUser'], $_FILES['file'], $_POST['title']);
break;
case "logout":
logout();
break;
case "stream":
stream((int)$_POST['IdPhoto']);
break;
}
// this line is redundant as the file ends anyway,
// but just making sure no more code gets executed
exit();
?>
*
*/
// this line starts the server session - that means the server will "remember" the user
// between different API calls - ie. once the user is authorized, he will stay logged in for a while
session_start();
// the requre lines include the lib and api source files
require("lib.php");
require("api.php");
// this instructs the client (in this case the iPhone app)
// that the server will output JSON data
header("Content-Type: application/json");
// the iPhone app sends over what "command" of the API it wants executed
// the tutorial covers "login","register","upload", "logout" and "stream"
// so using a switch statement for this taks makes most sense
// the functions you call inside the switch are found in the api.php file
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']);
break;
case "register":
register($_POST['username'], $_POST['password']);
break;
case "upload":
upload($_SESSION['IdUser'], $_FILES['file'], $_POST['title']);
break;
case "logout":
logout();
break;
case "stream":
stream((int)$_POST['IdPhoto']);
break;
}
// this line is redundant as the file ends anyway,
// but just making sure no more code gets executed
exit();
?>
Greg gil op 05/12/2015 20:08:28:
Ik krijg een foutmelding
Welke?
Code (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
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
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
// register API
function register($user, $pass) {
//check if username exists in the database (inside the "login" table)
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
//the username exists, return error to the iPhone app
errorJson('Username already exists');
}
// send confirmation email nog schrijven !!!
//try to insert a new row in the "login" table with the given username and password
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//registration is susccessfull, try to also directly login the new user
login($user, $pass);
}else {
//for some database reason the registration is unsuccessfull
errorJson('Registration failed');
}
}
//login API
function login($user, $pass) {
// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
// a row was found in the database for username/pass combination
// save a simple flag in the user session, so the server remembers that the user is authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
// print out the JSON of the user data to the iPhone app; it looks like this:
// {IdUser:1, username: "Name"}
print json_encode($result);
} else {
// no matching username/password was found in the login table
errorJson('Authorization failed');
}
}
//upload API
function upload($id, $photoData, $title) {
// check if there was no error during the file upload
if ($photoData['error']==0) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the photos table
$IdPhoto = mysqli_insert_id($link);
// move the temporarily stored file to a convenient location
// your photo is automatically saved by PHP in a temp folder
// you need to move it over yourself to your own "upload" folder
if (move_uploaded_file($photoData['tmp_name'], "upload/".$title.".jpg")) {
// file moved, all good, generate thumbnail
thumb("upload/".$IdPhoto.".jpg", 180);
//just print out confirmation to the iPhone app
print json_encode(array('successful'=>1));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
} else {
errorJson('Upload malfunction');
}
}
//logout API
function logout() {
// by saving an empty array to $_SESSION you are
// effectively destroying all the user session data
// ie. the server won't "remember" anymore anything about
// the current user
$_SESSION = array();
// and to make double-sure, there's also a built-in function
// which wipes out the user session
session_destroy();
}
?>
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
// register API
function register($user, $pass) {
//check if username exists in the database (inside the "login" table)
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
//the username exists, return error to the iPhone app
errorJson('Username already exists');
}
// send confirmation email nog schrijven !!!
//try to insert a new row in the "login" table with the given username and password
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//registration is susccessfull, try to also directly login the new user
login($user, $pass);
}else {
//for some database reason the registration is unsuccessfull
errorJson('Registration failed');
}
}
//login API
function login($user, $pass) {
// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
// a row was found in the database for username/pass combination
// save a simple flag in the user session, so the server remembers that the user is authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
// print out the JSON of the user data to the iPhone app; it looks like this:
// {IdUser:1, username: "Name"}
print json_encode($result);
} else {
// no matching username/password was found in the login table
errorJson('Authorization failed');
}
}
//upload API
function upload($id, $photoData, $title) {
// check if there was no error during the file upload
if ($photoData['error']==0) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the photos table
$IdPhoto = mysqli_insert_id($link);
// move the temporarily stored file to a convenient location
// your photo is automatically saved by PHP in a temp folder
// you need to move it over yourself to your own "upload" folder
if (move_uploaded_file($photoData['tmp_name'], "upload/".$title.".jpg")) {
// file moved, all good, generate thumbnail
thumb("upload/".$IdPhoto.".jpg", 180);
//just print out confirmation to the iPhone app
print json_encode(array('successful'=>1));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
} else {
errorJson('Upload malfunction');
}
}
//logout API
function logout() {
// by saving an empty array to $_SESSION you are
// effectively destroying all the user session data
// ie. the server won't "remember" anymore anything about
// the current user
$_SESSION = array();
// and to make double-sure, there's also a built-in function
// which wipes out the user session
session_destroy();
}
?>
We missen nog steeds een antwoord ;)
- SanThe - op 05/12/2015 20:12:28:
Welke?
Greg gil op 05/12/2015 20:08:28:
Ik krijg een foutmelding
Welke?
Expected content type {("text/json", "application/json", "text/javascript")}, got text/html
Als ik naar het script kijk mis ik waar de aanroepen werkelijk plaatsvinden. Dus function calls naar bijvoorbeeld login() etc. Op dat punt zal de foutmelding ook ergens staan. Overigens is de melding wel duidelijk genoeg, je stuurt het verkeerde content-type.
Er zou ook nog een fout in de response kunnen zitten waardoor een foutmelding afgedrukt wordt en zodoende het resultaat foutief als HTML geinterpreteerd wordt.
Zou ook kunnen, en gezien de "text/javascript" kun je heel goed gelijk hebben. Echter zonder de juiste code is het gissen.
Dit is mijn lib.php (behalve mijn database gegevens)
Code (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
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
<?php
//setup db connection
$link = mysqli_connect();
mysqli_select_db($link, "iReport");
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
//setup db connection
$link = mysqli_connect();
mysqli_select_db($link, "iReport");
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>