Convert file_get_contents into $_FILES - php

I have a functionality which will get user input and file input in a form and sent it as an email. I am using this code to capture those files:
$attachments_array = NULL;
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if($tmp_name != ""){
$data=array(
'tmpfname' => $tmp_name,
'filename' => $name,
'type' => $type,
);
$attachments_array[] = $data;
}
}
So I am getting the user file input and putting it into $attachments_array . But what if I have a fixed file located somewhere like in:
https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf
How do I pass that into the attachments array? I am trying:
$attachments_array[] = file_get_contents('https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf');
But seems not working. I would like to pass it in the attachment array like the $data variable.

file_get_contents only gets the actual content of a file and returns it.
You would need to create an associative array and fill all used parameters by yourself, and perhaps save the file somewhere locally, depending on what are the further steps in your file processing.
$row = array();
$row['filename'] = 'A_Beginners_Guide_to_Outsourcing.pdf';
$row['type'] = "application/pdf"; // you might need some other method of getting a file type.
$tmp_path = "/my/tmp/path/".$row['filename'];
$body = file_get_contents('https://www.myurl.com/A_Beginners_Guide_to_Outsourcing.pdf');
file_put_contents($tmp_path, $body); // btw, be careful of what you save on your server..
$row['tmpfname'] = $tmp_path;
$attachments_array[] = $row;

Related

Allowed extension phpmailer

