ZipArchive not saving file on live server in Laravel - php

I have some encrypted responses that I convert to a Zip file in my Laravel application. The function below downloads the API response, saves it as a Zip file, and then extracts it while I read the folder's contents. In my local environment, it works well. However, the Zip file is not getting saved to the storage folder on the live server. No error is being shown, only an empty JSON response. Please, what could be the cause?
public function downloadZipAndExtract($publication_id, $client_id)
{
/* We need to make the API call first */
$url = $this->lp_store."clients/$client_id/publications/$publication_id/file";
$file = makeSecureAPICall($url, 'raw');
// Get file path. If file already exist, just return
$path = public_path('storage/'.$publication_id);
if (!File::isDirectory($path)) {
Storage::put($publication_id.'.zip', $file);
// Zip the content
$localArchivePath = storage_path('app/'.$publication_id.'.zip');
$zip = new ZipArchive();
if (!$zip->open($localArchivePath)) {
abort(500, 'Problems experienced while reading file.');
}
// make directory with the publication_id
// then extract everything to the directory
Storage::makeDirectory($publication_id);
$zip->extractTo(storage_path('app/public/'.$publication_id));
// Delete the zip file after extracting
Storage::delete($publication_id.'.zip');
}
return;
}

First thing I'd check is if the storage file is created and if it isn't created, create it. Then I'd look at your file permissions and make sure that the the groups and users permissions are correct and that you aren't persisting file permissions on creation. I've had many instances where the process that's creating files(or trying) is not in the proper group and there is a sticky permission on the file structure.

Related

Remove "Attachments" folder after PHPMailer email is sent

I've got a web form which has a unique upload folder for each user (using their PHP session_id() as the folder name) which works well. When the form is submitted (after error checking) PHPMailer is used to send the email and the attachments. This is also working well. However, after the email is sent, I would like to remove the uploads from the folder and then the folder itself (sort of a self-cleanup!) The files are removed as expected but the folder remains (albeit empty). I wonder if the folder is somehow "still in use" so doesn't get deleted or something similar? This is the code:
// Empty the contents of the upload folder
if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
// Check for any files inside the directory
$files = glob($dir.'/*'); // Get all file names
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
// Remove the upload folder
rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
}
Any other ideas on why this folder is remaining?
Ben
I would guess that your folders might contain hidden files (starting with .) which the default glob pattern won't match, so try this:
$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
Also check the return value on both unlink and rmdir so you can see exactly where it's failing.
Turns out after much testing that the problem was not actually with rmdir at all! My web form uses a Dropzone for photo uploads to a unique folder for each user using their php session_id() and this folder is supposed to be created when they add a photo to Dropzone (if it doesn’t already exist). Problem was I’d put the folder creation code outside of the actual upload script so the folder was in fact being deleted but them instantly created again when the form submitted and the page reloads! Sorry about that but thanks for all your help. :)

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).

upload a file to a specific folder php

My purpose is uploading a remote file create from my PC to specific folder, but I don't know whats wrong with my code below. It uploads the file with the name and the .jpg extension, but it is not moving the file to the specified folder.
if(isset($_POST["image"])){
define("SITE_NAME","project_name/"); //constant for project name
define("SITE_PATH",$_SERVER['DOCUMENT_ROOT']."/".SITE_NAME); //constant for project base directory
define("IMAGES_URL",SITE_URL."images/"); //constant for image directory
$upload_base_dir=IMAGES_URL;
$upload_time_dir=date('Y')."/".date('m')."/".date('d')."/"; // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true); //create directory if not exist
}
$input = $_POST["image"];
$file = fopen(time()."image.jpg", 'wb');
fwrite($file, $input);
//$image_name=basename($_FILES['image']['name']);
$image=time().'_'.$image_name;
move_uploaded_file($file,$upload_dir.$image);
fclose($file);
}
Any suggestions? Thank you in advance.
move_uploaded_file($file,$upload_dir.$image) will only work for items within temp, that are accessable via $_FILES superglobal. If you are sending your file as a strieam within post, that wont work.
1) If file is a form upload make sure form is a multipart and access your file via $_FILES superglobal
move_uploaded_file($_FILES['userfile']['tmp_name'], $yourDirectory.$yourFilename);
2) If you post the file as a stream via post (keep in mind this will only work for small files as large ones will exceed request limit). Save the file directly to it's destiantion using fopen or to move it after you created it use rename() - http://php.net/manual/en/function.rename.php
rename($currentFilePath, $newFilePath)
P.S. sending files as post streams is a very very bad idea.

