Receive POST in Swift using PHP - php

Good morning,
I'm trying to send a variable (id_post) through a PHP file using Swift and the .php file it's called, but ¨id_post¨ is empty, because when I print the value of ¨id_post¨ it's always empty.
Do you know why is this happening? I have used the same function in another project from 1 month ago and there is working and here isn't. Am I missing something?
Also I have tested the ¨postString¨ value and it's always correct (id_post=64).
Here is my Swift code:
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.website.com/post.php")!)
request.HTTPMethod = "POST"
let postString = "id_post="+id_post
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print("post: \(responseString)")
self.posts = self.parseJsonData(data!)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
task.resume()
}
Here is my PHP code:
$dbhost="localhost";
$dbusuario="dbuser";
$dbpassword="dbpassword";
$db="db";
$conexion = mysql_connect($dbhost, $dbusuario, $dbpassword);
mysql_select_db($db, $conexion);
mysql_query("SET NAMES 'utf8'");
$id_post=$_POST['id_post'];
$return_arr = array();
$fetch = mysql_query("SELECT * FROM posts WHERE id=$id_post");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC))
{
$row_array['id'] = $row['id'];
$row_array['image'] = $row['image'];
array_push($return_arr,$row_array);
}
echo '{"post": '.json_encode($return_arr).'}';
Thanks in advance,
Regards.

The only thing I had to change it was the "http://www.website.com" to "http://website.com". I don't know why it wasn't working that way, but I post the solution if someone has the same weird problem.
Regards,

Related

Xcode 8.3 get data from php and json

I'm trying to make a small program, that send a username to a web data base. and get the name, status, point of the user.
i have fund out how to send the username, and get the json output.
it look like this: {"name":"gert","status":"0","point":"20"}
and this is my php code
<?php
header('Content-type: application/json');
ob_start();
session_start();
mysql_connect("host","username","password");
mysql_select_db("dbname") or die("Unable to select database");
$qrcode = $_POST['username'];
$result = mysql_query("SELECT * FROM qrcode WHERE qrcode = '$qrcode' ");
$pic_name = mysql_fetch_array($result);
$myObj = new \stdClass();
$myObj->name = $pic_name['name'];
$myObj->status = $pic_name['status'];
$myObj->point = $pic_name['point'];
$myJSON = json_encode($myObj);
echo $myJSON;
ob_end_flush();
?>
and this is my swift code
import UIKit
class ViewController: UIViewController {
let url_to_request:String = "http://www.hholm.dk/time_app/gertqrcode.php"
override func viewDidLoad() {
super.viewDidLoad()
download_request()
}
func download_request()
{
let url:URL = URL(string: url_to_request)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "username=200"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.downloadTask(with: request as URLRequest, completionHandler: {
(
location, response, error) in
let urlContents = try! NSString(contentsOf: location!, encoding: String.Encoding.utf8.rawValue)
guard let _:NSString = urlContents else {
print("error")
return
}
print(urlContents)
})
task.resume()
}
}
and now i have to extract the json, (i think its called)
I would like to have the name, status and point, as some ting i can use i the rest of the program.
try it.
If you have any questions let me know, I hope I have helped!
import Foundation
import UIKit
class getJSON: NSObject, URLSessionDataDelegate
{
//properties
var data : NSMutableData = NSMutableData()
func downloadItems(user:String)
{
let url = NSMutableURLRequest(url: NSURL(string: "http://192.168.1.102:8888/test/test.php")! as URL)
url.httpMethod = "POST"
let postString = "a=\(user)"
url.httpBody = postString.data(using: String.Encoding.utf8)
print(url.httpBody = postString.data(using: String.Encoding.utf8))
var session: URLSession!
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url as URLRequest)
task.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
self.data.append(data as Data);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if error != nil
{
print("Not Found", error ??)
}
else
{
print("Ok")
self.parseJSON()
}
}
func parseJSON()
{
var jsonResult: NSArray = NSArray()
do
{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
print("jsonResult.count",jsonResult.count)
}
catch let error as NSError
{
print("jsonResult: ", error)
}
var jsonElement: NSDictionary = NSDictionary()
var contador = 0
for i in (0..<jsonResult.count)
{
jsonElement = jsonResult[i] as! NSDictionary
if let nameUser = jsonElement["name"] as? String,
let pointUser = jsonElement["point"] as? String,
let statusUser = jsonElement["status"] as? String
{
print("Name: ", nameUser)
print("Status: ", statusUser)
print("Point: ", pointUser)
}
}
}
}
Try this in your php, I'm showing you how I made it work for me, it will need to change as you wish, I'm passing this code as an example.
<?php
header('Content-type: application/json');
ob_start();
session_start();
mysql_connect("host","username","password");
mysql_select_db("dbname") or die("Unable to select database");
$qrcode = $_POST['username'];
$query="SELECT name,status,point FROM qrcode WHERE qrcode = '$qrcode'";
$resultset = mysql_query($query, $connection);
$data = array();
while ($row = mysql_fetch_assoc($resultset))
{
$data[] = $row;
}
//echo '<pre>',print_r($data),'</pre>';
echo json_encode($data);
ob_end_flush();
?>
In your viewcontroller:
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
print("Status: ",getStatusUSer)
}
#IBAction func get(_ sender: Any)
{
let userName = "charles"
let getUser = getJSON()
getUser.downloadItems(user:userName)
}
//Your Code...
}

