android image to base64 string, and send to php - php

im using this code in the android app, to capture image from camera and send to a javascript file to send a php controller for create file and inset some info to mysql.
the process works fine but the result image is to small and really poor quality
if( ACTION_TAKE_PICTURE == requestCode )
{
Bundle extras = intent.getExtras();
Bitmap bitmap;
if( null == extras || null == (bitmap=(Bitmap)extras.get("data")) ) return;
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
byte [] ba = out.toByteArray();
String b64img = Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP);
try { out.close(); } catch(Exception e) {}
wv.loadUrl( String.format("%s%s('%s')", getString(R.string.js_call_prefix), getString(R.string.js_callback_camera), b64img ));
}
the php code is:
public function executeImagen(sfWebRequest $request) {
$id = $request->getParameter('id');
$img = $request->getParameter('img');
$category = $request->getParameter('category');
$user = $this->getUser()->getAttribute('id_users');
try {
$basepdir = $path = sfConfig::get("sf_upload_dir") . '/photos/';
$basename = date('Ymd_His');
$buffer = base64_decode(str_replace(' ', '+', $img));
$pname = sprintf("%s%s.JPG", $basepdir, $basename);
$photo = sprintf("%s.JPG", $basename);
$fd = fopen($pname, "wb");
if ($fd) {
fwrite($fd, $buffer);
fflush($fd);
fclose($fd);
}
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
try {
$tabla = Doctrine::getTable('StorePhotos');
$tabla = new StorePhotos();
$tabla->id_store = $id;
$tabla->id_category = $category;
$tabla->id_users = $user;
$tabla->imagen = $photo;
$tabla->photo_date = date('Y-m-d H:i:s');
$tabla->save();
} catch (Exception $e) {
trigger_error("ERROR: ", $e->getMessage());
}
return sfView::NONE;
}
thanks.

You are getting and sending the thumbnail. You need to retrieve the full-size image from disk instead. Read this guide by Google.

Related

Retrofit 2 Working In Postman and Localhost but Not On Amazon AWS Live Server

My retrofit instance is working fine with localhost (both android code and postman), and working fine online with postman. But when I go to Amazon AWS instance (a.k.a online) the android part is not working. Please see my code below. The error log from android is D/response: {"error":true,"message":"Required parameters are not available"}
Interestingly the problem is with large file sizes 2M, small file sizes 24KB are getting uploaded fine. I have already checked the php.ini file the max sizes there are 25MB
I am following this tutorial : https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
public interface Api {
//the base URL for our API
//make sure you are not using localhost
//find the ip usinc ipconfig command
String BASE_URL = "http://creative-thinker.com/files/images/secret_crushes/";
//this is our multipart request
//we have two parameters on is name and other one is description
#Multipart
#POST("Api.php?apicall=upload")
Call<MyResponse> uploadImage(#Part("image\"; filename=\"myfile.jpg\" ")
RequestBody file, #Part("desc") RequestBody desc);
}
My Object Class
public class MyResponse {
public boolean error;
String message;
}
My Fragment
ivImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Open The File Choose And Send To Activity For Result
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && data != null) {
//the image URI
Uri selectedImage = data.getData();
//calling the upload file method after choosing the file
uploadFile(selectedImage, "My Image");
}
}
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getContext().getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
MyResponse res= response.body();
Log.d("response", new Gson().toJson(res));
Toast.makeText(getContext().getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getContext().getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
/*
* This method is fetching the absolute path of the image file
* if you want to upload other kind of files like .pdf, .docx
* you need to make changes on this method only
* Rest part will be the same
* */
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
FileHandler.php
<?php
class FileHandler
{
private $con;
public function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function saveFile($file, $extension, $desc)
{
$name = round(microtime(true) * 1000) . '.' . $extension;
$filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
move_uploaded_file($file, $filedest);
$url = $server_ip = gethostbyname(gethostname());
$stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)");
$stmt->bind_param("ss", $desc, $name);
if ($stmt->execute()) {
return true;
}
return false;
}
public function getAllFiles()
{
$stmt = $this->con->prepare("SELECT id, description, image FROM images ORDER BY id DESC");
$stmt->execute();
$stmt->bind_result($id, $desc, $url);
$images = array();
while ($stmt->fetch()) {
$temp = array();
$absurl = 'http://' . gethostbyname(gethostname()) . '/files/images/secret_crushes' . UPLOAD_PATH . $url;
$temp['id'] = $id;
$temp['desc'] = $desc;
$temp['url'] = $absurl;
array_push($images, $temp);
}
return $images;
}
}
Api.php
<?php
require_once dirname(__FILE__) . '/FileHandler.php';
$response = array();
if (isset($_GET['apicall'])) {
switch ($_GET['apicall']) {
case 'upload':
if (isset($_POST['desc']) && strlen($_POST['desc']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$upload = new FileHandler();
$file = $_FILES['image']['tmp_name'];
$desc = $_POST['desc'];
if ($upload->saveFile($file, getFileExtension($_FILES['image']['name']), $desc)) {
$response['error'] = false;
$response['message'] = 'File Uploaded Successfullly';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
break;
case 'getallimages':
$upload = new FileHandler();
$response['error'] = false;
$response['images'] = $upload->getAllFiles();
break;
}
}
echo json_encode($response);
function getFileExtension($file)
{
$path_parts = pathinfo($file);
return $path_parts['extension'];
}
I am trying to catch the values of items in Api.php using
$response['message'] = $string; just where $response['message'] = 'Required parameters are not available';
and getting the following results
$string = $_POST['desc'];
D/response: {"error":true,"message":"My Image"}
$string = $_POST['desc'];
$string = strlen($string);
D/response: {"error":true,"message":"8"}
$string = $_FILES['image']['error'];
D/response: {"error":true}
$string = UPLOAD_ERR_OK;
D/response: {"error":true,"message":"0"}
And removing && $_FILES['image']['error'] === UPLOAD_ERR_OK enters the data into database but no image still uploaded
Finally found the solution after searching the net... The issue was file size
I am on php 7 and Apache. So the configuration needs to changed at two places
The configuration
upload_max_filesize = 25M
post_max_size = 25M
max_execution_time = 300
max_input_time = 300
memory_limit = 128M
The locations
sudo nano /etc/php/7.0/fpm/php.ini
sudo nano /etc/php/7.0/apache2/php.ini
Apparently the settings needs to be changed for PHP AND Apache on Amazon AWS. Hope it helps others.

Failed to upload picked image from gallery to php server

I'm using PHP for a project that needs to be able to upload images from a gallery. For now I'm trying this:
I'm trying to pick image from gallery using httpClient and upload it to php serve. What works from is - pick image, convert mediafile to base64, but when it comes to php it recieves image file but doesn't add it to folder and always returns failed upload.
Where am I mistaken?
Here is my code:
private async void browse_image(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
var file = await CrossMedia.Current.PickPhotoAsync();
MF = file;
if (file == null)
return;
string[] stringSeparators = new string[] { "." };
var result = file.Path.Split(stringSeparators, StringSplitOptions.None);
img_path.Text = u.Username + code.Text + "." + result[1];
var stream = file.GetStream();
profile.Source = ImageSource.FromStream(() =>
{
return stream;
});
}
public bool convert_image_to64(){
var stream = MF.GetStream();
byte[] filebytearray = new byte[stream.Length];
stream.Read(filebytearray, 0, (int)stream.Length);
base64 = Convert.ToBase64String(filebytearray);
if(String.IsNullOrEmpty(base64)){
return false;
}
return true;
}
async Task upload_profile_page()
{
try
{
string result = "";
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("image", base64));
postData.Add(new KeyValuePair<string, string>("filename", img_path.Text));
var stringPayload = JsonConvert.SerializeObject(postData);
var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
await DisplayAlert("", content.ToString(), "ok");
HttpClient client = new HttpClient();
var response = await client.PostAsync("http://example.com/upload_app.php", content);
var FinalJSonResult =. (JArray)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
if (FinalJSonResult.Count > 0)
{
var j = (JObject)FinalJSonResult[0];
result = j.GetValue("result").ToString();
if (result.Equals("0"))
{
await DisplayAlert("0 ->", "failed to upload", "ok");
}
else if (result.Equals("1"))
{
await DisplayAlert("1 ->", "uploaded image successffully", "ok");
}
else
{
await DisplayAlert("1 ->", result, "ok");
}
}
else
{
await DisplayAlert("Error", "Empty result" + "\n" + "size of returned array:- " + FinalJSonResult.Count.ToString(), "Ok");
}
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.ToString(), "Ok");
return;
}
}
<?php // read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$base = $data_back->{"image"};
$filename = $data_back->{"filename"};
$binary=base64_decode($base);
$result1 = array();
header("Content-type: application/json");
try{ // Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$result1 = array();
// Images will be saved under '.../uplodedimages' folder
$file = fopen('.../uplodedimages/'.$filename, 'wb');
// Create File
if(fwrite($file, $binary)==false){
array_push($result1,array( 'result'=>"0"));
}else{
$result1 = array();
array_push($result1,array( 'result'=>"1"));
}
fclose($file);
}catch(Exception $e) {
array_push($result1,array( 'result'=>$e));
}
echo json_encode($result1,JSON_UNESCAPED_UNICODE);
?>

Uploading SVG Laravel 5.5

How do I properly upload a svg file with Laravel 5.5?
The standard image validation rule does not see it as a proper image (image|mimes:jpeg,png,jpg,gif,svg)
When I remove all validation, the file get's stored as a txt file.
My upload code:
$request->file('image')->store('images', 'public');
This Will Work
Use Like This Will Work
if ($request->hasFile('file')) {
$file = $request->file('file');
$file->move($file, 'uploads/audio');
}
from a svg string creating a file, I didn't succeed with string sending as it abuses about some wrong chars after it been transmited to Laravel. So far from Android by okhttp:
private static final MediaType MEDIA_TYPE_TXT =MediaType.parse("text/plain");
....
MultipartBody.Builder obj_ = new MultipartBody.Builder().setType(MultipartBody.FORM);
fileImzo_ = new File(fileSafar_.getAbsoluteFile().getParentFile().getAbsolutePath(),"imzo.txt");
String nomiImzo_ = fileImzo_.getName();
//svgImzo is a raw SVG xml string
InputStream stream_ = new ByteArrayInputStream(svgImzo.getBytes(StandardCharsets.UTF_8));
try {
try (OutputStream output_ = new FileOutputStream(fileImzo_)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = stream_.read(buffer)) != -1) {
output_.write(buffer, 0, read);
}
output_.flush();
}
}catch(Exception e){
e.printStackTrace();
} finally {
try {
stream_.close();
} catch (IOException e) {
e.printStackTrace();
}
}
obj_.addFormDataPart("fileImzo", nomiImzo_, RequestBody.create(fileImzo_, MEDIA_TYPE_TXT));
}
RequestBody req = obj_
.addFormDataPart("copayDodmi", "" + copayDodmi)
.addFormDataPart("izoh", xavar.getText().toString())
.addFormDataPart("driver_id", "" + driverId_)
.build();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + token)//Authorization
.url(MehmonxonaActivity.URLI_ASSOSI + "/supurdani_paket_dodashud")
.post(req)
.build();
....
in Laravel controller , say we add the file path to array to update a row in the table:
....
if ($request->hasFile('fileImzo')) {
$imzo_filename = $this->sozuNomiFaylate('fileImzo', $request);
if (!is_null($imzo_filename)) {
$arr['signature_svg'] = $imzo_filename;
}
}
....
and the function sozuNomiFaylate():
....
private function sozuNomiFaylate(string $alias, \Illuminate\Http\Request $request)
{
$separatorLcl = DIRECTORY_SEPARATOR;
$image = $request->file($alias);
$ext=$image->getClientOriginalExtension();
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext==='')
$ext='svg';
$filename = time() . '.' .$ext ;
$path = public_path('images' . $separatorLcl . 'uploads' . $separatorLcl . $filename);
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext===''){
File::put($path,$image->get());//Illuminate\Support\Facades\File
}else
try {
l::k($path);
Image::make($image)->save($path);
} catch (\Exception $e) {
l::k($e->getMessage());
l::k($e->getTraceAsString());
l::k('fayl soxta na shud');
return null;
}
return $filename;
}
....
And you are done