Yii2 generate zip file and download- In YII2.0

I have a situation, I have list of user data, in that data details, i have stored a file also.
Now i want to download all the file of users in zip file, when a user click on a button like DOWNLOAD.
i have written a action in controller where im fetching the file to be downloaded, but im unable to write code for making zip finle and download it.
Below is my code in controller.
public function actionMain($jid)
{
$values = UserRequest::find()->where(['sender_code'=>$jid,'status'=>1])->all();
$i=1; foreach($values as $data) {
$users = Users::find()->where(['access_code'=>$data->reciever_code])->one();
$file_names[]= $users->attach_cv;
}
}
This is working fine. in $file_name im fetching all the file's, But i want to download this files in a zip foder.
Please help me to solve this issue
The link provided is in core php and easily implemented in that. But how about doing the same in framework. Because i have array of file name in action. As you can see above. DO i need to write the code for generating .ZIP in the same action or any other action.
I would recommend using a ZipArchive as specified in the comment by SiZE.
That way you initiate the zipping process before you start the download.
File creation:
/**
* Generate zip file for upload
*
* #throws Exception
*/
private function createZip($files)
{
$file = 'full_path_to_file/your_file_name.zip';
$zip = new ZipArchive();
if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {
throw new \Exception('Cannot create a zip file');
}
foreach($files as $file){
$zip->addFile($file[file_name], $file[local_name]);
}
$zip->close();
}
And then you can return the zip file path for download in your action

Issues of Parse Email and Save Attachments into directory

I am using this script(http://stuporglue.org/mailreader-php-parse-e-mail-and-save-attachments-php-version-2/) to save email attachment on my server. You can also view the complete script on browser here: http://stuporglue.org/downloads/mailReader.txt
Everything works fine but there are 2 problems here.
1) The file name of the image that i saved into the directory is not an image: 1360341823_test_jpg
How to convert the file name from 1360341823_test_jpg to 1360341823_test.jpg
in the script?
2) The permission of the file that saved in the directory is 600.
How to make it default 755 or 775?
I believe this is the function to convert the image in the script.:
function saveFile($filename,$contents,$mimeType){
global $save_directory,$saved_files,$debug;
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time()."_".$filename;
while(file_exists($save_directory.$name)) {
$name = time()."_".$filename;
}
// Attempt to lock
$outfile = fopen($save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
} else {
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
// This is for readability for the return e-mail and in the DB
$saved_files[$name] = Array(
'size' => formatBytes(filesize($save_directory.$name)),
'mime' => $mimeType
);
}
Any help?
The original script used the data to store in the DB but I think you are trying to save it in the file. You are creating the file without extension here:
// Attempt to lock
$outfile = fopen($save_directory.$name,'w');
Either add the .jpg after the line as:
#outfile.=".jpg";
Other way if you don't want to change script then you can get use as:
$contents = file_get_contents($save_directory.$name);
$outfile = fopen($save_directory.$new_name,'w');
write($outfile,$contents);
fclose($outfile);
This would resolve your first problem and for second question kindly use the FTP or Control panel provided to access the files to change the ownership rights. If you don't know about any thing then you contact your Web Hosting Service Provider to share the ownership from 755 to 775

Categories