I am editing a current website right now. I want to change file uploading mechanism from http to ftp. They use File module with Drupal 7. the thing i need is, in a form, when i select which files to upload, how can i get their machine path (e.g. C:\path/to/file.mov)?
I need this path to use in php ftp_nb_put function.
function assets_managed_file_form_upload_submit($form, &$form_state) {
for ($i = 0; $i < $form_state['num_files']; $i++) {
if ($form_state['values']['files_fieldset']['managed_field'][$i] != 0) {
// Make the file permanent.
$file = file_load($form_state['values']['files_fieldset']['managed_field'][$i]);
$file->status = FILE_STATUS_PERMANENT;
$directory = 'private://cubbyhouse/'. $form_state['values']['allowed_user'];
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
$file->uid = $form_state['values']['allowed_user'];
drupal_chmod($file->uri);
file_save($file);
//drupal_set_message(t($debug=print_r($form)));
// Need to add an entry in the file_usage table.
file_usage_add($file, 'assets', 'image', 1);
drupal_set_message(t("Your file has been uploaded!"));
}
}
}
Right now this is how they handle file submitting
Related
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
Can not upload PDF, JPG,... file at databases at different server?
I have a form on a one server and when they fill the data, data should be stored in a database on another server
function do_upload_files($id) {
$allowed_doc_exts = "txt|pdf|jpg|jpeg|doc|odt|gif";
$allowed_docs = 5;
$ret = array();
for ($i = "0"; $i <= $allowed_docs; $i++) {
$exts = explode("|", $allowed_doc_exts);
$doc = "documents_" . $i;
if (!isset($_FILES[$doc]))
continue;
if (empty($_FILES[$doc]["name"]))
continue;
$ext = pathinfo($_FILES[$doc]["name"], PATHINFO_EXTENSION);
if (!in_array(strtolower($ext), $exts))
continue;
$doc_dir = "/home/httpd/vhosts/domain.com/httpdocs/content/document/$id/";
if (!is_dir($doc_dir))
mkdir($doc_dir, 0777, true);
$doc_path = $doc_dir . $i;
if(move_uploaded_file($_FILES[$doc]["tmp_name"], $doc_path)) {
$ret[$i]["name"] = $_FILES[$doc]["name"];
$ret[$i]["type"] = $_FILES[$doc]["type"];
}
This is problem (i think):
$doc_dir = "/home/httpd/vhosts/domain.com/httpdocs/content/document/$id/";
You have to create some kind of API, on the server you wanna put files on. Otherwise you could just easily put files on stackoverflow server for example. So you have to create an API on the other server, who takes the files, and saves it onto the server. Aswell, you should password protect it, or you will be hacked very fast, if everybody can put files on your server.
On the other side, you just have to send data with a form, which contains the files.
While User uploads the files, the folder should be automatically created in the dropbox with the username as folder name. and then after the files that were uploaded by the user should be saved in that folder.
Error thrown:
"
Error: Resource at uri: https://api.dropbox.com/1/metadata/dropbox/sweety could not be found."
The code is
// Upload
$wpschunks = explode("/",$wpsdbTmpFile);
for($i = 0; $i < count($wpschunks); $i++) {
$c = $i;
}
global $current_user;
$wpuserid = $current_user->data->ID;
$wpusername = $current_user->data->user_login;
$newfoldername = $wpusername;
// echo trim($wpsdb_path,'/').' //\\ ';
$folderMetadata = $dropbox->getMetaData(trim($wpsdb_path, '/') . '/' . $newfoldername, true);
if (!$folderMetadata['is_dir']) {
$dropbox->CreateFolder(trim($wpsdb_path, '/') . '/' . $newfoldername, "dropbox");
if ( !$dropbox->putFile(trim($wpsdb_path,'/').'/'.$newfoldername.'/'.$wpschunks[$c], $wpstmpFile,"dropbox") ) {
throw new Exception(__('ERROR! Upload Failed.','simpleDbUpload'));
}
if($wpsdb_delete_file == "True") {
if (isset($wpsdbTmpFile) && file_exists($wpsdbTmpFile)) {
unlink($wpsdbTmpFile);
}
}
}
Note:
When we create the blank folder manually in dropbox and then delete it and then if we try to upload the files the folder is create automatically(using this code) and the files also get uploaded.
I have no idea what "api version of 2010" means. :-) I don't know what library the Wordpress plugin is based on, but it looks like in this one, an error is raised when you request the metadata of a path that doesn't exist. I don't see why this is a problem... just handle the error and continue?
As an alternative, you could just not create the folder at all. Folders are implicitly created in Dropbox when you upload files into them. So you could just go straight to the $dropbox->putFile() call and skip checking for the folder and creating it if it doesn't already exist.
If I have a file called file.html how do i make 10 clones of this file via PHP such that they are renamed file1....file10?
$filename = 'file.html'
$copyname = 'file2.html'
if ($file = #fopen($copyname, 'x')) {
// We've successfully created a file, so it's ours. We'll close
// our handle.
if (!#fclose($file)) {
// There was some problem with our file handle.
return false;
}
// Now we copy over the file we created.
if (!#copy($filename, $copyname)) {
// The copy failed, even though we own the file, so we'll clean
// up by itrying to remove the file and report failure.
unlink($copyname);
return false;
}
return true;
}
Small file approach: this allows you to do something with the contents of the file before saving it:
$text = file_get_contents('file.html');
for($i = 0; $i < 100; $i++) {
file_put_contents('file'.$i.'.html', $data);
}
Bigger files approach: this does not allow you to access the contents of the file before saving it, it only tells the underlying OS to make the copy (equivalent to a linux bash command of cp file.html file1.html):
for($i = 0; $i < 100; $i++) {
copy('file.html', 'file'.$i.'.html');
}
Just run your code in a loop:
$filename = 'file.html'
for($i=1; $i<=10; $i++) {
$copyname = "file$i.html";
copy($filename, $copyname);
}
Feel free to add error checking and handling.
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?