I have a php script I'm using to upload zip files to my ftp and automatically unzip them.
I wonder if there is a finished php script to delete folders and files on my ftp.
Reason I'm asking is because I save so much time doing the zip upload and unzip process instead of unzipping locally and then upload the files.
So now my problem is that it takes quite allot of time to delete folders and files using Filezilla and I want to speed that up.
Anyone with a working solution?
Edit:
Here is my unzip code that I'm using:
<?php
/* Simple script to upload a zip file to the webserver and have it unzipped
Saves tons of time, think only of uploading Wordpress to the server
Thanks to c.bavota (www.bavotasan.com)
I have modified the script a little to make it more convenient
Modified by: Johan van de Merwe (12.02.2013)
*/
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = dirname(__FILE__).'/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Unzip a zip file to the webserver</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
I don't mean to plug my own work here but there is a script I am selling on a website called Code Canyon called MightyFTP that wraps the complex procedural php ftp functionality into a much simpler OO API.
As far as I am aware deleting a folder requires recursive deletion via the current FTP API so there is little bit of work involved normally.
A link to the script is here "http://codecanyon.net/item/mightyftp/8276375"
If you had my code and you wanted to delete an ftp folder the code to do it is very straight forward as demonstrated below.
require_once("MightyFTP/FTPClient.php");
$myFtpClient = new MightyFTP\FTPClient("yourftpserver", new MightyFTP\FTPCredentials("yourftpusername", "yourftppassword"));
$ftpDirectoryToDelete = $myFtpClient->getFile("/PathToDirectory/");
$parentDir = $ftpDirectoryToDelete->delete(); //The directory and all its children have been deleted. It will then return the parent of the deleted file/folder.
$ftpDirectoryToDelete->rename(""); //Will throw an exception because you will not be able to run an operation on a file/directory that no longer exists.
Related
I'm trying to build a basic upload form to add multiple files to a folder, which is processed by PHP.
The HTML code I have is:
<form id="form" action="add-files-php.php" method="POST" enctype="multipart/form-data">
<div class="addSection">Files To Add:<br><input type="file" name="files[]" multiple /></div>
<div class="addSection"><input type="submit" name="submit" value="Add Files" /></div>
</form>
And the PHP to process is:
$file_path = "../a/files/article-files/$year/$month/";
foreach ($_FILES['files']['files'] as $file) {
move_uploaded_file($_FILES["file"]["name"],"$file_path");
}
I can run the PHP without any errors, but the files don't get added to the path folder.
Where am I going wrong with this?
I have a similar code actually in one of my projects. Try it.
foreach ($_FILES['files']['name'] as $f => $name) {
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path);
}
Look at the following page:
http://php.net/manual/en/function.move-uploaded-file.php
EDIT:
Nowhere in the code you provided, does it show that you actually give your file a filename, you simply refer to a path, rather than a path+filename+extension
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path . $name);
modifying my original code sample to be like the second one, should work.
Iterate the $_FILES['files']['error'] array and check if the files are actually uploaded to the server:
$dest_dir = "../a/files/article-files/$year/$month";
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// The temporary filename of the file stored on the server
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$name = basename($_FILES["files"]["name"][$key]);
// Handle possible failure of the move_uploaded_file() function, too!
if (! move_uploaded_file($tmp_name, "$dest_dir/$name")) {
trigger_error("Failed to move $tmp_name to $dest_dir/$name",
E_USER_WARNING);
}
} else {
// Handle upload error
trigger_error("Upload failed, key: $key, error: $error",
E_USER_WARNING);
}
}
The biggest issue with your code is that you are trying to move $_FILES['files']['name'] instead of $_FILES['files']['tmp_name']. The latter is a file name of temporary file uploaded into the temporary directory used for storing files when doing file upload.
P.S.
Using relative paths is error-prone. Consider using absolute paths with the help of a constant containing path to the project root, e.g.:
config.php
<?php
define('MY_PROJECT_ROOT', __DIR__);
upload.php
<?php
require_once '../some/path/to/project/root/config.php';
$dest_dir = MY_PROJECT_ROOT . "/a/files/article-files/$year/$month";
I am pulling my hair out over here. I have spent the last week trying to figure out why the ZipArchive extractTo method behaves differently on linux than on our test server (WAMP).
Below is the most basic example of the problem. I simply need to extract a zip that has the following structure:
my-zip-file.zip
-username01
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
-username02
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
The following code will extract the root zip file and keep the structure on my WAMP server. I do not need to worry about extracting the subfolders yet.
<?php
if(isset($_FILES["zip_file"]["name"])) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$errors = array();
$name = explode(".", $filename);
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$errors[] = "The file you are trying to upload is not a .zip file. Please try again.";
}
$zip = new ZipArchive();
if($zip->open($source) === FALSE)
{
$errors[]= "Failed to open zip file.";
}
if(empty($errors))
{
$zip->extractTo("./uploads");
$zip->close();
$errors[] = "Zip file successfully extracted! <br />";
}
}
?>
The output from the script above on WAMP extracts it correctly (keeping the file structure).
When I run this on our live server the output looks like this:
--username01\filename01.txt
--username01\images.zip
--username01\songs.zip
--username02\filename01.txt
--username02\images.zip
--username02\songs.zip
I cannot figure out why it behaves differently on the live server. Any help will be GREATLY appreciated!
To fix the file paths you can iterate over all extracted files and move them.
Supposing inside your loop over all extracted files you have a variable $source containing the file path (e.g. username01\filename01.txt) you can do the following:
// Get a string with the correct file path
$target = str_replace('\\', '/', $source);
// Create the directory structure to hold the new file
$dir = dirname($target);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Move the file to the correct path.
rename($source, $target);
Edit
You should check for a backslash in the file name before executing the logic above. With the iterator, your code should look something like this:
// Assuming the same directory in your code sample.
$dir = new DirectoryIterator('./uploads');
foreach ($dir as $fileinfo) {
if (
$fileinfo->isFile()
&& strpos($fileinfo->getFilename(), '\\') !== false // Checking for a backslash
) {
$source = $fileinfo->getPathname();
// Do the magic, A.K.A. paste the code above
}
}
i have upload script which does the job for uploading in usual way like browse the file from computer and upload but i want to convert the existing script to upload from url.for example if i paste the url which is direct link of video file it should be uploaded to my server. i can use php copy method and feof to do the job but i want to do with my existing script as several other data are related to my uploading script i tried with above both method but its not working.
converting this code to accept remote url upload
<form enctype="multipart/form-data" id="form1" method="post" action="">
<p><label>Upload videos</label>
<input type="file" name="video">
<span>Only mp4 is accepted</span>
<input type="submit" value="Submit" class="button"></p>
if (!eregi(".mp4$",$_FILES['video']['name'])) {
die("Unavailable mp4 format");
}
$uri = save_file($_FILES['video'],array('mp4'));
function save_file($file) {
$allowed_ext = array('mp4');
$ext = $file['name'];
if (in_array($ext, $allowed_ext)) {
die('Sorry, the file type is incorrect:'.$file['name']);
}
$fname = date("H_i",time()).'_'.get_rand(3);
$dir = date("Ym",time());
$folder = 'uploads/userfiles/'.$dir;
$uri = $folder.'/'.$fname.'.'.$ext;
if (!is_dir($folder))
mkdir($folder, 0777);
if (copy($file['tmp_name'],$uri))
return $uri;
else {
return false;}}
?>
If you're getting a URL, you aren't getting a file upload so you can't just use a file upload script and wish it would work. Just use the copy() function to get the file from the URL and save it to your server.
You should use "http_get" to download files from another server.
$response = http_get($url);
I am using the simple script below to upload a zip file via php and then unzip it on my server.
The file will be a zipped folder. When the upload is complete I want to echo a link to the new folder.
So for instance if I upload a zip file containing a folder called "bar", after the success message I want to echo "http://foo.com/bar".
Any help much appreciated.
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed',
'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/foo.com/".$filename; // change this to the correct
site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/foo.com/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
Taking a quick glance over everything, I'd say
$message = "Your .zip file was uploaded and unpacked. Files";
from what I gather on your script your telling it to upload directly to the servers directory path of the domain. Appending $filename as the folder name to that path so it creates a folder as such accordingly. From that its hardcoding the domain like you would to any other link and then appending the same filename variable to the end of it so it shows the same folder you just uploaded to.
This is just my guess overall though again only taking a quick glance and all.
From a detailed look at your code, I would say that I can give a few comments:
1) You should use mkdir() to create a new directory in the uploads directory of your site (I assume it's the root in this case).
2) You don't need to move uploaded file before unzipping it. Simply unzip it into the newly created directory. Make sure there isn't already another directory with the same name. The uploaded file should be deleted automatically by PHP, so no need to unlink.
3) In reference to:
$name = explode(".", $filename);
What happens if the filename has more than one dot? You should really use substr() with strrpos() to get everything after the last dot.
4) After uploading, just echo the path http://www.yoursite.com/newdir - don't see the problem. If you can be more specific about what you are having difficulty with, please comment.
I have made an application to upload files and it's working out well. Now I want to upload my files on a database, and I also want to display the uploaded files names on my list by accessing the database.
So please help me do this. My code is given below:
function uploadFile() {
global $template;
//$this->UM_index = $this->session->getUserId();
switch($_REQUEST['cmd']){
case 'upload':
$filename = array();
//set upload directory
//$target_path = "F:" . '/uploaded/';
for($i=0;$i<count($_FILES['ad']['name']);$i++){
if($_FILES["ad"]["name"])
{
$filename = $_FILES["ad"]["name"][$i];
$source = $_FILES["ad"]["tmp_name"][$i];
$type = $_FILES["ad"]["type"];
$name = explode(".", $filename);
$accepted_types = array('text/html','application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type)
{
if($mime_type == $type)
{
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "F:" . '/uploaded/'.$filename;
// change this to the correct site path
if(move_uploaded_file($source, $target_path )) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("F:" . '/uploaded/'); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
echo "Your .zip file was uploaded and unpacked.";
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
break;
default:
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
//$this->assign_values('cmd','uploads');
$this->assign_values('cmd','upload');
}
}
my html page is
<html>
<link href="css/style.css" rel="stylesheet" type="text/css">
<!--<form action="{$path_site}{$index_file}" method="post" enctype="multipart/form-data">-->
<form action="index.php?menu=upload_file&cmd=upload" method="post" enctype="multipart/form-data">
<div id="main">
<div id="login">
<br />
<br />
Ad No 1:
<input type="file" name="ad[]" id="ad1" size="10" /> Image(.zip)<input type="file" name="ad[]" id="ad1" size="10" /> Sponsor By : <input type="text" name="ad3" id="ad1" size="25" />
<br />
<br />
</div>
</div>
</form>
</html>
Why not save the uploaded filename as a field in the db?
Looking at your code you have implemented the "Upload" you dont seem to be storing the file location into a database, you need to do the following:
On upload, store the details of the filename and path into a database table
To display these as a list - query the database, and write back to HTML page.
There are loads of examples of this on the internet, PHP.net is a good place to start.
If all you need to do is display the contents of a directory, then you can achieve a listing without the need of a database.
If you really need to upload onto the database you can use BLOBs (Binary Large Object) to achieve this:
See these links:
Wikipedia - Binary large object
MySQL - The BLOB and TEXT Types
PostgreSQL - Large Objects (BLOBs)
Also, rephrase your question!