Jump to content

PHP MySQL query fail


n0sferatu

Recommended Posts

Hey there,

 

I'm trying to set up a file sharing upload/download script locally in php.

I have everthing set up, up to the point where, when I'm trying to download a file I get the following error:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\XXX\inc\mdb.php on line 28
EXPIRED

I searched the www to figure out a solution and I understand that I get the error because one of the MySQL queries fails and it returns a boolean value, however I don't understand which and what I need to change it..

 

The following snippet is from the mdb.php line 28:

    function rowCount()
    {

        return mysql_num_rows($this->_Result);
    }
}

I know this is of no help, so the following code is from the main php download script:

<?php
if(!defined('CORE'))
    exit(0);
    
if(isset($_GET['code']))
{
    $rs = $Core->DB->query('SELECT * FROM tickets WHERE code=\''.$Core->DB->esc($_GET['code']).'\' AND ready=1 LIMIT 1');
    if($rs->rowCount() > 0)
    {
        $row = $rs->getAssoc();
        $rs = $Core->DB->query('SELECT * FROM uploads WHERE id='.intval($row['fid']).' LIMIT 1');
        if($rs->rowCount() > 0)
        {
            $finfo = $rs->getAssoc();
            if(file_exists('uploads/' . $finfo['code']))
            {
                $fpath = 'uploads/' . $finfo['code'];
                header('Content-Description: File Transfer');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Expires: 0');
                header('Content-Disposition: attachment; filename="'.basename($finfo['fname']).'"');
                header('Content-Transfer-Encoding: binary');
                header('Content-Length: '.filesize($fpath));
                readfile($fpath);
            }
            $Core->DB->query('DELETE FROM tickets WHERE id='.$row['id'].' LIMIT 1');
            $Core->end();
        }
        
    }
    else
        echo 'EXPIRED';
}

$Core->end();
?>

The error page I get when clicking download also contains "Expired" so I understand that it's because the if clause from the function fails, but I don't understand where or what is wrong.

The MySQL database has 3 tables: "tickets" "uploads" "users"

 

If I didn't provided enough info to get help, please let me know and I shall follow up with more.

 

 

Just as a heads up, the script isn't mine and I have no idea what I am doing as I don't know php or MySQL. Please be patient with me.

Link to comment
Share on other sites

Ok, that's embarrassing; I think the issue was that the variable that defined the path to the upload folder was was wrong.

 

The issue is now, that once I try the download link, it shows me the folder with all the uploaded files in it.

I have attached a screenshot.

To be more explicit, the download link, doesn't download the file, but it shows me the whole uploads folder.

 

I would kindly appreciate your help and sorry for the post above.

 

2qvqeix.jpg

Edited by n0sferatu
Link to comment
Share on other sites

You would need to show us the code that is making the download link itself.  Based on what your download script needs, sounds like it's not getting a "code" in the url, simple guess without the rest of your code.

 

Or this is failing too

 $rs = $Core->DB->query('SELECT * FROM uploads WHERE id='.intval($row['fid']).' LIMIT 1');

So the browser doesn't know to send it to the download screen popup

Edited by fastsol
Link to comment
Share on other sites

Thank you so much for the reply.

 

 

So I have a js script handling the upload events and a simple php upload script, both that you can find below. However, I can't seen to find anything of use in these.

function swfUploadPreLoad() {
	var self = this;
	var loading = function () {
		//document.getElementById("divSWFUploadUI").style.display = "none";
		document.getElementById("divLoadingContent").style.display = "";

		var longLoad = function () {
			document.getElementById("divLoadingContent").style.display = "none";
			document.getElementById("divLongLoading").style.display = "";
		};
		this.customSettings.loadingTimeout = setTimeout(function () {
				longLoad.call(self)
			},
			15 * 1000
		);
	};
	
	this.customSettings.loadingTimeout = setTimeout(function () {
			loading.call(self);
		},
		1*1000
	);
}
function swfUploadLoaded() {
	var self = this;
	clearTimeout(this.customSettings.loadingTimeout);
	//document.getElementById("divSWFUploadUI").style.visibility = "visible";
	//document.getElementById("divSWFUploadUI").style.display = "block";
	document.getElementById("divLoadingContent").style.display = "none";
	document.getElementById("divLongLoading").style.display = "none";
	document.getElementById("divAlternateContent").style.display = "none";
	
	//document.getElementById("btnBrowse").onclick = function () { self.selectFiles(); };
	document.getElementById("btnCancel").onclick = function () { self.cancelQueue(); };
}
   
