I am trying to upload an image from my android application to a php script on my server. In my script, I am attempting to decode the image (using base64_decode) and then use file_put_contents() to save the image as a file in my directory. My problem is that the file 'appears' empty when I have .jpg at the end of the file name. When I removed that to see what was added for the image encoding, I see a very long string of characters, (65214 bytes specifically that were written to the file). When I run the code again, only this time uploading the $_POST['sent_image'] without decoding, I get the same exact string of text.
I am not sure what I am doing wrong... The end goal would be to save the image on the server, so it could be viewed elsewhere online, and also be able to retrieve it and get back into another activity in my android application.
All suggestions are appreciated!
NOTE: I have also tried imagecreatefromstring(), but that causes 0 bytes to be written.
My Code:PHP that gets encoded android image and tries to save to server directory:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
Thank you!
Using str_replace may be problematic if image format is other than jpg, for example.
Example code:
<?php
$photo = $_POST['newUnitStatusPhoto'];
if(substr($photo, 0,5) !== "data:"){
//do error treatment as it's not datauri
die("Error: no data: scheme");
};
$decodedPhoto = substr($photo, 5);
$mimeTerminator = stripos($decodedPhoto,";");
if($mimeTerminator === false){
die("Error: no mimetype found");
};
$decodedPhoto = substr($decodedPhoto, $mimeTerminator+8); //1<;>+4<base>+2<64>+1<,>
// $decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
// $decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$unitname = "testando";
$fileName = "".$unitname."_rej.jpg";
$target = 'img/';
$newFile = $target.$fileName;
if(file_exists($newFile))
unlink($newFile);
$success = file_put_contents($newFile, $newUnitStatusPhoto);
echo $success;
Related
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name']) ){
//connecting to the database
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');
$resume_name = $_POST['exp'];
$employee_id = $_POST['employee_id'];
$file_data = $_FILES['pdf']['name'];
$upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_path . getFileName($employee_id). '.'. $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName($employee_id);
try{
if(file_exists($upload_path))
{
$existing_file = glob($upload_path."/*.*");
$empty_file = implode(" ",$existing_file);
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
else
{
mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql))
{
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
}
}
//here is my method getFileName
function getFileName($employee_id)
{
//mysql query to fetch data
$sql = mysql_query("SELECT resume_path from employee_registration where
employee_id = '$employee_id'") or die(mysql_error());
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$response=$row['resume_path'];
}
$resume_name = explode("/", $response);
echo $resume_name[4];
return $resume_name;
}
Change below line:
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
To
move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);
I have a form that users can upload files like html, css, php, java, js, txt, javascript and other files which i included
But my problem is how can i prevent xss attack or face deformation after successful upload
Example when user upload files like this
<input type='text'> //This will show input instead of in plain text
body{display:none!important;} // My document body off
So i tried to make this php script, it worked very fine while viewing in my site but when i try to open the file in my notepadd++ i don't like the look can anyone suggest me how i can do this better outside my code or fix mine
<?php
session_start();
if(!class_exists('DBController')){ require_once("../../_inc/dbcontroller.php"); }
if(isset($_FILES['fileuploader'])){
include_once('../fileextension.php');
$test = true;
$FileName = $_FILES['fileuploader']['name'];
$tmp_name = $_FILES['fileuploader']['tmp_name'];
$uploadPath = __DIR__ . '/'.$FileName;
$currentBas = '';
$defaultProjecName = '';
$exetype = pathinfo($FileName, PATHINFO_EXTENSION);
$extension = strtolower($exetype);
if(in_array($extension,$afile)){
$FTypeof = 'file';
}
else if(in_array($extension,$aimg)){
$FTypeof = 'image';
}
else{
$FTypeof = 'unknown';
}
$FDiscripT = 'No available '.($FTypeof == 'unknown') ? '' : $FTypeof.' discription';
//Here i move the selected file in a directory
$moveResult = move_uploaded_file($tmp_name, $uploadPath);
if ($moveResult != true) {
unlink($uploadPath);
}else{
// If file was moved then open file and get the content
if(file_exists($uploadPath)){
$fileUploadname = $uploadPath;
$filechecker = fopen($fileUploadname, "a+");
$mesure = filesize($fileUploadname);
if($mesure == 0){
$sizechecker = 1;
}
else{
$sizechecker = filesize($fileUploadname);
}
$get_content_file = fread($filechecker, $sizechecker);
fclose($filechecker);
//Then here i use htmlentities to encote the file content
if(!empty($get_content_file)){
$sanitize_file = htmlentities($get_content_file);
$sanitize_file_status = true;
}
if($sanitize_file_status == true){
//Now i put the content back the the file
try{
$openForWrite = fopen($uploadPath, 'w');
$recreateNewfile = fwrite($openForWrite, $sanitize_file);
fclose($openForWrite);
if($recreateNewfile){
//Then insert the other information to database
if($test == false){
$makefile_db = new DBController();
$makefile_db->prepare("INSERT INTO jailorgchild(jailowner,jailchildbasname,prodefault,jailchillink,jailchilddate,filediscription,contentType)
VALUES(:jailowner,:jailchildbasname,:SubDif,:jailchillink,:jailchilddate,:FDiscripT,:contentType)");
$makefile_db->bind(':jailchildbasname', $currentBas);
$makefile_db->bind(':SubDif', $defaultProjecName);
$makefile_db->bind(':jailchillink', $FileName);
$makefile_db->bind(':jailowner', $_SESSION['username']);
$makefile_db->bind(':jailchilddate', date('Y-m-d H:i:s'));
$makefile_db->bind(':FDiscripT', $FDiscripT);
$makefile_db->bind(':contentType', $FTypeof);
$makefile_db->execute();
$filewasmake = $makefile_db->rowCount();
$makefile_db->free();
}
echo '<pre>';
echo $sanitize_file;
//echo 'Unclean Content <br/>'. $get_content_file;
}
}catch(PDOException $e){
echo "Error:" . $e->getMessage();
}
}else{
unlink($uploadPath);
}
}
}
}
?>
HTML FORM
<form method="post" action="testuploader.php" enctype="multipart/form-data">
<input type="file" name="fileuploader">
<input type="submit" value="load">
</form>
OUTPUT IN NOTEPAD++
<?php if(isset($_GET['postid'])){ echo '<h5 style="color:
#2f2f2f;">Related Articles</h5><br/>'; <?php } }?>
So if another user download it and the file look like that i don't think is good please i need help
I have gone through a ton of this invalid arguments passed messages on this forum and I am very sorry but have not found any example that helps my situation.
As you can see from the code below with the generous help of Rasclatt, I have several field names including 9 files to be uploaded to the server while the rest of the fields get submitted to the database.
When I attempt to run the code, I get, "Warning: implode(): Invalid arguments passed in..." which is on line 94 - the start of the INSERT statement.
An important point to note is that not all files can be uploaded at one time during an insert.
Users can elect to upload all files, just as they can elect to just upload one file during an insert iteration.
Any idea how to resolve this?
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
include("../Connections/Connect.php");
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
// You may want to add document root
$target = $_SERVER['DOCUMENT_ROOT']."/uploads";
// I am filtering the files incase there are empty uploads
// You need to have the proper file input name (item)
$_FILES['item']['tmp_name'] = array_filter($_FILES['item']['tmp_name']);
$_FILES['item']['name'] = array_filter($_FILES['item']['name']);
$_FILES['item']['type'] = array_filter($_FILES['item']['type']);
$_FILES['item']['size'] = array_filter($_FILES['item']['size']);
foreach($_FILES['item']['name'] as $i => $value ) {
$file_name = $_FILES['item']['name'][$i];
$file_size = $_FILES['item']['size'][$i];
$file_tmp = $_FILES['item']['tmp_name'][$i];
$file_type = $_FILES['item']['type'][$i];
$bidDate = ms_escape_string($_POST['txtBidDate']);
$dueDate = ms_escape_string($_POST['txtDueDate']);
$dueTime = ms_escape_string($_POST['txtDueTime']);
$bidTitle = ms_escape_string($_POST['BidTitle']);
$bidId = ms_escape_string($_POST['BidID']);
$desc = ms_escape_string($_POST['Description']);
$dept = ms_escape_string($_POST['Department']);
$bidContact = ms_escape_string($_POST['BidContact']);
$contactEmail = ms_escape_string($_POST['ContactEmail']);
$contactPhone = ms_escape_string($_POST['ContactPhone']);
$numBids = ms_escape_string($_POST['NumofBids']);
$awardDate = ms_escape_string($_POST['txtAwardDate']);
$awardrecip1 = ms_escape_string($_POST['AwardRecip']);
$bidType = ms_escape_string($_POST['BidType']);
$lastUpdate = ms_escape_string($_POST['txtLastUpdate']);
$notes = ms_escape_string($_POST['Notes']);
$status = ms_escape_string($_POST['Status']);
$sqlArr['values'][$i] = "'".ms_escape_string($_FILES['item']['name'][$i])."'";
$sqlArr['columns'][$i] = "Addend".$i;
$sqlArr['columns'] = "SignInSheet";
$sqlArr['columns'] = "TabSheet";
$sqlArr['columns'] = "BidFile";
// At this point you are only notifying user.
// You have no code to prevent this limitation.
if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg")
$echo = 'You can only upload PDFs, JPEGs or GIF files.<br>';
// So far, this is just for notification, you haven't
// actually done anything about this limitation
if($file_size > (8 * 1024 * 1024))
$echo='File size must be less than 8 MB';
// Makes the folder if not already made.
if(!is_dir($target))
mkdir($target,0755,true);
//Writes the files to the server
if(move_uploaded_file($_FILES['item']['tmp_name'][$i], $target."/".$file_name)) {
//If all is ok
echo "The file ". $file_name. " has been uploaded to the directory and records saved to the database";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
if(isset($sqlArr['columns'])) {
$sql="INSERT INTO bids (BidDate,DueDate,DueTime,BidTitle,BidID,Description,,'".implode("','",$sqlArr['columns'])."',Department,Xcontract,ContactEmail,ContactPhone,NumofBids,AwardDate,AwardRecip1,BidType,LastUpdate,Notes,BidStatus)
VALUES ('$bidDate', '$dueDate','$dueTime',$bidTitle','$bidId','$desc',".implode(",",$sqlArr['values']).", '$dept','$bidContact','$contactEmail','$contactPhone','$numBids','$awardDate','$awardrecip1','$bidType','$lastUpdate','$notes',$status')" ;
$objQuery = sqlsrv_query($conn, $sql);
sqlsrv_close($conn);
} ?>
one problem:
$sqlArr['columns'] = "SignInSheet";
$sqlArr['columns'] = "TabSheet";
$sqlArr['columns'] = "BidFile";
is overwriting the value, not creating an array, you want:
$sqlArr['columns'][] = "SignInSheet";
$sqlArr['columns'][] = "TabSheet";
$sqlArr['columns'][] = "BidFile";
I have been looking around for a solution to this problem, and thus haven't found one. I'm hoping someone will be able to help me out with this problem.
I have this PHP script that gets the posted file, uploads, renames, and moves into a directory:
<?php
$fileName = $_POST['fileName'];
if (!$fileName) $fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
if (!isset($_FILES['wav']) || $_FILES['wav']['error'] > 0) {
$error = 'Y';
$message = 'Error while uploading. Error code: '.$_FILES['wav']['error'];
} else {
$res = #move_uploaded_file($_FILES['wav']['tmp_name'], $distFile);
if (!$res) {
$error = 'Y';
$message = 'Unable to create the file.';
}
}
echo '
<?xml version="1.0"?>
<response>
<error value="'.$error.'" />
<message>'.htmlspecialchars($message).'</message>
</response>
';
?>
That all works fine, however whenever I try to implement a header redirect (like so):
<?php
$fileName = $_POST['fileName'];
if (!$fileName) $fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
if($filename) {
header('Location: http://google.co.uk');
}
I am unable to refresh the page. I must point out that this script is located in a different file than the page I am trying to reload. This script is located in the file saveWav.php and I am trying to reload index.php.
I want you to replace your code to this
$fileName = $_POST['fileName'];
if (!$fileName)
{
$fileName = $distFile.rand(1,999)."-".basename($_COOKIE["email"]);
$distFile = dirname(__FILE__).'/audio/'.$fileName.'.wav';
$error = 'N';
$message = 'Your song was uploaded!';
}
else
{
header('Location: http://google.co.uk');
}
hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here