When i tried to UPDATE / PUT fields from iOS to PHP server and am not getting these value over there.
this is my iOS Code
NSString *url=#"http://example.com/project/php/basicinfo.php";
NSString *stringData = [NSString stringWithFormat:#"fname=%#&mname=%#&lname=%#&email=%#&country=%#&city=%#&dob=%#&role=%#",firstNameCell.fname.text ,mnameCell.mname.text,lnameCell.lname.text,emailCell.email.text,[countryCell.country currentTitle],cityCell.city.text,[dobCell.dob currentTitle],#"Model"];
NSLog(#"%#",stringData);
NSURL *aUrl = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"UPDATE"];
[request setHTTPBody:[stringData dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
When i echo in PHP its coming as empty.
Pls help me
This is the receiving response
Did Receive Response <NSHTTPURLResponse: 0x14ef17e40> { URL: http://example.com/project/php/basicinfo.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 1;
"Content-Type" = "text/html; charset=utf-8";
Date = "Fri, 15 Jan 2016 15:15:40 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
"X-Powered-By" = "PHP/5.5.9-1ubuntu4.11";
} }
PHP Code
<?php
header("Content-type: text/html; charset=utf-8");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$charset="UTF8";
$fname=$_POST['fname'];
$mname=$_POST['mname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];
$dob=$_POST['dob'];
$role=$_POST['role'];
echo $name;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/* change character set to utf8 */
if (!mysqli_set_charset($conn, "utf8")) {
exit();
} else {
mysqli_close($link);
echo $email;
$sql="UPDATE `basicinfo` SET `fname`='$fname',`mname`='$mname',`lname`='$lname',`email`='$email',`country`='$country',`city`='$city',`dob`='$dob',`role`='$role' WHERE `email`='$email'";
if ($conn->query($sql) === TRUE) {
// echo $email;
} else {
echo "fail";
}
//printf("Current character set: %s\n", mysqli_character_set_name($conn));
}
?>
if you use UPDATE HTTP method to call your script $_POST won't work.
You can do something like that:
$rest = $_SERVER['REQUEST_METHOD'];
if(isset($_SERVER['CONTENT_TYPE'])) {
$content_type = $_SERVER['CONTENT_TYPE'];
}
if ($rest=="PUT") {
$body = file_get_contents("php://input");
parse_str($body, $parsed);
switch ($content_type)
{
case "application/json":
// do stuff
break;
case "application/x-www-form-urlencoded":
// do stuff
break;
}
break;
}
}
Or use POST
Related
I'm using php method as web service to add user_comment to mysql database.
<?php
require '../database/connection.php';
extract($_POST);
if (isset($_GET['book_ID'])) {
$book_ID = $_GET['book_ID'];
$user_ID = $_GET['user_ID'];
$theComment = $_GET['theComment'];
}
if (!$db) {
$json[] = array("Message" => "Connection failed");
echo json_encode($json);
}
$sql = mysql_query("INSERT INTO Comment (user_ID , book_ID , theComment) VALUES ('$user_ID','$book_ID','$theComment')");
mysql_query($sql, $db);
$json[] = array("Message" => "Done");
echo json_encode($json);
everything fine if I type English but I have problem with Arabic
Objective-C:
-(NSString *)addCommentForBook:(NSString *)bookID userID:(NSString *)userID theComment:(NSString *)theComment{
NSString *dt = [NSString stringWithFormat:#"?book_ID=%#&user_ID=%#&theComment=%#",bookID,userID,theComment];
NSURL *myURL = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"http://www.myweb.com/library/Books/addCommentForBook.php%#",dt]];
NSMutableDictionary *theArray;
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
if (myData) {
id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
theArray = (NSMutableDictionary *)myJSON;
}
return [[theArray valueForKey:#"Message"]objectAtIndex:0];
}
If I test from Browser work php work fine with Arabic but from iOS not work
Any one tell me what's wrong or do I need to convert the string from UITextField first or?
What could be wrong with this code, I'm trying to get into my MAMP sever which is turned on, I have one php file in the server where I'm testing the connections and such, this:
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
echo $username
echo $password
if($username && $password) {
$db_name = 'DBTest';
$db_user = 'pedro';
$db_password = 'pedro';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
And in Xcode The app currently has 3 views all in swift, but the important one is this:
//
// LogInViewController.swift
// ParkingApp
//
// Created by Pedro Alonso on 02/06/15.
// Copyright (c) 2015 Pedro Alonso. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
#IBOutlet weak var loginLabel: UILabel!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
#IBAction func enterTapped(sender: UIButton) {
var username: String = usernameField.text
var password: String = passwordField.text
if ( username.isEmpty || password.isEmpty) {
var alertView: UIAlertView = UIAlertView()
alertView.title = "Failed"
alertView.message = "Error in the username or password"
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
} else {
var post: String = "username=\(username)&password=\(password)"
NSLog("Post data: %#", post)
println(post)
var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")!
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!
var postLenght: String = String(postData.length)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLenght, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if urlData != nil {
let res = response as! NSHTTPURLResponse!
println(urlData)
NSLog("Response code: %ld", res.statusCode)
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
NSLog("Response: ==> %#", responseData)
var error: NSError?
let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
let succes: Int = jsonData.valueForKey("succes") as! Int
if succes == 1 {
NSLog("Login Success")
var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var errorMsg: String?
if jsonData["error_message"] as? String != nil {
errorMsg = jsonData["error_message"] as! String?
} else {
errorMsg = "Unknown error"
}
var alertView: UIAlertView = UIAlertView()
alertView.title = "Sign in failed"
alertView.message = errorMsg
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = responseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}
The .php file is in /Applications/MAMP/htdocs, what is not clear is why is giving me response code 500, and I'm at a lost not sure why is happening. Any help?? Thanks.
EDIT: The response:
<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 04 Jun 2015 12:11:35 GMT";
Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.7";
} }
I can access from safari in the simulator to localhost:8888, so there is no connection problem.
EDIT2: So it is the request apparently, because it tells me invalid data skipping all and returning this:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
What could be wrong with the way I've done the request?
EDIT2: I have changed the code and activated the mysql log to see the queries, but still the $stmt->get_result() or fetch() are doing nothing and I do not know why. I'm not doing it throughout IOS but simple browser here is the troublesome part.
Modified part:
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?";
if ($stmt = $mysqli->prepare($query)) {
//$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->sqlstate;
var_dump($stmt);
/* bind result variables */
//$stmt->bind_result($dataOne,$password);
$result = $stmt->get_result();
printf("test: ", $dataOne, $password);
//fetch value
while($stmt->fetch()) {
echo $dataOne;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($result != null) {
error_log("User $username: password match.");
echo '{"success":1, "dataOne:"'.$dataOne.'}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
The $stmt is not retuning anything on the get_result() or is not going into the while(fetch()) I'm just do not know now. Any help?
Well, if your web server is throwing http error code 500 (Internal Error) it is because your PHP script is crashing. I would try and read the php log, and try and do some debugging of the php script.
Maybe there is something wrong with the posted data from your iOS app, making the php script fail?
Also accessing localhost:8888 from safari in this case would not prove that the php script is working, as it requires you to post any data for the script to execute. if($_POST) {. By just browsing that script, the if statement will never be true.
EDIT:
It some times helps to verify one component at a time. Try building a simple html form that posts username and password against your server (http://localhost:8888/jsonlogin2.php). When you see this working as expected, move on to making sure the app works. This way you can tell if your errors are on the server (php script) or in your app.
It's also good to check $_POST like this:
if (!empty($_POST)) {}
This will check if the $_POSTis empty.
Your app is also using application/x-form-urlencoded and my guess is that this should be: application/x-www-form-urlencoded.
But once again. Make a local html form, and make certain that your php script is working, and then move over to the app.
I'm attempting to verify the integrity of a consumable purchase in my app.
I've tested my in app purchase and it works fine. However, upon testing it with an "In-App-Purchase Cracker" with a jailbroken device, I realized that All of my receipts returned ok by apple's servers regardless of whether the purchase actually happened or not.
My transaction listener:
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
[self unlockFeature];
[[SKPaymentQueue defaultQueue]
finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
NSLog(#"Transaction Failed");
[[SKPaymentQueue defaultQueue]
finishTransaction:transaction];
break;
default:
break;
}
}
unlockFeature:
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
NSString *rs = [receipt base64EncodedStringWithOptions:kNilOptions];
NSInteger amt = _cDonAmt;
_cDonAmt = 0;
if (receipt) {
NSURL *url = [NSURL URLWithString:#"http://example.com/verifyDonation.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[MasterViewController getUserId] forKey:#"userID"];
[request setPostValue:rs forKey:#"receipt"];
[request setPostValue:[NSString stringWithFormat:#"%ld",(long)amt] forKey:#"dAmt"];
[request setDelegate:self];
[request startAsynchronous];
}
I'm hoping that my error might lie in my PHP Verification script
<?php
class VerifyDonation {
function verify() {
$uid = htmlspecialchars($_POST["userID"]);
$dA = intval(htmlspecialchars($_POST["dAmt"]));
$receipti = $_POST["receipt"];
$sandbox = true;
//start getting
if ($sandbox)
$verify_host = "ssl://sandbox.itunes.apple.com";
else
$verify_host = "ssl://buy.itunes.apple.com";
$json='{"receipt-data" : "'.$receipti.'" }';
//opening socket to itunes
$fp = fsockopen ($verify_host, 443, $errno, $errstr, 30);
if (!$fp)
{
// HTTP ERROR
return false;
}
else
{
//iTune's request url is /verifyReceipt
$header = "POST /verifyReceipt HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($json) . "\r\n\r\n";
fputs ($fp, $header . $json);
$res = '';
while (!feof($fp))
{
$step_res = fgets ($fp, 1024);
$res = $res . $step_res;
}
fclose ($fp);
//taking the JSON response
$json_source = substr($res, stripos($res, "\r\n\r\n{") + 4);
//decoding
$app_store_response_map = json_decode($json_source);
$app_store_response_status = $app_store_response_map->{'status'};
//end geting
if ($app_store_response_status == 0)//eithr OK or expired and needs to synch
{
echo "validReceipt";
$link = mysql_connect("localhost", "user", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("database");
mysql_query("UPDATE `users` SET `donarAmt`= donarAmt + $dA WHERE facebookId = $uid");
return true;
}
else
{
echo "invalidReceipt";
return false;
}
}
}
}
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$ver = new VerifyDonation;
$ver->verify();
?>
I have an app that receives a JSON file generated by my jason.php script and displays the data in a table view.
It works fine until I try to use 'include(db_connect.php)' in my jason.php file to pass the database log in details to it.
Running my php script, with 'include(db_connect.php)', does work in a browser (returns the JSON file formatted correctly) but it doesn’t work on my phone.
However..
It does work on my phone if I just paste the contents of db_connect.php into the jason.php file...and it returns exactly the same JSON file in a browser.
Both ways return exactly the same JSON text in browser.
All the app does is expect to receive a JSON file from a specified URL, it does’t pass anything to it. Just visits the URL and stores whats returned in an NSData object.
If anyone knows why this is happening I would be grateful to know!
Thanks
jason.php: this returns a the JSON script perfectly in my browser
<?php
require("db_connect.php");
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM cities";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
db_connect.php the log in details
<?php
$host = "xxxxx"; //Your database host server
$db = "xxxxx"; //Your database name
$user = "xxxxx"; //Your database user
$pass = "xxxxx"; //Your password
$connection = mysql_connect($host, $user, $pass);
?>
jason_pasted.php this is exactly the same as jason.php but the contents of db_connect.php are just pasted in - produces exactly the same result in browser, and also works when used in my app.
<?php
$host = "xxxxx"; //Your database host server
$db = "xxxxxx"; //Your database name
$user = "xxxxx"; //Your database user
$pass = "xxxxxx"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM cities";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
ViewController.m extract from the app code
-(void) retrieveData
{
NSURL *url = [NSURL URLWithString:jsonURL];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up cities array
citiesArray = [[NSMutableArray alloc]init];
for (int i=0;i<[json count]; i++)
{
//create city object
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"cityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"cityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"country"];
City *myCity = [[City alloc] initWithCityID:cID
andCityName:cName
andCityState:cState
andCityPopulation:cPopulation
andCityCountry:cCountry];
//add city oject to city array
[citiesArray addObject:myCity];
}
[davesTableView reloadData];
}
TL;DR the app works perfectly with jason_pasted.php but not jason.php.
jason.php and jason_pasted.php return exactly the same JSON script when opened in a browser.
String returned from jason.php and jason_pasted.php
(
{
cityName = London;
cityPopulation = 8173194;
cityState = London;
country = "United Kingdom";
id = 1;
},
{
cityName = Bombay;
cityPopulation = 12478447;
cityState = Maharashtra;
country = India;
id = 2;
},
{
cityName = "Kuala Lumpur";
cityPopulation = 1627172;
cityState = "Federal Territory";
country = Malaysia;
id = 3;
},
{
cityName = "New York";
cityPopulation = 8336697;
cityState = "New York";
country = "United States";
id = 4;
},
{
cityName = Berlin;
cityPopulation = 3538652;
cityState = Berlin;
country = Deutschland;
id = 5;
}
)
error returned only when NSUrl points to jason.php
2014-02-13 11:43:34.760 JSONios[4655:60b] JSON error: Error Domain=NSCocoaErrorDomain Code=3840
"The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or
object and option to allow fragments not set.)
UserInfo=0x14659c40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
This is placed in an answer for formatting:
Do not ignore errors!
Incorrect:
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Note: The docs do not specify that nil may be passed for the error parameter.
Correct:
// There is an assumption that the JSON head is a dictionary.
NSError *error;
NSDictionary *jsonAsDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonAsDict == nil) {
NSLog(#"JSON error: %#", error);
}
else { // For debug only
NSLog(#"JSON: %#", jsonAsDict);
}
Now, what happens with this code?
Also please provide the JSON string if possible.
Oh, I personally to not care how the php creates the JSON, all I need to see is the JSON.
Still having trouble: NSLog the data as a string:
NSLog(#"data: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
If no data add the error parameter to
dataWithContentsOfURL:options:error:
in place of dataWithContentsOfURL:
Just doing a normal HTTP post with a NSMutableURLRequest and sendAsynchronousRequest. But the NSHTTPURLResponse object I pass in has a statusCode of zero after the call. I get this error:
sendAsynchronousRequest error = Error Domain=NSURLErrorDomain
Code=-1005 "The network connection was lost." UserInfo=0xb374a00
{NSErrorFailingURLStringKey=http://54.221.224.251,
NSErrorFailingURLKey=http://54.221.224.251, NSLocalizedDescription=The
network connection was lost., NSUnderlyingError=0xb587990 "The network
connection was lost."} 2013-09-04 16:46:19.146 panic[2032:5907]
statusCode: 0
but no status code. Why? The status code the server is sending is 150.
When I POST different data to the server, and don't ask it to return a statusCode, the connection goes smoothly and as expected.
App Code:
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
NSLog(#"sendAsynchronousRequest error = %#", error);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:#"%d",code];
NSLog(#"%#",coder);
if (data) {
NSLog(#"This is Data: %#",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:#"%d",code];
NSLog(#"%#",coder);
}
}];
PHP Code:
index.php
<?php
require_once 'includes/main.php';
class dumb {
function dumber(){
/*--------------------------------------------------
Handle visits with a login token. If it is
valid, log the person in.
---------------------------------------------------*/
if(isset($_GET['tkn'])){
// Is this a valid login token?
$user = User::findByToken($_GET['tkn']);
if($user){
// Yes! Login the user and redirect to the protected page.
$user->login();
redirect('panic://success');
}
// Invalid token. Redirect back to the login form.
redirect('panic://fail');
}
/*--------------------------------------------------
Handle logging out of the system. The logout
link in protected.php leads here.
---------------------------------------------------*/
if(isset($_GET['logout'])){
$user = new User();
if($user->loggedIn()){
$user->logout();
}
redirect('index.php');
}
/*--------------------------------------------------
Don't show the login page to already
logged-in users.
---------------------------------------------------*/
$user = new User();
if($user->loggedIn()){
redirect('protected.php');
}
/*--------------------------------------------------
Handle submitting the login form via AJAX
---------------------------------------------------*/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = $_POST["name"];
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
$subject = "Thank You for Registering!";
$message = "Thank you for registering at our site!\n\n";
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
else{
sendResponse(150, 'Account already created.');
return false;
}
}
else if(isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = '';
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
sendResponse(155, 'Account not yet created.');
return false;
}
else{
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
}
/*--------------------------------------------------
Output the login form
---------------------------------------------------*/
}
}
$api = new dumb;
$api->dumber();
?>
sendResponse function
function sendResponse($status, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . 'ERROR';
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
1xx status codes are special (see http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-23.html#status.1xx); also, it's not a good idea just to make up new status codes.