swift 2 character "&" cannot upload in http POST Request - php

I am trying to send some string to mysql through PHP which the string include some special characters, such as "&,?,/".
The problem is all the string which after the character "&" will be missed.
for example, the string "Ak-47&Bomber" will be send in "Ak-47".
Swift:
let url: NSURL = NSURL(string: "MyPhP.php")!
let session = NSURLSession.sharedSession()
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodydata = "String=\(Ak-47&Bomber)"
request.HTTPBody = bodydata.dataUsingEncoding(NSUTF8StringEncoding)
if bodydata != " " {
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
PHP :
$String= ($_POST["String"]); // the String i got "Ak-47"
$sql = "INSERT INTO table (string) VALUES ('" .
$String."' )";
$result = mysqli_query($conn, $sql);
any solution?

Related

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.

swift 3 with Mysql

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

Return json value with php from swift iOS

Hello I have a small a problem with the code below, Xcode print this error:
ERROR: json error: Error Domain=NSCocoaErrorDomain Code=3840 "No
value." UserInfo={NSDebugDescription=No value.}
SWIFT CODE:
let yourUrl=“mylink.php”
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL!)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
let dataString = "Email=\(Email.text)&Password=\(Password.text)"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()
PHP CODE:
mylink.php
<?php
header("Content-Type: application/json");
$email = $_POST["Email"];
$password = $_POST["Password"];
$stat=“myvalue”;
return json_encode($stat);
?>
How can I solve this error?

Request on php script with nsurlconnection

i try to send value to server with this code by i have an error on this line:
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
the error is : EXTRA ARGUMENT IN CALL "error"
var yourUrl="mylink"
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "
V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "my value"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
if let dataFromString = results!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
if(json=="0"){
print("\n Dati non validi");
}
else{
print("\n Account creato");
}
}
You should never use sendSynchronousRequest as it is a blocking call. Also it is deprecated from iOS 9.0 onwards. Instead you can use NSURLSession. Try out following code
var yourUrl="mylink"
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = "my value"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()

How to send a image to a php file using Swift

For my app i need to send a image to a php file.
I already know how to send strings using this:
var bodyData = "info=test"
let URL: NSURL = NSURL(string: "LINK TO A PHP FILE")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
And in my php file:
$info = $_POST['info'];
echo $info;
But i don't know how to send a image
var imageData :NSData = UIImageJPEGRepresentation(imagenReduced, 1.0);
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
let tempData = NSMutableData()
let fileName = filenames + ".jpg" //"prueba.jpg"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)
var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")
//check this code
func callToProfileUpdate()
{
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "Loading"
var userID: AnyObject! = NSUserDefaults.standardUserDefaults().valueForKey("USER_ID")
var urlString = NSString(string:"\(baseurl)action=update_profile&user_id=\(userID)&user_name=\(userName.text)&account_type=\(self.selectedAccountTypeLabel.text!)&show_comments=\(commentStauts)&tag_permission=\(tagPermission)")
urlString = urlString .stringByReplacingOccurrencesOfString(" ", withString: "%20")
var url = NSURL(string:urlString as String)
let urlRequest = NSMutableURLRequest(URL: url!)
if mediaData != nil
{
urlRequest.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
urlRequest.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"photo\"; filename=\".png\"\\.png\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(mediaData)
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
urlRequest.HTTPBody = body
}

Categories