Jump to content

Major Issues ...


Smudly

Recommended Posts

Hi, I am having some major issues.

My site provides sheet music available for downloading for free. When a user clicks on a sheet to download, a new window opens up. This user views our sponsor's website for 30 seconds. Once the time is up, they can download the free sheet.

 

Now for the issues:

 

I found a download script that I'm putting to the test. When clicking download, it asks where you want to save the file and downloads the file just fine. After some testing, i found that if the user tries to download the sheet again, my entire php/html code displays on the page, as well as a bunch of nonreadable characters (I'm guessing this is from the .pdf file that is supposed to be downloaded).

 

I need to modify my code to stop this from happening. I've tried to exit() the code or die() after the sheet downloads, but I must be doing it wrong because nothing seems to work. I also tried a redirect to send them to a different page once they download the file. That doesn't work either.

 

The next issue is the bottom page is supposed to display our sponsor's website, which it does. However, the frame that contains the website is not 100% in height as it is specified to be. Something in my code is causing it to stop extending all the way.

 

If you would like to see exactly what is happening for yourself, you can go here:

http://www.sheetmusichaven.com/download.php?sheet=98%20Degrees-I%20Do%20Cherish%20You-SheetMusicHaven.pdf&artist=98%20Degrees&title=I%20Do%20Cherish%20You

 

I'm using the latest version of Firefox, PHP 5.

 

And for the code. I warn you it is ugly ><

 

<?php
session_start();

include_once('inc/connect.php');

$sheet = $_GET['sheet'];
$artist = stripslashes($_GET['artist']);
$title = stripslashes($_GET['title']);
$hyphen = " - ";
$url = "http://www.youtube.com";
$timetodownload = $_POST['timetodownload'];

$todayquery = mysql_query("SELECT `todayviews` FROM `websites` WHERE `active`='yes'");
$todayresult = mysql_fetch_assoc($todayquery);

$todayviews = $todayresult['todayviews'];

$result = mysql_query("SELECT `url` FROM `websites` WHERE `active`='yes' && `dailyviews`>'$todayviews' && `credits`>0");
$i = 0;
while($row = mysql_fetch_array($result))
  {
    
    while($i<1){
    
    $url = $row['url'];    
    $i++;
    
    }
  
  }


if(strlen($artist)+strlen($title)>80){
    $artist = "";
    $hyphen = "";
}
$ip = $_SERVER['REMOTE_ADDR'];
// Time Goes Here

// $ipcheck = mysql_query("SELECT ip FROM downloading WHERE ip='$ip'");
// $ipcount = mysql_num_rows($ipcheck);

// if ($ipcount!=0)
// {
// $error1 = "<div id='regerror'>Username already taken!</div>";
// }

// $ipquery = "INSERT INTO downloading VALUES ('','$ip','$time')";
// mysql_query($ipquery);

$timesdownloaded = 0;
if(isset($timetodownload)&&$timesdownloaded<1){
###############################################################
# File Download 1.31
###############################################################
# 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','admin/uploads/');

// 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',
  
  // images
  'gif' => 'image/gif',
  'png' => 'image/png',
  'jpg' => 'image/jpeg',
  'jpeg' => 'image/jpeg',
);



####################################################################
###  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($sheet) || empty($sheet)) {
  die("Please specify file name for download.");
}

// Nullbyte hack fix
if (strpos($sheet, "\0") !== FALSE) die('');

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

// 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*);
    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);
  
}


    $timesdownloaded++;
    if(isset($timetodownload)==($_POST['timetodownload'])){
    $timetodownload = "";
    echo "<meta http-equiv=\"refresh\" content=\"0;url=index.php?letter=0\">";
    }
    if($timesdownloaded>0){
        header("Location: index.php");
    }
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Free Piano Sheet Music - Sheet Music Haven" />
<meta name="keywords" content="free,piano,sheet,music,download,keyboard,haven,lyrics,notes,chords,score,top,modern,popular,jazz,classical,sheetmusichaven" />
<meta name="author" content="Sheet Music Haven - Free Piano Sheet Music. Download all types of piano sheet music for free. Popular sheets are added often" />
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />
<title>Downloading <?php echo $sheet; ?> - Sheet Music Haven</title>
<link rel="stylesheet" type="text/css" href="styles/style.css" />
<style>
iframe {
padding: 0px;
spacing: 0px;
}

body{
    margin: 0px;
    color: #000000;

}
#bggreen{
    width: 99%;
    height: 88%;
    background-color: #6aa504;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}
#countdown{
    color: #4296ce;
    font-size: 18px;
        
}

.sheetbar a{color: #000000;
         font-family: "Arial", Helvetica, sans-serif;
         }