how could i change my code to only accept some extensions.
look my code :
<?php
ob_start();
$_SESSION['nomecomp'] = $_POST['nomecomp'];
$email_env = $_POST['email_env'];
if (isset($email_env)) {
//variaveis vindas da pagina
$varcritico = $_POST['varcritico'];
$nomecomp = $_POST['nomecomp'];
$chapa = $_POST['chapa'];
$funcao = $_POST['funcao'];
$setor = $_POST['setor'];
$unidade = $_POST['unidade'];
$deschelp = $_POST['deschelp'];
//variveis do modal
//$email_env = $_POST['email_env'];
//$senha_env = $_POST['senha_env'];
<td>$deschelp</td>
</tr>
</table>'";
/**
* PHPMailer multiple files upload and send example
*/
$msg = '';
//if (array_key_exists('userfile', $_FILES)) {
// Create a message
// This should be somewhere in your include_path
include ("lib/PHPMailerAutoload.php");
$mail = new PHPMailer();
i have tried add some codes , but dont made sucess , for example , could i try push the array and see if the extension are inside some array ?
thanks.
Presuming you want to check the uploaded file types before moving them:
$AllowedFileTypes = array("pdf","txt"); // build array
$FileName = $_FILES['userfile']['name']; // get filename of file input
$FileType = end((explode(".", $FileName))); // get file type/extension
if(in_array($FileType, $AllowedFileTypes)){ // check to see if file type is allowed
// perform copy/move file
}
else{
// ignore/alert/whatever
}
Note: You may have to amend the variables to suit your requirements.
If you wish to validate the file type/extension before submitting the form, take a look at jQuery validation for file input: https://stackoverflow.com/a/20929391/715105

Unable to upload Image on live site

I have a site where there is member registration. All data will be saved but I get only this error:
Could not move the file "/tmp/phpa4pH3I" to "/home/sporter/public_html/someonect.org/uploads\membersImages/33921.jpg" ()
My code is like this
public function store(){
// dd(Input::all());
$validator = Validator::make(Input::all(), Members::$rules);
if($validator->passes()):
$first_name = Input::get('mem_firstName');
$last_name = Input::get('mem_lastName');
$email = Input::get('mem_email');
$image = Input::get('mem_image');
$phone = Input::get('mem_phone');
$occupation = Input::get('mem_occupation');
$citizen = Input::get('mem_citizen');
$address = Input::get('mem_address');
$destinationPathImage = str_replace('PROJECT\\', '', base_path().'\uploads\membersImages\\') ;
//Generating a random name
$randomName = rand(11111,99999);
//Renaming the image
$ImageName = $randomName.'.'.'jpg'; // renameing image
$imagePath = $destinationPathImage.$ImageName;
Members::create([
'first_name'=>$first_name,
'last_name'=>$last_name,
'email'=>$email,
'image'=>$imagePath,
'phone'=>$phone,
'occupation' => $occupation,
'citizen' => $citizen,
'address'=>$address
]);
...
I don't understrand clearly your str_replace part, but if you setup your url in config properly, you don't need this.
I'm using this kind of upload for an image:
if($request->hasFile('mem_image')) {
$file = $request->file('mem_image');
$ext = $request->file('mem_image')->getClientOriginalExtension();
$filename = rand(11111,99999). '.' . $ext;
$file->move('./uploads/', $filename);
$member->mem_image = '/uploads/' . $filename;
$member->save();
}
In case, your uploads directory is in your public folder.
If your script have permission for writing in target folder. The problem can be only in path. Check what contain in variable $destinationPathImage. It must be correct and exists path. In your error message I see problem with slashes.
also think that it's be cool to check exists of destination folder and file exists before save to database record with path of file.
You're not using the proper slashes.
Replace \uploads\membersImages\\ with /uploads/membersImages/.
If it still not working, please double check the permissions in that folder using the is_writable php function. However, have in mind that the is_writable function is not working properly on windows platforms.

How to save a image filecontent into the SQL database using eloquent?

I'm getting confused about how to save an image content inside of a database table.
Please see the fourth line of code. I'm sure that this restful method (using POST) is working because getSize() returns the true value.
Also, if I debug what returns the 5th line I get something like the next one:
So, I'm not sure if what am I missing to save this data into the database.
$personId = Input::get('PersonId');
$file = Input::file('media');
$tmppath = $file->getRealPath();
$content = file_get_contents($tmppath); //$file->getSize();
// return $content;
$model = Person::find($personId);
$model->Photo = $content;
$model->save();
$result = array(
"success" => true,
"data" => $personId,
"error" => ""
);
You need to save the file to the server and only store the path in the database.
Write an appropriate method, ideally you can store it in a trait.
private function saveFileToDisk($file, $fileName)
{
$path = public_path() . '/uploads/';
return $file->move($path, $fileName . $file->getClientOriginalExtension());
}
An then pass the file input to your method and provide a name for the file:
$model->Photo = $this->saveFileToDisk(Input::file('media'), $model->Name);
Obvisouly you need to validate you input before all this.

multi picture upload in zend framework, how to?

i have an issue with uploading multiple files to disk. here is my code.
i have a request with 2 pictures that gets sent to a upload function. the 2 pictures are in a var called $multiUpload
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$file = array();
$filename = array();
foreach($multiUpload as $key=>$val){
// get the file extension
$file[] = explode('.',$val);
// create custom file name
$filename[] = time().'.'.$file[$key][1];
//send to the upload function
$this->uploadToDisk($folderPath, $filename[$key]);
// sleep 1 sec so that the pic names will be different
sleep(1);
}
return $filename;
}
public function uploadToDisk($folderPath, $filename)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination($folderPath);
$adapter->addFilter( 'Rename',array(
'target' => $folderPath."/".$filename,
'overwrite' => true
) );
if ($adapter->receive()) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
this will return
Array
(
[0] => Array
(
[0] => 1332977938.jpg
[1] => 1332977939.jpg
)
)
but only array[0][0] or 1332977938.jpg will actually get saves to the disk.
Why are they now both get saved? wired
any ideas?
I suspect the second call to uploadToDisk is returning fail because you can only call Zend_File_Transfer_Adapter_Http::receive() once for each file. Since you are not specifying a file when calling receive, it is receiving all of the files the first time you call uploadToDisk and subsequently is failing with a File Upload Attack error.
Here is some code you can try. This tries to receive each file individually and then save them one at a time with each call to uploadToDisk.
A few notes about the code:
The first parameter to uploadToDisk ($val) may need to be changed as I am not sure what the original values are. It should correspond to one of the element names used for the file upload (See Zend_File_Transfer_Adapter_Http::getFileInfo()) for a list of the files.
I changed the method for generating a unique filename so you don't have to sleep(1)
Zend_File_Transfer_Adapter_Abstract::setDestination() is deprecated and will go away in the future. Instead, just use the Rename filter. When using Rename, setDestination() has no effect.
And here it is...
<?php
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$filenames = array();
foreach($multiUpload as $key => $val){
// get the file extension
$ext = explode('.', $val);
$ext = $ext[sizeof($ext) - 1];
// create custom file name
do {
$filename = uniqid(time()) . '.' . $ext;
$diskPath = $folderPath . $filename;
} while (file_exists($diskPath));
$filenames[$key] = $filename;
//send to the upload function
// $val is the file to receive, $diskPath is where it will be moved to
$this->uploadToDisk($val, $diskPath);
}
return $filename;
}
public function uploadToDisk($file, $filename)
{
// create the transfer adapter
// note that setDestination is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($file)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}

Drupal 6 Node Creation PHP Script with File upload not working

I've got this PHP script I'm working on to import pay-stubs into Drupal. It's doing everything the way I want except the script is not attaching the uploaded PDF file to the node.
A few notes; Drupal's filesystem is set to private, not sure if this makes a difference or not. Second, the pdf files are already in the correct location 'paystubs/[uid]/paystub_1.pdf' so I think my problem is that the file is not being associated to the node correctly.
Here is the code
function create_drupal_node($employeeID, $employeeDate, $drupalUid, $file2) {
$sourcePDF = "/var/www/html/mgldev.************.com/burst_pdfs/pdfs/" . $file2;
$destinationPDF = '/paystubs/' . $drupalUid . '/' . $file2;
$destination = '/paystubs/' . $drupalUid . '/';
if (!file_check_directory($destination, TRUE)){
echo "Failed to check dir, does it exist?";
mkdir($destination);
echo "trying to drupal mkdir...";
}
// Copy the file to the Drupal files directory
if (file_exists($sourcePDF)) {
if(!rename($sourcePDF, $destinationPDF)) {
echo "Failed to move file\n";
}
}
//Create node and attach file uplaod
$file_drupal_path = "paystubs/" . $drupalUid . "/" . $file2;
$mime = 'pdf/application';
$file = new stdClass();
$file->filename = $file2;
$file->filepath = $file_drupal_path;
$file->filemime = $mime;
$file->filesize = filesize($file_drupal_path);
$file->uid = $drupalUid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file);
$node = new StdClass();
$node->type = 'paystub';
$node->body = $employeeID;
$node->title = $employeeDate;
$node->field_paystub_upload = array(
array(
'fid' => $file->fid,
'title' => $file2,
'filename' => $file->filename,
'filepath' => $file->filepath,
'filesize' => $file->filesize,
'mimetype' => $mime,
'data' => array(
'description' => $file2,
),
'list' => 1,
),
);
$node->uid = $drupalUid;
$node->status = 1;
$node->active = 1;
$node->promote = 1;
node_save($node);
}
The node is created and the title and body of the node have the right values. When I look at the node using Devel module I can see that the 'field_paystub_upload' array is null. So for some reason its doing everything right except attaching the file to the node and that is what I've been banging my head on for days. Best response gets on free internet?
Drupal's file.inc file_save_upload uses $_FILES, which is a global, magically set by PHP. Drupal expects an uploaded file, not a file that exists locally.
You best just call a custom file-saver method, to process local files. Make sure its path up in the files database-table too. file_save_upload will be valuable for creating such a helper method.
Big thanks to berkes for helping me solve this problem. Turns out that since the files were already on the drupal webserver and not being uploaded to PHP $_FILES global variable, I was unable to programmatically upload the file correctly.
This was causing every other way I've tried to fail. I tried using Drupals defualt upload module and I also tried using CCK's fielfield module both were not working. Thanks to berkes suggestion I found a function that comes with CCK's filefield widget to save uploaded files that are already on the server. Hopefully this helps someone else.
This is the function I found that can save a file thats already on the web-server.
Here is the working code I used to create the node and attach the file after calling field_file_save_file.
function create_drupal_node($employeeID, $employeeDate, $drupalUid, $file2){
$file_remove_html_extention = substr($file2, 0, -7);
$file_pdf = $file_remove_html_extention . '.pdf';
$node = new stdClass();
$node->type = 'paystub';
$node->status = 1;
$node->uid = $drupalUid;
$node->title = $employeeDate . ' - eStub';
$node->body = $employeeID;
$node->created = time();
$node->changed = $node->created;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->language = 'en';
$file = '/var/www/html/mgldev.foobar.com/burst_pdfs/pdfs/' . $file_pdf;
// Get the path to your Drupal site's files directory
$dest_folder = '/paystubs/' . $drupalUid;
$dest = 'paystubs/' . $drupalUid . '/' . $file_pdf;
if (!file_check_directory($dest_folder, TRUE)){
mkdir($dest_folder);
}
// Load the CCK field
$field = content_fields('field_paystub_upload', 'paystub');
// Load the appropriate validators
$validators = array_merge(filefield_widget_upload_validators($field));
// Create the file object
$file = field_file_save_file($file, $validators, $dest_folder);
// Apply the file to the field, this sets the first file only, could be looped
// if there were more files
$node->field_paystub_upload = array(0 => $file);
// The file has been copied in the appropriate directory, so it can be
// removed from the import directory
unlink($file);
// change file status to permanent
file_set_status($file,1);
node_save($node);
}
</pre></code>
Thanks again berkes

Categories