function swfUploadLoadFailed() {
	clearTimeout(this.customSettings.loadingTimeout);
	//document.getElementById("divSWFUploadUI").style.display = "none";
	document.getElementById("divLoadingContent").style.display = "none";
	document.getElementById("divLongLoading").style.display = "none";
	document.getElementById("divAlternateContent").style.display = "";
}
   
   
function fileQueued(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Pending...");
		progress.toggleCancel(true, this);
		var objs = document.getElementById('divSWFUploadUI').getElementsByTagName('object');
		//objs[0].style.visibility = 'hidden';
		

	} catch (ex) {
		this.debug(ex);
	}


}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		 */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Uploading...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Uploading... " + percent + "%");
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		if(serverData.substring(0,9) == 'FILEINFO:')
		{
			var r = serverData.substring(9);
			var p = r.split('|');
			var div = document.createElement('DIV');
			div.innerHTML = '<h2>' + p[1] + '</h2><span class="label">URL to Download:</span><br /><input type="text" name="file" class="text" onclick="javascript:this.focus(); this.select();" value="' + p[2] + '/#download_' + p[0] + '" />';
			document.getElementById('completed').appendChild(div);
		}
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);

	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file)
{
	if (this.getStats().files_queued === 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = true;
	}
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	var status = document.getElementById("divStatus");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}

The php script

<?php
if(!defined('CORE'))
	exit(0);
	
if(isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']))
{
	if($Core->checkLogin())
		$uid = $Core->V['user']['id'];
	else
		$uid = 0;
	$code = md5(rand(1111,9999) . date('YmdHis'));
	$fname = basename($_FILES['Filedata']['name']);
	$Core->DB->query('INSERT INTO uploads (uid,fname,description,password,code) VALUES ('.$uid.',\''.$Core->DB->esc($fname).'\',\'\',\'\',\''.$code.'\')');
	$insertId = $Core->DB->insertId();
	
	if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], 'uploads/' . $code))
	{
		$Core->DB->query('DELETE FROM uploads WHERE id='.$insertId.' LIMIT 1');
	}
	
	$_SESSION['upload'] = array('fname' => $fname, 'code' => $code);
	
	echo 'FILEINFO:'.$code.'|'.$fname.'|'.$Conf['docUrl'];
	$Core->end();
}

$Core->redirect('./#home');	
?>

After I upload something, the script changes the name of the file uploaded using md5 and saves it in the uploads folder; after that it generates a link like the one below, "a3cf448cad2c1240931ce9427581fdf2" being the uploaded filename. but if I access the URL, it shows the entire uploads folder.

http://localhost/XXX/uploads/#download_a3cf448cad2c1240931ce9427581fdf2

Would it be easier if I zipped the whole project and attached it here? or is there a way to find the snippet of code handling this?

Sorry, if I'm not of very much help.

Link to comment
Share on other sites

The link generated takes the client to a download page with a timer, after the timers reaches 0, the following download link is available:

http://localhost/fileit/?exec=download&code=ad7372e30da67e8bf24dd9072d343d3a

If I modify in the script, the path to the uploads folder to point wrong, after I upload a file, then I get to the step where the timer goes off and generates the download link.

If I use the right path to the uploads folder, after I upload a file and access the below link, it just shows the uploads folder and doesn't reach the page with the timer:

http://localhost/fileit/uploads/#download_e13bee660f33e35a2a84147dfa559c9a

The timer snippet code