#logo{
    position: relative;
    width: 320px;
    height: 65px;
    text-align: center;
    float: left;
    top: 19px;
}
#timer{
    position: relative;
    width: 65%;
    height: 59px;
    float: left;
    text-align: center;
    top: 3px;
    background-color: #ececec;
    border-style: solid;
    border-color: #93DB70;
}
</style>
<script type="text/javascript">

var time = 2;

function startCountdown(){
    var t = setTimeout("countdown()", 1000);
}

function countdown(){
var sHeet = "<?php echo $sheet;?>";
var artist = "<?php echo $artist;?>";
var tItle = "<?php echo $title;?>";

    --time;
    if(time == 0){
        document.getElementById("countdown").innerHTML = "<form action='download.php?sheet=<?php echo $sheet; ?>' method='POST'><input type='image' src='img/download.png' alt='Download' name='timetodownload' value='Download'><\/form>";

    }else{
        document.getElementById("countdown").innerHTML = time;
        var t = setTimeout('countdown()', 1000);
    }
}
</script>
</head>
<body onload="startCountdown();" bgcolor="#343331">

<table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0">
<?php

echo "<tr><td style='background:#343331;height:80px;border-bottom:#aaaaaa solid 2px;'>";

echo "<div id='bggreen' class='sheetbar'>
<div id='logo'><a href='index.php'><img src='img/logosmall.png'></a><br />
    <a href='suggestions.php' style='color: #ececec; font-size: 14px;'>Report Errors</a></div>
<div id='timer'>
It is our sponsor's that keep this website running. Please view their website while you wait for:<br />
<span style='color: #6aa504;'>".ucwords($artist).$hyphen.ucwords($title)."</span>
<br />
<div id='countdown'>2</div>
</div>
</div>".$error;
echo "</td></tr>";
?>

<tr><td>
<iframe src="<?php echo $url;?>" width="100%" height="100%" frameborder="0" marginwidth="0" marginheight="0">
  <p>Your browser does not support iframes.</p>
</iframe>
</td></tr>

</table>

</body>
</html>

Link to comment
Share on other sites

I cannot really tell what's going on... I tried your URL and cannot even get the download to open -> javascript errors IE8

 

If I were you, I would write my own script to force downloads... 

 

use to force the $file_contents as a download

header('Content-Disposition: attachment; filename='.basename($file_path));

 

Use W3C Validator like Pika suggests to fix those layout issues.!

Link to comment
Share on other sites

I wrote this script awhile back for someone at my workplace... It never got used, so here you go...

Play around and i!research!i the headers I provide by have commented out for different http directives...

 

<?php
// gfile.php

// February 3, 2010

if ( isset($_GET['file']) ){
//save the file alias as a local variable
$file_alias = $_GET['file'];
}else{
//no file alias was specified; produce error
echo "<b>gfile.php: Insufficient Parameters</b><br />Please contact <a href=\"youman@youserver.com\">Someone</a>";
die; //error; kill script
}



switch ( $file_alias ) {
// Here you can add file aliases and paths - pretty self explanatory
//-------------------------------------------------------------
case 'testfile':
	$file_path = '/home/you/testfssile1.txt';
	$is_file_html = false;
	break;
case 'report':
	$file_path = '/home/you/cfmcreport.html';
	$is_file_html = true;
	break;
case 'csvfile':
	$file_path = '/home/you/comma.csv';
	$is_file_html = false;
	break;
//-------------------------------------------------------------
default:	
	//file_alias failed to pair with a definite file; print generic error
	print_generic_error();
	die; //error; kill script
}

//i use @ in front of the file_get_contents to tell PHP not to print any error's or warnings
//because warning messages are very specific and i just want to use my own generic message
if ( !$file_contents = @file_get_contents($file_path) ) {
// this expression didn't resolve; the file doesn't exist, the permissions are not set correctly, or something!
// IF YOU CANT FIGURE OUT WHY, YOU CAN ALWAYS REMOVE @ FOR A MORE SPECIFIC REASON WHY PHP COULDNT OPEN THE FILE
print_generic_error();
die;
}


//header('Content-Description: File Transfer');
//header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file_path));
//header('Content-Transfer-Encoding: ascii');
//header('Expires: 0');
//header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
//header('Pragma: public');
//header('Content-Length: ' . filesize($file_path));

//these headers tell the browser what type of content we are displaying
//used to maintain formatting of plain text documents when being displayed in the browser

/*if ( $is_file_html ) { //send proper header
header("Content-type: text/html");
}else{
header("Content-type: text/plain");
}*/

//send the contents to the browser
echo $file_contents;

//function to print the error message
function print_generic_error() {
echo "<b>gfile.php: File Inaccessible</b><br /><br />";
echo "This error can be attributed to the following reasons:";
echo "<ul><li>The file does not exist</li>";
echo "<li>You do not have the correct permissions</li>";
echo "<li>The system failed to properly open this file</li></ul>";
echo "Please contact <a href=\"youman@youserver.com\">Someone</a>";
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.