/    Sign up×
Community /Pin to ProfileBookmark

Need Help with php upload

Hi,

I am new with php, got this code to upload files but i need help with creating
a display a download link (hides true file location) if the file has successfully uploaded.

[B]Upload Code:[/B]

[code=php]
<form action=”<?php echo $_SERVER[‘PHP_SELF’];?>” method=”post” enctype=”multipart/form-data” name=”file_upload”>
<input type=”file” name=”file” id=”file”>
<input type=”hidden” name=”execute” id=”execute”>
<input type=”submit” name=”Submit” id=”Submit” value=”Submit”>
</form>
<?php
if (isset($_POST[‘execute’])) {

$filename = $_FILES[“file”][“name”];
$file_basename = substr($filename, 0, strripos($filename, ‘.’));
$file_ext = substr($filename, strripos($filename, ‘.’));
$filesize = $_FILES[“file”][“size”];

if (($file_ext == “.jpg” || $file_ext == “.png” || $file_ext == “.zip” || $file_ext == “.rar” || $file_ext == “.gif” || $file_ext == “.pdf”) && ($filesize < 2500000)) {
$newfilename = md5(time() . $file_basename) . $file_ext;

if (file_exists(“upload/” . $newfilename)) {
$error = “You have already submitted this file.”;
} else {
move_uploaded_file($_FILES[“file”][“tmp_name”], “upload/” . $newfilename);
echo “File uploaded successfully.”;
}
} elseif (empty($file_basename)) {
$error = “Please select a file to upload.”;
} else {
$error = “Only jpg, png, zip, rar, gif and pdf files can be submitted.”;
unlink($_FILES[“file”][“tmp_name”]);
}
}
?>[/code]

Thanks!

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@hastxJun 26.2009 — in order to hide the true url there are a few options:

one is to set up URL rewriting on your server ...this basically takes long url and makes it to a short string.

Another solution is to maintain a database or text file which maps a number to a file location. your download link would look like
[code=html]<a href="download.php?file=23415">Download this file</a>[/code]

An easy way to simply not show the upload dir (though not very secure, at least it wont display the directory) , is just dont display the uploads directory and hard code it into the download script...Your URL:
[code=html]<a href="download.php?file=myFileName_3123.jpg">Download this file</a>[/code]
download.php would look like this:
[code=php]
$fileDir = 'uploads';//The path to the dir containing the uploads
$file = $_GET['file'];//The name passed from the URL
$filename = $fileDir . '/' . $file;//The full path to the file

$save_as = $file; // this is the name the user sees. you could rename the file to "myjpg.jpg" if you want and that is what the user would save as
$file_size = filesize("$filename");
$c_type = 'image/jpeg'; //what mime is the file?
if ($fp = fopen("$filename", 'rb')) {

Header('Content-Type: '. $c_type); // this depends on file type!!!
Header('Content-Disposition: attachment; filename="'.$save_as.'"');
Header('Content-Length: '.$file_size);
fpassthru($fp);
} else {
echo"cannot find file";
}
[/code]

This method would create an invisible file pass-thru and never actually display the location of the file to the user.
Copy linkTweet thisAlerts:
@YooNetauthorJun 27.2009 — Hi hastx,

Thanks for the advice, is there a way to protect this so that users wont hotlink the direct download?

Thank again ?
Copy linkTweet thisAlerts:
@hastxJun 27.2009 — An easy way to do that would be to test the $_SERVER['HTTP_REFERER'] variable (http://us.php.net/manual/en/reserved.variables.server.php) at the beginning of your download.php script...if the referer is not the page containing your download link ...the script exits before pushing the file.

Once again, it is not the most secure thing in the world, not ALL browsers will work with this method, and someone could defeat this protection if they really wanted to, but I have found it to be an easy way to help prevent leaches without inconveniencing the legitimate users on the common browsers. And this can be added with a couple lines of code.

Your other alternatives would be to implement a login or captcha system, which would take more work and make an extra step for the real users, but it is up to you to decide how secure you need to be.
Copy linkTweet thisAlerts:
@YooNetauthorJun 27.2009 — Hi, thanks again for the reply, i have found this file and going to test it soon, will tell you how it goes.

[code=php]<?php

###############################################################
# File Download 1.3
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
###############################################################
# Sample call:
# download.php?f=phptutorial.zip
#
# Sample call (browser will try to save with new file name):
# download.php?f=phptutorial.zip&fc=php123tutorial.zip
###############################################################

// Allow direct file download (hotlinking)?
// Empty - allow hotlinking
// If set to nonempty value (Example: example.com) will only allow downloads when referrer contains this text
define('ALLOWED_REFERRER', '');

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. "/" )
define('BASE_DIR','/home/user/downloads/');

// log downloads? true/false
define('LOG_DOWNLOADS',true);

// log file name
define('LOG_FILE','downloads.log');

// Allowed extensions list in format 'extension' => 'mime type'
// If myme type is set to empty string then script will try to detect mime type
// itself, which would only work if you have Mimetype or Fileinfo extensions
// installed on server.
$allowed_ext = array (

// archives
'zip' => 'application/zip',

// documents
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',

// executables
'exe' => 'application/octet-stream',

// images
'gif' => 'image/gif',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',

// audio
'mp3' => 'audio/mpeg',
'wav' => 'audio/x-wav',

// video
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo'
);



####################################################################
### DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if (ALLOWED_REFERRER !== ''
&& (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)
) {
die("Internal server error. Please contact system administrator.");
}

// Make sure program execution doesn't time out
// Set maximum script execution time in seconds (0 means no limit)
set_time_limit(0);

if (!isset($_GET['f']) || empty($_GET['f'])) {
die("Please specify file name for download.");
}

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($_GET['f']);

// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

$dir = opendir($dirname);

while ($file = readdir($dir)) {
if (empty($file_path) && $file != '.' && $file != '..') {
if (is_dir($dirname.'/'.$file)) {
find_file($dirname.'/'.$file, $fname, $file_path);
}
else {
if (file_exists($dirname.'/'.$fname)) {
$file_path = $dirname.'/'.$fname;
return;
}
}
}
}

} // find_file

// get full file path (including subfolders)
$file_path = '';
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
die("File does not exist. Make sure you specified correct file name.");
}

// file size in bytes
$fsize = filesize($file_path);

// file extension
$fext = strtolower(substr(strrchr($fname,"."),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
die("Not allowed file type.");
}

// get mime type
if ($allowed_ext[$fext] == '') {
$mtype = '';
// mime type is not set, get from server settings
if (function_exists('mime_content_type')) {
$mtype = mime_content_type($file_path);
}
else if (function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME); // return mime type
$mtype = finfo_file($finfo, $file_path);
finfo_close($finfo);

}
if ($mtype == '') {
$mtype = "application/force-download";
}
}
else {
// get mime type defined by admin
$mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET['fc']) || empty($_GET['fc'])) {
$asfname = $fname;
}
else {
// remove some bad chars
$asfname = str_replace(array('"',"'",'\','/'), '', $_GET['fc']);
if ($asfname === '') $asfname = 'NoName';
}

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename="$asfname"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
while(!feof($file)) {
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
@fclose($file);
die();
}
}
@fclose($file);
}

// log downloads
if (!LOG_DOWNLOADS) die();

$f = @fopen(LOG_FILE, 'a+');
if ($f) {
@fputs($f, date("m.d.Y g:ia")." ".$_SERVER['REMOTE_ADDR']." ".$fname."n");
@fclose($f);
}

?>/PHP]
×

Success!

Help @YooNet spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...