PHP not inserting images into directory - php

I've got a PHP script that receives data from users. The script is hosted on an AWS EC2 instance running Apache, PHP and PostGreSQL.
Here's the script:
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$length = 5;
$fileName = '';
for($i = 0; $i < $length; $i++) {
$fileName .= $chars[mt_rand(0, 36)];
}
$filePath = "uploads/$fileName.jpg";
$encoded_photo = $_POST['snap'];
echo $encoded_photo;
$photo = base64_decode($encoded_photo);
$file = fopen($filePath, 'wb');
fwrite($file, $photo);
fclose($file);
So a random filename is generated for the photo and then the $filePath variable is inserted into the PostGreSQL.
However when I check the uploads/ directory it's empty. No JPEGs to be found. I believe my code to be correct, perhaps the permissions of the directory aren't correct? Could any provide any guidance?
Please note I have host=localhost port=5432 dbname=*** user=**** password=**** in my pg_connect() method.

Apache needs to be able to write to the uploads/ directory. One way to do this is to put the Apache user into the group on uploads/ and make sure the group has write permission on the directory.
https://stackoverflow.com/questions/7283068/how-to-add-an-existing-user-into-a-group-in-linux
This will give the group write permission: chmod g+w uploads/

Related

PHP copy command folder

My currency working directory is ../main
I have a script which accepts files to be uploaded.
I have the following code but instead of coping the file into the ../_assets folder, it copies it into the ../main folder with the filename as ../_assets/correct.csv.
Any idea what might be wrong here?
Thanks
const IMPORT_FILE_DIR = "..\_assets\\";
private $file_name = "";
$this->file_name = Page::IMPORT_FILE_DIR . $_FILES['file_in']['name'];
$result= copy( $_FILES['file_in']['tmp_name'],$this->file_name);
Here fileName is = "..\_assets\correct2.csv"

Storing image to Public folder Laravel 5.1

I'm trying to save an image to a folder in my laravel application.
I'm getting the error:
fopen(F:\blog\public/usr-data/photos): failed to open stream: Permission denied
Here's my laravel controller which is writing to this folder.
$error = false;
$absolutedir = public_path();
$dir = '/usr-data/photos';
$serverdir = $absolutedir.$dir;
$filename = array();
foreach($_FILES as $name => $value) {
$json = json_decode($_POST[$name.'_values']);
$tmp = explode(',',$json->data);
$imgdata = base64_decode($tmp[1]);
$fileAry = explode('.',$json->name);
$extension = strtolower(end( $fileAry ));
$fname = $card->id.'.'.$extension;
$handle = fopen($serverdir,'w');
fwrite($handle, $imgdata);
fclose($handle);
$filename[] = $fname;
}
I've tried using
Icacls "F:\blog\public/usr-data/photos" /grant Everyone:(OI)(CI)F
But no joy - still the same issue.
You need to set up writing permissions on a storage and public folders and then all folders inside these ones. Use right click on a folder, go to Properties and change folder permissions.
http://m.wikihow.com/Change-File-Permissions-on-Windows-7
EDIT: This will work for Linux only. I'm keeping this answer in case anyone runs into the same problem on a Linux machine.
Try this:
php artisan cache:clear
sudo chmod -R 777 app/storage
composer dump-autoload
Instead of using file write, you can also use the Laravel filesystem storage class. Please try with the below given example.
$image represents the encoded image.
$Id represents the id of the user.
public function imageUpload($image, $Id)
{
//Decode base64 string to image
$profile_image = 'image/jpeg;base64,' . $image;
$new_data = explode(";", $image);
$data = explode(",", $new_data[1]);
$file = base64_decode($data[1]);
$imageFileName = $Id . '.jpeg';
$image_path = '/storage/' . $imageFileName;
Storage::put($imageFileName, $file);
return $image_path;
}

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

moving uploaded file to a dynamic table in php

I'm trying to move the file that I uploaded using move_uploaded_file. Here are my variables:
$filename = $_FILES['File_file']['name'];
$folder_id = $_POST['File']['folder_id'];
$folder_name_result = $this->filemanager_model->getfoldername($folder_id);
$fileloc = $_FILES['File_file']['tmp_name'];
$folder_name = "";
foreach ($folder_name_result->result_array() as $row)
{$folder_name = $row['title'];}
$pathAndName = "filemanager/".$folder_name."/".$filename;
And the outputs of the variables:
$folder_name = Grrr
$pathAndName = filemanager/Grrr/cis.png
$fileloc = C:\xampp1.8\tmp\phpE21E.tmp
When I run the move_uploaded_file function, it generates an error where:
move_uploaded_file(filemanager/Grrr/cis.png): failed to open stream: No such file or directory
move_uploaded_file(): Unable to move 'C:\xampp1.8\tmp\php2565.tmp' to 'filemanager/Grrr/cis.png'
My filepaths:
/admin - base_url
/admin/filemanager/Grr - The folder I want it to save
/admin/application/controllers/- the path of my controllers
Is there something wrong with my code as to why it's not working?
I just had something wrong with the formatting of my file path. I had to include the exact path since I'm on localhost, so once I put this on the server I've got to change path to the one on my server.
$pathAndName = "C:\\xampp1.8/htdocs/cicubecms/admin/filemanager/".$cat_name."/".$folder_name."/".$filename;

Folder with Random Name and Save file to it with PHP

So I am creating trying to create a PHP script where the client can create a folder with a 10 digit name of random letters and numbers, and than save the document they are currently working on into that folder. Its like a JSfiddle where you can save what you are currently working on and it makes a random folder. My issue is that it wont create my directory, and the idea is correct, and it should work. However, PHP isn't saving an Error Log so I cannot identify the issue. Here's what I got so far.
PHP
save_functions.php
<?php
function genRandomString() {
$length = 10;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
<?php
function createFolder() {
$folderName = genRandomString(); //Make a random name for the folder
$goTo = '../$folderName';//Path to folder
while(is_dir($goTo)==true){ //Check if a folder with that name exists
$folderName = genRandomString();
$goTo = '../$folderName';
}
mkdir($goTo,7777); //Make a directory with that name at $goTo
return $goTo; //Return the path to the folder
}
?>
create_files.php
<?php
include('save_functions.php');//Include those functions
$doc = $_POST['doc'];//Get contents of the file
$folder = createFolder();//Make the folder with that random name
$docName = '$folder/style.css';//Create the css file
$dh = fopen($docName, 'w+') or die("can't open file");//Open or create the file
fwrite($dh, $doc);//Overwrite contents of the file
fclose($dh);//Close handler
?>
The call to mkdir($goTo,7777) has wrong mode, this is usually octal and not decimal or hex. 7777 is 017141 in octal and thus tries to set non-existent bits. Try the usual 0777.
But why don't you just use tempnam() or tmpfile() in your case?

Categories