I Have Problem ,
when i want to do the update method using slim framework.
my data can not be updated .
below is my code PHP :
$app->put('/eta1/{id}', function($request, $response, $args) use($app, $db){
$matkul = $request->getParams();
$eta1 = filter_var($matkul['eta1'], FILTER_SANITIZE_STRING);
$eta2 = filter_var($matkul['eta2'], FILTER_SANITIZE_STRING);
$query = $db->prepare('UPDATE tbl_matkul SET eta1=$eta1, eta2=$eta2 WHERE id = :id');
$query->bindParam('id', $args['id']);
$result = $query->execute();
$responseJson["error"] = false;
$responseJson["message"] = "Berhasil menambahkan ke database";
echo json_encode($responseJson);
});
Iam using retrofit in android client
Try this:
$app->put('/eta1/{id}', function($request, $response, $args) use($app, $db){
$matkul = $request->getParams();
$row = [
'id' => (int)$args['id'],
'eta1' => $matkul['eta1'],
'eta2' => $matkul['eta2'],
];
$sql = "UPDATE tbl_matkul SET eta1=:eta1, eta2=:eta2 WHERE id=:id;";
$status = $db->prepare($sql)->execute($row);
$responseJson = [];
if ($status) {
$responseJson["error"] = false;
$responseJson["message"] = "Berhasil menambahkan ke database";
} else {
$responseJson["error"] = true;
$responseJson["message"] = "Database operation failed";
}
return $response->withJson($responseJson);
});
Related
I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all
so I want to upload an image using retrofit to my Slim framework API. Right now I can upload the images successfully using a seperate .php file in my other project that receives the images through the $_FILES object here is it
<?php
ini_set('display_errors',1);
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');
ini_set('max_input_time', 30000);
ini_set('max_execution_time', 30000);
require_once '../include/Functions.php';
$db = new Functions();
$result['error'] = true;
$result['message'] = 'Error occurred, try again1';
$userfk = $_POST['userid'];
$fileNames = array();
for($i = 0; $i < count ( $_FILES ['file'] ['name'] ); $i ++) {
try {
$extension = pathinfo($_FILES ['file'] ["name"][$i], PATHINFO_EXTENSION);
array_push($fileNames,microtime_float().'_'.rand(1, 99999999).'.'.$extension);
if (move_uploaded_file( $_FILES ['file'] ["tmp_name"][$i], "../images/iduploads/".$fileNames[$i])) {
$result['error'] = false;
$result['message'] = 'Upload success';
} else {
$result['error'] = true;
$result['message'] = 'Something went wrong, try again';
throw new Exception('Could not move file');
}
} catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error, photos did not upload, try again';
}
}
if(count ( $_FILES ['file'] ['name']) > 0 && !empty($fileNames))
$db->uploadIdentificationDocs($userfk, $fileNames[0], $fileNames[1], $fileNames[2]);
echo json_encode($result);
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
And from my Android side I use
#POST("idUpload.php")
Call<Result> uploadMultiFile(#Body RequestBody file);
And
APIService service = retrofit.create(APIService.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
User user = SharedPreferencesUtils.getUserPreferences(this);
builder.addFormDataPart("userid", user.getUserId());
builder.addFormDataPart("file[]", profilePicture.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), profilePicture));
MultipartBody requestBody = builder.build();
ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, this);
Call<Result> call = service.uploadMultiFilee(progressRequestBody);
This works but I don't like the idea of leaving Slimto upload the image, reason I choose it is because of it's simplicity and clean code. This feels wrong, so I tried uploading using slims' provided functions
$app->post('/uploadprofilepicture/{userid}', function (Request $request, Response $response) {
$db = new Functions();
$userFk = $request->getAttribute('userid');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
But it fails, it just returns error 500, after running postman Call to a member function getError() on null meaning $request->getUploadedFiles() is null
#Zamrony was right, well at least he helped me figure out my issue, in the end here is the working code
use Slim\Http\UploadedFile;
$profilePhotoContainer = $app->getContainer();
$profilePhotoContainer['upload_directory'] = '../images/iduploads/';
$app->post('/uploadprofilepicture', function (Request $request, Response $response) {
$db = new Functions();
$directory = $this->get('upload_directory');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['profilephoto'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
It should be $uploadedFiles not $uploadedFile . That is why you get null.
Edit: $uploadedFile variable is not initialized. That is why you get null. For example if html is defined as follow
<form method="post" enctype="multipart/form-data">
<input type="file" name="myUploadedFile">
</form>
Then in code that handle file upload, it should be
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['myUploadedFile'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
//TODO: move file
}
Read Uploading files using POST forms for more information.
I tried several ways to upload a file on the FTP server, but I failed in that.
Here I am pasting My server code (php)to accept the file from the device, please provide android code corresponding to that server code.
<?php
error_reporting(0);
include("dbconfig.php");
$msg = '';
$status = 1;
$overwrite = 1;
/*echo "<pre>";
print_r($_POST);
echo "</pre>";*/
/*echo "<pre>";
print_r($_FILES);
echo "</pre>";*/
if(trim($_POST['userid'])!='')
{
$userid = trim($_POST['userid']);
$overwrite = trim($_POST['overwrite']);
if($overwrite == 0)
{
$selfilesqry = mysql_query("SELECT filepath FROM userfiles WHERE userid = 1 AND status=1");
while($row = mysql_fetch_array($selfilesqry))
{
$selfiles[] = $row['filepath'];
}
}
/* echo "<pre>";
print_r($selfiles);
echo "</pre>";*/
$host = '97.***.****';
$usr = '*****************8';
$pwd = '**********************';
$paths = '/mobbisys/cloudbin/data';
//$paths = '/php_projects/mahesh/ftpupload/data';
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
for($i=0; $i<count($_FILES['txtfile']['name']); $i++)
{
if($_FILES['txtfile']['name'][$i]!='')
{
$type = explode('/',$_FILES['txtfile']['type'][$i]);
$filetype = $type[0];
if($filetype == 'audio')
{
$path = $paths."/audio";
}
else if($filetype == 'video')
{
$path = $paths."/video";
}
else if($filetype == 'image')
{
$path = $paths."/image";
}
else
{
$path = $paths."/misc";
}
//echo "<br />".$path;
$name = $_FILES['txtfile']['name'][$i];
$filep = $_FILES['txtfile']['tmp_name'][$i];
// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);
$filepath = strtolower($path.'/'.$name);
if($overwrite == 1)
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
else
{
if(in_array($filepath, $selfiles))
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i].' already exist.';
}
else
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
}
}
}
// close the FTP stream
ftp_close($conn_id);
}
else
{
$msg = 'Please provide userid';
}
echo $msg;
?>
You have to include move_uploaded_file function when you want insert
Syntax : move_uploaded_file ( string $filename , string $destination )
Example : move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./upload/".$_FILES["uploadedfile"]["name"]);
http://php.net/manual/en/function.move-uploaded-file.php
this is bad code. why not upload the files from android device via ftp without a server side script?
see here
I try to set a http autentification with android
this is my class
http://pastebin.com/SB9TKtQZ
I use like this
EditText user = (EditText)findViewById(R.id.referent_login_input);
EditText password = (EditText)findViewById(R.id.referent_password_input);
Api login = new Api(getString(R.string.api_url));
login.updateUrl("login");
login.updateHeader(user.getText().toString(), password.getText().toString());
String connect = login.get();
My php is
if( !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']) ) {
echo "no !!!";
}
else {
echo "yes";
}
and I always have no !!!
I set something in my EditText
Thanks
we're programming a little "home device control" app within our studying using Appcelerator Titanium. We programmed a back-end in Java which is connected to our front-end apps with an interface which can receipt requests through a SOAP call. Therefore we used the suds.js. All works fine with iOS but nothing seems to happen in Android and we do not know why. :-(
First of all we want to provide a user-login to authorize the user. Name and password will be send to the back-end which provides a user-token afterwards. In iOS all works fine, Android seems to have a problem with the following code which I noticed through different test comments because the comments within this code are not shown in the developer console:
suds.invoke('login', callparams, function(xmlDoc) {
Titanium.API.info("Test after function is called");
var results = xmlDoc.documentElement.getElementsByTagName('return');
Titanium.API.info("another test comment");
Titanium.API.info(results);
if (results && results.length>0) {
var isAdmin = results.item(0).getElementsByTagName('admin');
if(isAdmin.item(0).text == "true") {
Titanium.API.info("isAdmin: true");
Titanium.App.Properties.setBool('isAdmin', true);
} else {
Titanium.API.info("isAdmin: false");
Titanium.App.Properties.setBool('isAdmin', false);
}
var userToken = results.item(0).getElementsByTagName('userToken');
Titanium.API.info("userToken: " + userToken.item(0).text);
Titanium.App.Properties.setString('userToken', userToken.item(0).text);
Titanium.App.Properties.setString('username', username.value);
//Rein oder raus???
//alert("Login erfolgreich! \n isAdmin: " + isAdmin.item(0).text + " \n userToken: " + userToken.item(0).text)
//Aufruf Hauptmenüfenster
openWindow('js/menue.js', 'Hauptmenü', true);
} else {
var resultsError = xmlDoc.documentElement.getElementsByTagName('S:Fault');
var errorString = resultsError.item(0).getElementsByTagName('faultstring');
Titanium.API.info("error: " + errorString.item(0).text);
alert(errorString.item(0).text);
}
});
The url-link to the back-end: http://localhost:8888 Localhost because the back-end is running on my desktop for testing. I am not sure if the request will be receipt of the back-end at all.
Thanks for help in advance!
Best regards, Stefan
The whole code:
Part of app.js: (sorry for german code comments)
// Checkbox bekommt Eventlistener, der Angibt ob das Passwort gespeichert werden soll.
checkbox.addEventListener('click', function(e) {
if(Titanium.App.Properties.getBool('loginAuto') == true){
imageUrl = 'images/checkbox_unchecked.png';
Titanium.App.Properties.setBool('loginAuto', false);
Titanium.API.info('Setze loginAuto = false');
} else if(Titanium.App.Properties.getBool('loginAuto') == false){
imageUrl = 'images/checkbox_checked.png';
Titanium.App.Properties.setBool('loginAuto', true);
Titanium.API.info('Setze loginAuto = true');
}
checkbox.image = imageUrl;
});
// Loginbutton bekommt Eventlistener, der bei Klick den Login durchführt.
loginBtn.addEventListener('click', function(e) {
// Datenbank wird erneut initialisiert, falls noch nicht vorhanden
var db_userdata = Titanium.Database.install("db/myHome4.sqlite", 'myHome4');
// Für den Fall das Benutzername und Passwort gespeichert werden sollen, werden sie hier in die DB geschrieben.
if(Titanium.App.Properties.getBool('loginAuto') == true){
Titanium.API.info('Speichere Name und Password in der Datenbank.');
db_userdata.execute("DELETE FROM login");
db_userdata.execute("INSERT INTO login (id, name, password) VALUES (1, ?, ?)", username.value, password.value);
Titanium.App.Properties.setString('loginName', username.value);
Titanium.App.Properties.setString('loginPassword', password.value);
} else {
db_userdata.execute("DELETE FROM login");
}
db_userdata.close();
var url = Titanium.App.Properties.getString('url') + '/services?wsdl';
var callparams = {
username: username.value,
password: password.value
};
/* Im Folgenden der suds Client (SOAP Client), der die SOAP Abfragen ausführt und Werte zurück liefert.
Login-Vorgang und Aufruf des Hauptmenüfensters
*/
Titanium.API.info(Titanium.App.Properties.getString('url'));
var suds = new SudsClient({
endpoint: url,
targetNamespace: Titanium.App.Properties.getString('url')
});
Titanium.API.info("TEST1111");
try {
Titanium.API.info("Test before function");
suds.invoke('login', callparams, function(xmlDoc) {
Titanium.API.info("Test after function is called");
var results = xmlDoc.documentElement.getElementsByTagName('return');
Titanium.API.info("another test comment");
Titanium.API.info(results);
if (results && results.length>0) {
var isAdmin = results.item(0).getElementsByTagName('admin');
if(isAdmin.item(0).text == "true") {
Titanium.API.info("isAdmin: true");
Titanium.App.Properties.setBool('isAdmin', true);
} else {
Titanium.API.info("isAdmin: false");
Titanium.App.Properties.setBool('isAdmin', false);
}
var userToken = results.item(0).getElementsByTagName('userToken');
Titanium.API.info("userToken: " + userToken.item(0).text);
Titanium.App.Properties.setString('userToken', userToken.item(0).text);
Titanium.App.Properties.setString('username', username.value);
//Rein oder raus???
//alert("Login erfolgreich! \n isAdmin: " + isAdmin.item(0).text + " \n userToken: " + userToken.item(0).text)
//Aufruf Hauptmenüfenster
openWindow('js/menue.js', 'Hauptmenü', true);
} else {
var resultsError = xmlDoc.documentElement.getElementsByTagName('S:Fault');
var errorString = resultsError.item(0).getElementsByTagName('faultstring');
Titanium.API.info("error: " + errorString.item(0).text);
alert(errorString.item(0).text);
}
});
} catch(e) {
alert(e);
Ti.API.error('Error: ' + e);
}
});
/* Eventlistener für den Logout-Button, bei Klick wird das Menüfenster geschlossen und die Variablen username, userToken und is
isadmin gelöscht
*/
Ti.App.addEventListener('eventLogout', function(event)
{
Titanium.App.Properties.removeProperty("username");
Titanium.App.Properties.removeProperty("userToken");
Titanium.App.Properties.removeProperty("isAdmin");
Titanium.API.info("Lösche Einstellungen...");
win2.close();
});
suds.js:
/*
* Definition der Parameter, die für SOAP Client notwendig sind
*
*/
var url = Titanium.App.Properties.getString('url') + '/services?wsdl';
/**
* Suds: A Lightweight JavaScript SOAP Client
* Copyright: 2009 Kevin Whinnery (http://www.kevinwhinnery.com)
* License: http://www.apache.org/licenses/LICENSE-2.0.html
* Source: http://github.com/kwhinnery/Suds
*/
function SudsClient(_options) {
function isBrowserEnvironment() {
try {
if (window && window.navigator) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
function isAppceleratorTitanium() {
try {
if (Titanium) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
//Funktion zur Erweiterung von Variablen (Objekten)
function extend(original, extended) {
for (var key in (extended || {})) {
if (original.hasOwnProperty(key)) {
original[key] = extended[key];
}
}
return original;
}
//Prüfung ob ein Objekt ein Array ist
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
//Holt per get eine XMLHTTPRequest Object
function getXHR() {
return Titanium.Network.createHTTPClient();
}
//Aus einem String wird ein XML DOM object
function xmlDomFromString(_xml) {
xmlDoc = Titanium.XML.parseString(_xml);
return xmlDoc;
}
// Konvertiert ein Javascript OBbjekt in ein XML string
function convertToXml(_obj, namespacePrefix) {
var xml = '';
if (isArray(_obj)) {
for (var i = 0; i < _obj.length; i++) {
xml += convertToXml(_obj[i], namespacePrefix);
}
} else {
for (var key in _obj) {
if (namespacePrefix && namespacePrefix.length) {
xml += '<' + namespacePrefix + ':' + key + '>';
} else {
xml += '<'+key+'>';
}
if (isArray(_obj[key]) || (typeof _obj[key] == 'object' && _obj[key] != null)) {
xml += convertToXml(_obj[key]);
}
else {
xml += _obj[key];
}
if (namespacePrefix && namespacePrefix.length) {
xml += '</' + namespacePrefix + ':' + key + '>';
} else {
xml += '</'+key+'>';
}
}
}
return xml;
}
// Client Konfiguration
var config = extend({
endpoint:'https://localhost:8888/service',
targetNamespace: 'https://localhost:8888/service?wsdl',
envelopeBegin: '',
envelopeEnd: ''
},_options);
// Aufruf web service
this.invoke = function(_soapAction,_body,_callback) {
//Erstelle request body
var body = _body;
//Erlaubt einen String in einen XML body einzufügen - Ansonsten wird dieser aus einem XML Objekt erzeugt.
if (typeof body !== 'string') {
body = '<fron:'+_soapAction+'>';
body += convertToXml(_body);
body += '</fron:'+_soapAction+'>';
}
var ebegin = config.envelopeBegin;
config.envelopeBegin = ebegin.replace('PLACEHOLDER', config.targetNamespace);
//Erzeugt den Soapaction header
var soapAction = '';
if (config.targetNamespace.lastIndexOf('/') != config.targetNamespace.length - 1) {
soapAction = config.targetNamespace+'/'+_soapAction;
}
else {
soapAction = config.targetNamespace+_soapAction;
}
//Sende das XML document per HTTP_Post zum service endpoint
var xhr = getXHR();
xhr.onload = function() {
_callback.call(this, xmlDomFromString(this.responseText));
};
xhr.open('POST',config.endpoint);
xhr.setRequestHeader('Content-Type', 'text/xml;charset=UTF-8');
// xhr.setRequestHeader('SOAPAction', soapAction);
xhr.send(config.envelopeBegin+body+config.envelopeEnd);
Titanium.API.info(config.envelopeBegin+body+config.envelopeEnd);
Titanium.API.info("Test SUDS!");
};
}
I suppose that localhost will be the mobile (emulator) and not the hosting computer. Try binding the endpoints in Java to the machine name (not localhost) which is available in the network. Then point your SOAP connections to that machine.