PHP File Upload Then Show Download link - php

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.

Related

PHP move_uploaded_file results in error #1

I try to upload a file to an external server based on this code: https://www.w3schools.com/php/php_file_upload.asp .
On my local machine everything works fine but when uploading the exact same script to an external server it won't work anymore. When debugging with:
$_FILES["fileToUpload"]["error"]
I get an Error #1 in return altough im running the same php.ini as on my local machine. The uploads/ folder exists and the user www-data has also permissions to write it. I proofed this by running file_put_contents("uploads/test.txt", "working");. The only thing I could think of is the PHP Version difference (Local: 7.2.5; External: 7.2.19) or maybe a missing php module?!
It would be great if someone could help me solving this.
Try with full path using $_SERVER['DOCUMENT_ROOT'] also try to create recursively your folders using mkdir with 3rd parameter set to true (if not exists your path), increments your upload_max_filesize as suggested by Andreas into comments... here is a pseudo working example...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="fileToUpload" name="fileToUpload">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/var/www/html/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if ((isset($_FILES['fileToUpload']['name'])) && (!empty($_FILES['fileToUpload']['name']))) {
$temp_name = $_FILES['fileToUpload']['tmp_name'];
$file_name = $_FILES['fileToUpload']['name'];
$file_path = $upload_dir.$file_name;
$upload_process = move_uploaded_file($temp_name, $file_path);
#chmod($file_path,0755);
}
if ((isset($upload_process)) && ($upload_process == TRUE)) {
echo "File Uploaded With Success...";
}
if ((!isset($upload_process)) || ($upload_process == FALSE)) {
echo "Please, Upload some File...";
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
I hope this helps.
OK, i was dumb. I changed the wrong php.ini file. For anyone who experiences similar issues you can check the location of the php.ini file and if it's loaded by PHP with:
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
Hope this helps.

Can I create a php script to act as FTP

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.

PHP can't upload files to server?

I have a php file that uploads images like jpegs and png onto a folder called uploads that is stored on the apache server and in the same location as the php file.
I have checked the code of both the HTML and the PHP and both seem to be perfectly fine, however whenever I try to upload a file I always get an error message and the file doesn't get uploaded.
It would be much appreciated if someone with more experience than me can look at my code and tell me why it is behaving in this manner.
Here is the HTML form:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your File</title>
</head>
<body>
<?php
// put your code here
?>
<form enctype="multipart/form-data" method="post" action="fileHandler.php">
Select File:
<input name="uploaded_file" type="file"/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
and here is the PHP file that is executed when the form is submitted:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* PHP file that uploads files and handles any errors that may occur
* when the file is being uploaded. Then places that file into the
* "uploads" directory. File cannot work is no "uploads" directory is created in the
* same directory as the function.
*/
$fileName = $_FILES["uploaded_file"]["name"];//the files name takes from the HTML form
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];//file in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"];//the type of file
$fileSize = $_FILES["uploaded_file"]["size"];//file size in bytes
$fileErrorMsg = $FILES["uploaded_file"]["error"];//0 for false and 1 for true
$target_path = "uploads/" . basename( $_FILES["uploaded_file"]["name"]);
echo "file name: $fileName </br> temp file location: $fileTmpLoc<br/> file type: $fileType<br/> file size: $fileSize<br/> file upload target: $target_path<br/> file error msg: $fileErrorMsg<br/>";
//START PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------
if(!$fileTmpLoc)//no file was chosen ie file = null
{
echo "ERROR: Please select a file before clicking submit button.";
exit();
}
else
if(!$fileSize > 16777215)//if file is > 16MB (Max size of MEDIUMBLOB)
{
echo "ERROR: Your file was larger than 16 Megabytes";
unlink($fileTmpLoc);//remove the uploaded file from the PHP folder
exit();
}
else
if(!preg_match("/\.(gif|jpg|jpeg|png)$/i", $fileName))//this codition allows only the type of files listed to be uploaded
{
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
exit();
}
else
if($fileErrorMsg == 1)//if file uploaded error key = 1 ie is true
{
echo "ERROR: An error occured while processing the file. Please try again.";
exit();
}
//END PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------------------------
//Place it into your "uploads" folder using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, $target_path);
//Check to make sure the result is true before continuing
if($moveResult != true)
{
echo "ERROR: File not uploaded. Please Try again.";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
}
else
{
//Display to the page so you see what is happening
echo "The file named <strong>$fileName</strong> uploaded successfully.<br/><br/>";
echo "It is <strong>$fileSize</strong> bytes.<br/><br/>";
echo "It is a <strong>$fileType</strong> type of file.<br/><br/>";
echo "The Error Message output for this upload is: $fileErrorMsg";
}
?>
make sure that the directory structure has write permissions. You can check within php by using is_writeable. By checking from within PHP you will also be making sure that the PHP user has write access.
Check the folder permissions on the server. If incorrect, you can modify your php.ini file.

PHP File Upload using url parameters

Is there a way to upload a file to server using php and the filename in a parameter (instead using a submit form), something like this:
myserver/upload.php?file=c:\example.txt
Im using a local server, so i dont have problems with filesize limit or upload function, and i have a code to upload file using a form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="fileForm" enctype="multipart/form-data">
File to upload:
<table>
<tr><td><input name="upfile" type="file"></td></tr>
<tr><td><input type="submit" name="submitBtn" value="Upload"></td></tr>
</table>
</form>
<?php
if (isset($_POST['submitBtn'])){
// Define the upload location
$target_path = "c:\\";
// Create the file name with path
$target_path = $target_path . basename( $_FILES['upfile']['name']);
// Try to move the file from the temporay directory to the defined.
if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['upfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
</body>
Thanks for the help
Image Upload Via url:
//check
$url = "http://theonlytutorials.com/wp-content/uploads/2014/05/blog-logo1.png";
$name = basename($url);
try {
$files = file_get_contents($url);
if ($files) {
$stored_name = time() . $name;
file_put_contents("assets/images/product/$stored_name", $files);
}
}catch (Exception $e){
}
If you're doing this localy do you have the need to use "upload" mechanisms? otherwise if you're sending something externaly you could use cURL to upload the file, and run the PHP script on the CLI, quick google: http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html
if you want to use url to send the name of the file like below:
www.website.com/upload.php?hilton_plaza_party.jpg
There is a script to do that. Here: http://valums.com/ajax-upload/

Upload file to database through php code

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!

Categories