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";
Related
i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
//count array data inputed
for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
// update education
foreach( $data_detail_user['institution_names'] as $key => $file ){
// get old photo thumbnail
$get_photo = Educations::where('id', $key)->first();
// store photo
$path = $file->store(
'assets/education/thumbnail', 'public'
);
$education_user = Educations::find($incs);
$education_user->detail_user_id = $detail_user['id'];
$education_user->name = $data_detail_user['institution_names'][$incs];
$education_user->course = $data_detail_user['education_courses'][$incs];
$education_user->start = $data_detail_user['education_starts'][$incs];
$education_user->graduate = $data_detail_user['education_graduates'][$incs];
$education_user->address = $data_detail_user['education_addresses'][$incs];
$education_user->regencies = $data_detail_user['education_regencies'][$incs];
$education_user->provinces = $data_detail_user['education_provinces'][$incs];
$education_user->country = $data_detail_user['education_countries'][$incs];
$education_user->zip_code = $data_detail_user['education_zips'][$incs];
$education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
$education_user->save();
$data_detail_user = 'storage/' .$get_photo['certificate'];
if (File::exists($data_detail_user)) {
File::delete($data_detail_user);
} else {
File::delete('storage/app/public/' .$get_photo['certificate']);
}
}
}
[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png
$path = $request->file('path')->store('public/post');
I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.
I am trying to upload image but getting my own exception :
Image is not valid, please select a proper image.
I reviewed my code and researched on google and in stackoverflow as well. But did not get any proper solution. It is my code given below for uploading image
.
Code :
$fetchName = "SELECT FirstNameMiddleName, LastName FROM mmb WHERE UserId = ".$_SESSION['UserId'];
$fetchNameFire = mysqli_query($conn, $fetchName);
$resultName = mysqli_fetch_assoc($fetchNameFire);
$filename = $_FILES["aadhaarphoto"]["name"]."_".$_SESSION['UserId']."_".$resultName['FirstNameMiddleName']."_".$resultName['LastName'];
$tempname = $_FILES["aadhaarphoto"]["tmp_name"];
$folder = "AadhaarCards/".$filename;
//====================================================
$allowedExtension = array('jpg','png','gif','JPG','PNG','GIF');
$ext = pathinfo($filename,PATHINFO_EXTENSION);
//====================================================
if(!in_array($ext,$allowedExtension))
{
//echo mysqli_error($conn);
echo 'Image is not valid, please select a proper image';
}
else
{
$updateUser = "UPDATE mmb SET Address = '$UserAddress', DOB = '$UserDOB', Phone = '$UserPhone', Whatsapp = '$UserWhatsapp', AadhaarCardNo = '$UserAadhaarNo', AadhaarCardPhoto = '$folder' WHERE UserId = ".$_SESSION['UserId'];
$updateUserFire = mysqli_query($conn, $updateUser);
if($updateUserFire)
{
move_uploaded_file($tempname, $folder);
}
else
{
echo mysqli_error($conn);
}
}
It looks like you are appending things on to the end of the file name.
$filename = $_FILES["aadhaarphoto"]["name"]."_".$_SESSION['UserId']."_".$resultName['FirstNameMiddleName']."_".$resultName['LastName'];
So if the file name was "image.jpg" it would become something like "image.jpg_123_John_Doe". The file extension is now "jpg_123_John_Doe", which is not on your list.
If you change your code like this it should work.
$ext = pathinfo($_FILES["aadhaarphoto"]["name"],PATHINFO_EXTENSION);
Trying to append $_SESSION['bandname']; to an mp3 file upload, The concept
is when someone uploads a song it append the band name to mp3 bandname_songname.mp3 if that makes sense. here is my code so far.
the problem is with this line i think $aditionalnewFileName = $bandname.="_".$aditionofileName; this strange part is when I use the var_dump($bandname); well instead of the band name its the song I'm testing with string(88) "_police.ogg_police.ogg_police.ogg_police.ogg_police.mp3_police.mp3_police.mp3_police.wav". maybe mysqli would be more simple?
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
var_dump($_SESSION['bandname']);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution
time of this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client
//side file tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/',
'',$_FILES['song_name']['name']); // get client side file name remove
the special character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = $bandname.="_".$aditionofileName; //filename
changed with current time
if ( move_uploaded_file($aditiontmp_name,
"$uploads_dir/$aditionalnewFileName")) //Move uploadedfile
{
$uploadFile = $uploads_dir."/".$aditionalnewFileName; //Uploaded file
path
$ext = pathinfo($uploads_dir."/".$aditionalnewFileName,
PATHINFO_EXTENSION); //Get the file extesion.
$uploadFilebasename = basename($uploads_dir."/".$aditionalnewFileName,
".".$ext); //Get the basename of the file without extesion.
$exName = ".mp3";
$finalFile = $uploads_dir."/".$uploadFilebasename.$exName; //Uploaded
file name changed with extesion .mp3
$encode_cmd = "/usr/bin/ffmpeg -i $uploadFile -b:a 256000 $finalFile
2>&1"; // -i means input file -b:a means bitrate 2>&1 is use for debug
command.
exec($encode_cmd,$output); //Execute an external program.
echo "<pre>";
// will echo success , for debugging we can uncomment echo
print_r($output);
// also want to add redirect to this script to send back to profile
after upload
echo "The file was uploaded";
//echo print_r($output); // Report of command excution process.
echo "</pre>";
if($ext !== 'mp3'){ // If the uploaded file mp3 which is not remove
from uploaded directory because we need to convert in to .mp3
unlink( $uploadFile );
}
//0644 vs 0777
chmod( $finalFile, 0777 ); // Set uploaded file the permission.
}
else
{
echo "Uploading failed"; //If uploding failed.
}
?>
so after a while, I decided to go about it a different way. I used mysqli,i quarried the user name and bandname, then used the while loop used var_dump noticed bandname after staring at my code i saw i was editing the wrong line so i change $aditionofileName = preg_replace('/[^A-Za-z0-9-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); and change the line i thought was the problem to $aditionalnewFileName = "_".$aditionofileName; revmoed variable and removed the .
new code below.
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
if (isset ($_GET ['band_id']))
{ // Yes
$showband = $_GET ['band_id'];
}
else
{ // No
echo "ID not set"; // Just show the member
}
include 'connect.php';
$sql = "SELECT * from members WHERE band_id=$showband";
$result = mysqli_query ($dbhandle, $sql);
while ($row = mysqli_fetch_array ($result))
{
$username = $row ["username" ];
$bandname = $row ["bandname" ];
}
var_dump($bandname);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution time of
this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client side file
tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); // get client side file name remove the special
character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = "_".$aditionofileName; //filename changed with current
time
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;
I allow users to submit files into the database on my website. But every time a file is submitted, i get these error messages
( ! ) Warning: file_get_contents() expects parameter 1 to be a valid path, array given in C:\wamp64\www\MT\developerUpload.php on line 8
( ! ) Warning: trim() expects parameter 1 to be string, array given in C:\wamp64\www\MT\developerUpload.php on line 9
But I was told that "file_get_contents" is the way you send the file contents to the database. Without the "file_get_contents" it sends perfectly but with it, it gives me those error messages and I am not sure why. So what i want to do is, submit the file using the "file_get_contents" so later on i can display the content on the users page. Here is my code
PHP
$query = "INSERT INTO pack_screenshots(pack_id, file_name, file_tmp)VALUES(:packid, :file_name, :file_tmp)";
$stmtFileUpload = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
$file_name = addslashes(trim($_FILES['file']['name']));
try{
$stmtFileUpload->bindParam(':packid', $packid, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmtFileUpload->execute();
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$dir.'/'.$file_name);
}else{
$_SESSION['invalid'] = true;
header("Location: developer_invalid.php");
exit;
}
$_SESSION['thankyou'] = true;
header("Location: developerUpload_thankyou.php");
exit;
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
Your problem is you have no keys associated with the 2 lines giving you an error (and probably elsewhere in your code), therefore they are arrays (as you are not selecting a specific key).
You need to associate the keys to the $_FILES array.
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
Since you are using multiple uploads so you have to assign keys to them before proceed.
file_get_contents() and trim() accepts string here you pass array in it without assigning key.
Try this:
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));