Get Parameters in php file when POST from Swift

I'm trying to get parameters in my php file when I'm posting from SWIFT (login file)
This is my php file :
<?
$json = array();
$json['username'] = $_POST['username'];
$json['password'] = $_POST['password'];
$json['result'] = "false";
$json['id_familia'] = 148;
$json['id_centre'] = 2;
$json['web'] = "www.cec-escolalolivar.cat";
echo json_encode($json);
?>
This is swift code (of course I've tried with different options, sync, not sync, ....)
let url : NSURL = NSURL(string: "http://www.cec-info.cat/app/config.inc.main_families_json.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
let bodyData="data=xgubianas#gmail.com"
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response,data,error) in
print (response as Any)
if let data = data{
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print (json)
}
catch
{
print (error)
}
}
}

POST request in swift posting nothing

I have got a VC of an app that gets all the variables needed and should pass them through a POST request to a php file, where they are stored and sent to a database. The problem comes when the variables are not set in the database (I believe the connection is well done). The php file is working fine with an Android app that does the same (so the variables are well stored using the Android app).
I would be grateful if you could give me some help.
Swift
#IBAction func modPres(_ sender: AnyObject) {
let postDataURL = "https://www.juankarfollador.com/login_app.php"
let url: NSURL = NSURL(string: postDataURL)!
let request: NSMutableURLRequest = NSMutableURLRequest(url:url as URL)
request.httpMethod = "POST"
request.httpBody = user.data(using: String.Encoding.utf8)
request.httpBody = l_origen.data(using: String.Encoding.utf8)
request.httpBody = l_destino.data(using: String.Encoding.utf8)
request.httpBody = num_pal.data(using: String.Encoding.utf8)
request.httpBody = String(precio).data(using: String.Encoding.utf8)
request.httpBody = texto.data(using: String.Encoding.utf8)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response, data, error) in
print(response!)
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
if statusCode==200 {
print("Connection Successful")
} else {
print("Connection Failed (!200)")
}
}
}
}
Php
$precio = $_POST['precio'];
$texto = $_POST['texto'];
$user = $_POST['user'];
$l_origen = $_POST['l_origen'];
$l_destino = $_POST['l_destino'];
$num_pal = $_POST['num_pal'];
$modificar = $_POST['modificar'];
define('HOST','***');
define('USER','***');
define('PASS','***');
define('DB','***');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
mysqli_set_charset( $con, 'utf8');
//Cliente
$sql = "UPDATE users SET precio='$precio', text_cli='$texto', l_origen='$l_origen', l_destino='$l_destino', num_pal='$num_pal' WHERE username='$user' AND text_cli=''";
mysqli_query($con,$sql);
The console prints "Connection Successful", and this is why I think the connection is well done (I am not sure though, as I am pretty new to Swift)
You are overriding the httpBody of your request over and over.
On top of that you are not passing the keys matching the values of your post variables.
You need something along these lines:
let paramString = "precio=\(precio)&texto=\(texto)&user=\(user)&l_origen=\(l_origen)&l_destino=\(l_destino)&num_pal=\(l_destino)&modificar=\(modificar)"
request.httpMethod = "POST"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
In your PHP I don't see a validation, if you don't have it then you should really add it because it interacts with your db.
Not to mention that you are exposed to SQL injections.

Why is this JSON refusing to get a response? And fails on a curl http://.... response.json command

