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
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
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);
});
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 am working on a mobile android project that uploads images to the server. I am doing it in Flash Builder with the help of the PHP scripts on the server. My web page is hosted by goDaddy and I have done the permissions for uploading files as; I can upload image through web page. However, when I am trying to send from application it does not upload. Any ideas about the problem? My code is as below;
Flash Builder:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
title="Photo Upload">
<fx:Script>
<![CDATA[
private var urlRequest:URLRequest = new URLRequest("http://www.mywebsite.com/upload_file.php");
private var file:File;
//take a new picture with the camera
//select a picture from the camera roll (gallery)
protected function uploadGallery_clickHandler(event:MouseEvent):void
{
if (CameraRoll.supportsBrowseForImage)
{
trace("camera roll is supported");
var roll:CameraRoll = new CameraRoll();
roll.browseForImage();
roll.addEventListener(MediaEvent.SELECT,selectCompleteHandler);
}
else
{
trace("camera roll not supported");
statusText.text = "Camera roll not supported on this device.";
}
}
//when the selection is complete upload it
protected function selectCompleteHandler(event:MediaEvent):void
{
trace("event.data.file.url; = "+event.data.file.url);
file = event.data.file;
file.addEventListener(Event.COMPLETE,uploadCompleteHandler);
file.addEventListener(Event.OPEN,openUploadHandler);
file.upload(urlRequest);
}
protected function uploadCompleteHandler(event:Event):void
{
trace("upload complete");
statusText.text = "Photo Uploaded";
}
protected function openUploadHandler(event:Event):void
{
trace("uploading");
statusText.text = "Uploading...";
}
]]>
</fx:Script>
<s:VGroup x="21" y="23" width="200" height="200">
<s:Label id="statusText" fontSize="24" text="Choose a Photo..."/>
<s:Button id="galleryPhotoButton" label="Upload from Gallery"
click="uploadGallery_clickHandler(event)"/>
</s:VGroup>
</s:View>
PHP script on the server:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Do you get any error or any exception on the execution of above code ?
Also you can try adding the urlRequest method as follows to see if it works :
urlRequest.method = URLRequestMethod.POST;
Hello I'm trying to validate the token I've created with the accountManager from my php server but I keep getting the error "invalid token" from google server on my php server... Here is the code :
private String updateToken(boolean invalidateToken, int accountref) {
String authToken = "null";
try {
AccountManager am = AccountManager.get(TestAuthActivity.this);
Account[] accounts = am.getAccountsByType("com.google");
AccountManagerFuture<Bundle> accountManagerFuture;
if(TestAuthActivity.this == null){//this is used when calling from an interval thread
accountManagerFuture = am.getAuthToken(accounts[accountref], SCOPE, false, null, null);
} else {
accountManagerFuture = am.getAuthToken(accounts[accountref], SCOPE, null, TestAuthActivity.this, null, null);
}
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN).toString();
if(invalidateToken) {
am.invalidateAuthToken("com.google", authToken);
authToken = updateToken(false, accountref);
}
} catch (Exception e) {
e.printStackTrace();
}
Dialog d = new Dialog(TestAuthActivity.this);
d.setTitle("Token :" + authToken);
d.show();
createSession(TestAuthActivity.this, authToken);
return authToken;
}
So I'm getting a token then I'm sending it to my php server :
<?php
if( isset($_POST['authToken'])){
//pour que la réponse s'affiche comme du texte brut
header('Content-Type: text/plain');
/*partie à modifier*/
$name = 'www.google.com';//nom du site
$data = $_POST['authToken'];
$envoi = "POST /m8/feeds/contacts/default/full HTTP/1.1\r\n";
$envoi .= "Host: ".$name."\r\n";
$envoi .= "Authorization: GoogleLogin auth='".$data."'\r\n";
$envoi .= "Connection: Close\r\n";
$envoi .= "Content-type: application/x-www-form-urlencoded\r\n";
$envoi .= "Content-Length: ".strlen($data)."\r\n\r\n";
$envoi .= $data."\r\n";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket < 0){
die('FATAL ERROR: socket_create() : " '.socket_strerror($socket).' "');
}
if (socket_connect($socket,gethostbyname($name),80) < 0){
die('FATAL ERROR: socket_connect()');
}
if(($int = socket_write($socket, $envoi, strlen($envoi))) === false){
die('FATAL ERROR: socket_write() failed, '.$int.' characters written');
}
$reception = '';
while($buff = socket_read($socket, 2000)){
$reception.=$buff;
}
echo(json_encode($reception));
socket_close($socket);
}
?>
and I keep getting the error : 401 invalid token :S
Does anyone have a solution or a good sample (couldn't found one that matches what I want to do !)
I can think of two possible problems you might have:
The auth token has expired. When you call your method updateToken() to get the token you need to set the parameter invalidateToken to true to make sure you get a fresh token.
The value of SCOPE is wrong. Based on the code you've provided it looks like you are trying to use the Google Contacts API, for this API SCOPE should have the value https://www.google.com/m8/feeds