<?php
if(!defined('CORE'))
	exit(0);
	
if(isset($_GET['id']))
{
	$rs = $Core->DB->query('SELECT *, (dt - NOW()) AS countdown FROM tickets WHERE id='.intval($_GET['id']).' LIMIT 1');
	if($rs->rowCount() > 0)
	{
		$row = $rs->getAssoc();
		if($row['countdown'] < 1)
		{
			$rs = $Core->DB->query('SELECT * FROM uploads WHERE id='.intval($row['fid']).' LIMIT 1');
			if($rs->rowCount() > 0)
			{
				$finfo = $rs->getAssoc();
				$Core->DB->query('UPDATE tickets SET ready=1 WHERE id='.$row['id'].' LIMIT 1');
				echo '<a href="?exec=download&code='.$row['code'].'">DOWNLOAD</a>';
			}
		}
		else
			echo number_format($row['countdown'],0);
	}
	else
		echo 'EXPIRED';
}

$Core->end();
?>
Edited by n0sferatu
Link to comment
Share on other sites

Sorry for so many replies.

 

I also found the script that has the countdown function and generates the link.

<?php
if(!defined('CORE'))
	exit(0);
	
$rs = $Core->DB->query('SELECT * FROM uploads WHERE code=\''.$Core->DB->esc($params[1]).'\' LIMIT 1');
if($rs->rowCount() < 1)
{
	echo '<div class="error">Invalid or deleted file.</div>';
	return;
}
$row = $rs->getAssoc();

$code = md5(rand(1111,9999) . date('YmdHis'));

$Core->DB->query('INSERT INTO tickets (fid,code,dt,expires) VALUES ('.intval($row['id']).',\''.$code.'\',DATE_ADD(NOW(), INTERVAL 5 SECOND), DATE_ADD(NOW(), INTERVAL 15 SECOND))');
$insertId = $Core->DB->insertId();

$js = <<<JS

Global.doCountdown = function()
{
	var _self = this;
	var countdown = document.getElementById('countdown');
	if(!countdown)
		return;
	if(!this.XC)
		this.XC = new CXH();
	this.XC.reinit();
	this.XC.setCallback(function()
	{
		if(_self.XC.XH.readyState == 4 || _self.XC.XH.readyState == 'complete')
		{
			var r = _self.XC.XH.responseText;
			document.getElementById('countdown').innerHTML = r;
		}
	});
	this.XC.load('?exec=timer&id={$insertId}', 'GET');
	setTimeout(function() { _self.doCountdown(); }, 500);
};

Global.doCountdown();

this.style.display = 'none';

JS;

jspack($js);
	
echo <<<HTML

<h1>Downloading {$row['fname']}</h1>
<div id="countdown"></div>
<img src="images/loading.gif" border="0" alt="" onload="javascript:{$js}" />
HTML;

?>

The issue is, that it should load when I access "http://localhost/fileit/uploads/#download_file" and generate "http://localhost/fileit/?exec=download&code=file"

Link to comment
Share on other sites

Does your DB wrapper class have a mysql_error() function it can return the error for you?  I appears the first query on the download page is failing or the query on the timer page.  It's hard to tell cause you have EXPIRED echo out in 2 places in the scripts so I don't know which page the query is failing from.

Link to comment
Share on other sites

Hey,

 

I no longer get echo "Expired" from the using the script; I would get this error when the path to the uploads folder is wrong.

 

WIth the correct path, the page generates a link that should take me to a page with a timer that generates the download link:

First link:

http://localhost/fileit/uploads/#download_md5file

The client should access the link above and reach the download page with a timer and a download link like this:

http://localhost/fileit/uploads/?exec=download&code=md5file

But when you click on the first link, it shows the all the files from the uploads folder.

 

If by anychance you or anyone else could spare 5 min of their time to run the script locally.

Just create a database and modify etc/config.php with the credentials and then run from the browser install.php that should create the tables and colums for you.

 

Then if you try and upload something you can check out the behavior.

http://sharesend.com/ydtwbg4k
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.