I am having trouble getting this JSON to output correctly. I have been struggling with this for a number of days now.
The initial error I was receiving was:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is the output in the browser I get when using the request:
http://www.quasisquest.uk/KeepScore/getTotalsStats.php?player_id=2
{"Stats":{"totalWins":10,"totalDraws":6,"totalLosses":3,"winPercentage":"52.63%","goalsScored":40,"goalsConceded":30,"goalDifference":10}}
After discussion on here it was mentioned the problem may be php side but I am at a loss to what since even a simple echo json_endcode ("test") and taking out any MySQL interference has not worked.
I have spoke my to hosting company who have said everything is fine server-side.
This is the Swift function:
override func viewDidAppear(_ animated: Bool)
{
//communitiesTableView.reloadData()
let isUserLoggedIn = UserDefaults.bool(UserDefaults.standard)(forKey: "isUserLoggedIn");
if(!isUserLoggedIn)
{
self.performSegue(withIdentifier: "loginView", sender: self);
}
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTotalsStats.php?");
var request = URLRequest(url:myUrl!);
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpMethod = "POST";
let postString = "player_id=\(self.playerId)";
request.httpBody = postString.data(using: String.Encoding.utf8);
print (myUrl!,postString)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? AnyObject
print (json!)
if let arr = json?["Stats"] as? [[String:AnyObject]] {
self.totalWins = arr.flatMap { $0["totalWins"]}
print("here: ", self.totalWins)
}
} catch{
print(error)
}
}
}
task.resume()
}
Below is the php script:
<?php
require ("Conn.php");
require ("MySQLDao.php");
$playerId = htmlentities($_REQUEST["player_id"]);
$returnValue = array();
if(empty($playerId))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
//WINS LOSSES DRAWS AND %
$playerTotalWins = array();
$playerTotalWins = $dao->getTotalWins($playerId);
$playerTotalDraws = array();
$playerTotalDraws = $dao->getTotalDraws($playerId);
$playerTotalLosses = array();
$playerTotalLosses = $dao->getTotalLosses($playerId);
$winPercentage = (($playerTotalWins) / (($playerTotalWins) + ($playerTotalDraws) + ($playerTotalLosses)));
$newWinpercent = sprintf("%.2f%%", $winPercentage* 100);
//GOALS SCORED
$goalsScoredHome = array();
$goalsScoredHome = $dao->getGFHome($playerId);
$goalsScoredAway = array();
$goalsScoredAway = $dao->getGFAway($playerId);
$totalGoalsScored = ($goalsScoredHome + $goalsScoredAway);
//GOALS CONCEDED
$goalsConcededHome = array();
$goalsConcededHome = $dao->getGCHome($playerId);
$goalsConcededAway = array();
$goalsConcededAway = $dao->getGCAway($playerId);
$totalGoalsConceded = ($goalsConcededHome + $goalsConcededAway);
//GOAL DIFFERENCE
$goalDifference = ($totalGoalsScored - $totalGoalsConceded);
//PRINT OUT
header('Content-Type: application/json');
$arr = array('totalWins' => $playerTotalWins, 'totalDraws' => $playerTotalDraws, 'totalLosses' => $playerTotalLosses, 'winPercentage' => $newWinpercent, 'goalsScored'=>$totalGoalsScored, 'goalsConceded'=>$totalGoalsConceded, 'goalDifference' => $goalDifference);
echo json_encode (array('Stats' => $arr));
$dao -> closeConnection();
?>
It has been suggested I run a curl http://... -> response.json but this seems to save a file with 0 bytes.
I am totally at a loss and new to Swift so all help is appreciated.
So the problem was in this line let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTotalsStats.php?"); The ? was kicking it out.
Solved :)

Swift httppost data not inserting to MySQL database

I am trying to send data to php and insert it to mysql database but it doesn't seem to work. I have tried sending data to php just to encode it to json and echo it back to swift and it returns a result so it means that the php file received the data. However inserting the data is not working.
swift2 httppost
func post() {
let myUrl = NSURL(string: "http://localhost:8080/json/json.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"
// Compose a query string
let postString = "firstName=James&lastName=Bond";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
}catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
}
task.resume()
}
json.php
<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$conn = mysqli("localhost", "root", "root", "notify");
$query = mysqli_query($conn, "INSERT INTO user values('', '$firstName',
'$lastName')");
?>
If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:
<?php
// specify that this will return JSON
header('Content-type: application/json');
// open database
$con = mysqli_connect("localhost","user","password","notify");
// Check connection
if (mysqli_connect_errno()) {
echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno()));
exit;
}
// get the parameters
$field1 = mysqli_real_escape_string($con, $_REQUEST["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);
// perform the insert
$sql = "INSERT INTO user (first_name, last_name) VALUES ('{$field1}', '{$field2}')";
if (!mysqli_query($con, $sql)) {
$response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con));
} else {
$response = array("success" => true);
}
echo json_encode($response);
mysqli_close($con);
?>
Notes:
I wouldn't recommend logging in as root.
Make sure you use mysqli_real_escape_string to protect yourself against SQL injection attacks (see point 1).
I don't know if your user table has other fields in it, but if so, you might want to specify the column names in the insert statement. Even if you only have those two columns, it's a good way to "future-proof" your code.
Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the NSJSONSerialization to you.

Categories