PHP can not find files in windows

I have build a server use PHP based on WAMP Server on my windows 10 computer. what I want to do is when I send a GET request, the show_files.php should return a JSON object to me. The JSON object contains file names in path F:\NetEaseMusic\download on my computer. Then I use a file name to send a POST request to download_file.php and it returns a data stream so that I can download file. When I use HttpURLConnection, everything works well. However, when I try send the POST request use socket, download_file.php can get the file_name param, but it can not find the target file in F:\NetEaseMusic\download. I show the code.
this is
this is download_file.php
<?php
if(empty($_POST["file_name"]))
{
echo "NO_FILE_NAME\n";
print_r($_POST);
exit();
}
$path = iconv("utf-8", "GB2312","F:\\NetEaseMusic\\download\\".$_POST["file_name"]);
//$path = "F:\\NetEaseMusic\\download\\".$_POST["file_name"];
if (!file_exists ( $path )) {
echo "FILE_NOT_FOUND\n";
echo "F:\\NetEaseMusic\\download\\".$_POST["file_name"]."\n";
print($path);
exit ();
}
$file_size = filesize($path);
//header("Content-type: application/octet-stream");
//header("Accept-Ranges: bytes");
//header("Accept-Length:".$file_size);
//header("Content-Disposition: attachment; filename=".$path);
$file = fopen($path, "r");
while(!feof($file))
{
echo fread($file, 1024);
}
exit();
?>
this is my Client code which to download file. First of all I build a HTTP POST request,
private void downloadFileBySocket(String urlString, String fileName)
{
try{
StringBuilder sb = new StringBuilder();
String data = URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n";
//String data = "&file_name="+fileName;
sb.append("POST " + urlString + " HTTP/1.1\r\n");
sb.append("Host: 10.206.68.242\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
sb.append("Content-Length: " + data.length() + "\r\n");
sb.append("\r\n");
sb.append(data + "\r\n");
//sb.append( URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n");
System.out.println(sb.toString());
URL url = new URL(urlString);
Socket socket = new Socket(url.getHost(), url.getPort());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
writer.write(sb.toString());
writer.flush();
File file = new File("./" + fileName);
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new FileOutputStream(file));
in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[1024];
int readBytes = 0;
while((readBytes = in.read(buffer)) != -1)
{
out.write(buffer, 0, readBytes);
}
out.flush();
}catch (Exception e1)
{
e1.printStackTrace();
}finally {
try{
if(in != null)
{
in.close();
}
if(out != null)
{
out.close();
}
}catch (Exception e2)
{
e2.printStackTrace();
}
}
socket.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
and my main[] method
public static void main(String[] args)
{
SocketTest socketTest = new SocketTest();
socketTest.downloadFileBySocket(SocketTest.downloadFileUrl, "小胡仙儿 - 【二胡】霜雪千年.mp3");
}
Simple way:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("example.com/myfile.txt", #"c:/myfile.txt");

Uploading picture from xamarin form to a php server

Please I have been trying to upload pictures from a xamarin form application to a php server but seems not to be working. The server receives an empty $_FILES request. This is the c# code.
public async Task<bool> Upload(MediaFile mediaFile, string filename)
{
byte[] bitmapData;
var stream = new MemoryStream();
mediaFile.GetStream().CopyTo(stream);
bitmapData = stream.ToArray();
var fileContent = new ByteArrayContent(bitmapData);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileUpload",
FileName = filename
};
string boundary = "---8393774hhy37373773";
MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
multipartContent.Add(fileContent);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return true;
}
return false;
}
Below is the php file to receive the uploaded image. I tried to save the content of the posted image to file but the file only has an empty array and always return "failure". Please what am i missing wrong? I have searched the web but cant seem to understand the problem.
$uploads_dir = 'uploads/';
$req_dump = print_r( $_FILES, true );
$fp = file_put_contents( 'data.txt', $req_dump );
if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))
{
$tmp_name = $_FILES["fileUpload"]["tmp_name"];
$name = $_FILES["fileUpload"]["name"];
$Result = move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Success";
}
else
{
echo "Failure";
}
The AND operator is really not a good choice for you. (On line 4).
Sometimes it shows some really unexpected behaviour. (I can refer you to 'AND' vs '&&' as operator for more info).
If you want a logical AND use the && operator instead.
The line would be
if (isset($_FILES["fileUpload"]["tmp_name"]) && is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))
I know this is an old post but this is how I upload an image from Xamarin Forms to PHP
http://gjhdigital.com/xamarin/xamarin-forms-upload-image-to-php/
Xamarin c# code
using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace UploadPicToServer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btnUpload_Clicked(object sender, EventArgs e)
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
if (file == null)
return;
string fileName = file.Path;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
//UploadImage1(file.AlbumPath);
UploadImage(file.GetStream(), fileName);
}
private async void UploadImage(Stream mfile, string fileName)
{
int authorID = 2;
string username = "yourusername";
var url = "https://yourwebsite.com/ba-add-profile-pic.php";
url += "?id="+ authorID +"&username="+ username; //any parameters you want to send to the php page.
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://yourwebsite.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
//HttpContent content = new StringContent("fileToUpload");
//form.Add(content, "fileToUpload");
var stream = mfile;
StreamContent content = new StreamContent(stream);
//get file's ext
string fileExt = fileName.Substring(fileName.Length - 4);
string fName = "User-Name-Here-123" + fileExt.ToLower();
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = fName
};
form.Add(content);
var response = await client.PostAsync(url, form);
var result = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
//debug
Debug.WriteLine("Exception Caught: " + e.ToString());
return;
}
}
public static byte[] ToArray(Stream s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (!s.CanRead)
throw new ArgumentException("Stream cannot be read");
MemoryStream ms = s as MemoryStream;
if (ms != null)
return ms.ToArray();
long pos = s.CanSeek ? s.Position : 0L;
if (pos != 0L)
s.Seek(0, SeekOrigin.Begin);
byte[] result = new byte[s.Length];
s.Read(result, 0, result.Length);
if (s.CanSeek)
s.Seek(pos, SeekOrigin.Begin);
return result;
}
}
}
PHP code
//parameters send in via querystring
if (!isset($_REQUEST['author']) || !isset($_REQUEST['username']) ) {
die('{"status" : "Bad", "reason" : "Invalid Access"}');
}
$userID = $_REQUEST['author'];
$isGood = false;
try{
$uploaddir = '../someFolderToStoreTheImage/';
$fileName = basename($_FILES['fileToUpload']['name']);
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
//CHECK IF ITS AN IMAGE OR NOT
$allowed_types = array ('image/jpeg', 'image/png', 'image/bmp', 'image/gif' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['fileToUpload']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( '{"status" : "Bad", "reason" : "Not a valid image"}' );
}
//
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
//echo "File is valid, and was successfully uploaded.\n";
echo '{"status" : "Success", "reason" "'. $fileName .'"}';
$isGood = true;
} else {
//echo "Possible file upload attack!\n";
echo '{"status" : "Bad", "reason" : "Unable to Upload Profile Image"}';
}
}
catch(Exception $e) {
echo '{"status" : "Bad", "reason" : "'.$e->getMessage().'"}';
}

Categories