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)
}
}
}
Related
I would like to implement an IOS app via swift 5 to adjust a MySQL database triggered by a PHP script. I try to use the post request to handover the following parameters:
teamName = "Testteam"
teamCount = "member"
After some testing I found out, that parameters are not handover to PHP script (they are empty) and I don't know why.
Swift Code
let URL_SAVE_TEAM ="http://www.mydomain.de/createteam.php"
#IBOutlet weak var textFieldName: UITextField!
#IBOutlet weak var textFieldMember: UITextField!
#IBAction func Login(_ sender: UIButton) {
//created NSURL
let requestURL = NSURL(string: URL_SAVE_TEAM)!
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL as URL)
//setting the method to post
request.httpMethod = "POST"
//getting values from text fields
let teamName = textFieldName.text
let memberCount = textFieldMember.text
//creating the post parameter by concatenating the keys and values from text field
//let postParameters = "name="+teamName!+"&member="+memberCount!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) in
if error != nil {
print("error is \(String(describing: error))")
return
}
do { //parsing the response
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary //converting resonse to NSDictionary
print(myJSON)
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print(msg!)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
}
PHP script on server
<?php
//creating response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_GET['name'];
$memberCount = $_GET['member'];
$fp = fopen ('debug.log' , "w"); // Datei öffnen
fwrite ($fp , 'test'); // Dateiinhalt in die Datei schreiben
fwrite ($fp , $teamName); // Dateiinhalt in die Datei schreiben
fwrite ($fp , $memberCount); // Dateiinhalt in die Datei schreiben
fclose ($fp); // Datei schließen
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
?>
The PHP script is sending the error message (Could not add team) because the variable $teamName and $memberCount are empty. The overall connection to the PHP script seems to work.
You are using POST method, so you should get POST values not GET values:
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
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...
}
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.
I am trying to make registration in swift3 with mysql
but there is some thing wrong ,
when I run my app and make register return msg "some fields are empty"
In php code:
$fullname = htmlentities($_REQUEST["fullname"]);
$username = htmlentities($_REQUEST["username"]);
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$phone = htmlentities($_REQUEST["phone"])
swift code:
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://localhost/php/register.php?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "fullname=\(FirstName.text)%20\(LastName.text)&username=\(UserName.text)&email=\(Email.text)&password=\(Password.text)&phone=\(Phone.text)"
request.httpBody = body.data(using: String.Encoding.utf8)
let task = session.dataTask(with: url!) {data, response, error in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print(json)
}
} catch {
print("error in JSONSerialization")
}
}
}
task.resume()
I think you missed this
let task = session.dataTask(with: request) {data, response, error in
replace url with request
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 :)