Jump to content

Question about variable scope and a login form


capella07

Recommended Posts

Hi, all

 

I'm having trouble with a file upload script that has a login.

 

I got the upload script from phphq.net and integrated a login system to allow different users to login and upload to an assigned folder (which folder they are assigned to is set in the database and retrieved during login).

 

The login works fine, but I can't get the folder set right, which depends on what the user's assigned upload folder is set in the database.

 

The full script is attached. Looking at the script you can see that I set empty variables that hold the full url and folder, which are set after the user logs in because that will change depending on the assigned folder (as determined in the database) for that user.

 

As is, the files always upload to the same folder level as the script file.

 

I'd appreciate it if someone could take a look and help me out.

 

Thanks in advance!

 

 

[attachment deleted by admin]

Link to comment
Share on other sites

Hi capella07,

 

You probably don't have any responses as of yet because that PHP file is pretty long.  When you post shorter snippets of code (and generally using the

 tags) you may get a better response.

Either way:

I got a little confused with the code, though I was only quickly skimming over it.

As you mention, you start off declaring the variable and set it to an empty value:

[code=php:0]// Path to store files on your server. With trailing slash.
$folder = "";

 

I assume that the value of 'uploadFolder' in the 'users' table is set somewhere else within your application before this page.  Can you confirm that if you echo out your $row['uploadFolder'] that it displays the correct folder name and also echo out $folder to make sure that it does indeed display the value of:

 

"./uploads/" . $row['uploadFolder'] . "/"

 

(I can see that you have commented out an echo for this, so I am assuming this has already been checked, etc.)

 

If you (temporarily) change the upload path to a static one (e.g. just code the path you want an upload to go to), does it upload to the correct folder?  If it does go to the folder that you are trying to upload to when it is hard-coded AND the variable echos out as expected, then we can look into it from there. 

 

Hopefully someone else may have some better insight on this too hehe.

Link to comment
Share on other sites

capella, its not that the developers here dont wwant to help, you've attached a file, which includes other files in the script, it,will take some time to undertand it all. If you give an indication of whats suppose to happen at what line, it would be better.

 

Any way after loggin what is the value of the $folder and $full_url variables?

Link to comment
Share on other sites

Hi, jd

 

Point taken about the length of the code - that is a lot to digest. Thanks for braving it out, though!

 

To answer your question: Yes, if I give the $folder and $full_url variables actual values where I now set them as empty strings, the upload puts the file in the correct path.

 

Those echoes you mention that are right after the db query do return what I want (the folder name and the full url with the folder name added), but during the actual upload, the file gets put in the same folder as the php file itself. I've confirmed this by echoing those same variables when the uploading process happens.

 

syed: you just posted while I was writing this.

 

The variables $userName, $folder, $full_url, and $dbPassword are all empty after logging in.

 

Thanks, guys!

Link to comment
Share on other sites

Okay, I'm still trying to get this to work.

 

It was previously suggested that the code I provided was too long, so I'm posting a stripped down version that only includes the code relevant to the issue at hand - having trouble with variables being set in functions and not retaining their values.

 

On thing of note: Using echo statements for the variables all over the code has shown that it seems the after the line

header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

The variables are cleared, but it is after this point, when the file upload is processed and the folder values are important that the variables' values are needed.

 

Here's the code:

<?
include("../../secure/ipAllowed.php");

$password_form = "";
$userName = ""; // Comes from database and is used in logging the file upload
$folder = ""; // Path to store files
$full_url = ""; // Full browser-accessable URL
$password = "1"; // Must have a value to force the display of the login form

function checkPasswordInDb($enteredPassword) {

	require_once('../../secure/dbConnectFileUpload.php');
	$query = "SELECT uploadName, uploadPassword, uploadFolder FROM users WHERE uploadPassword = '$enteredPassword'";
	$result = @mysqli_query ($dbc, $query);

	if (mysqli_num_rows($result) == 1) {
		// The user entered a valid password

		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$dbPassword = $row['uploadPassword'];

		if ($dbPassword == $enteredPassword) {
			// User entered a password that is in the database
			$userName = $row['uploadName'];
			$folder = "./uploads/" . $row['uploadFolder'] . "/";
			$full_url = "http://www.example.com/FileUploader/uploads/" . $row['uploadFolder'] . "/";
			$password = $dbPassword;

			// The variables set here are empty when the IF statement is first entered and echo with the correct values after the variables are set
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
	mysqli_close($dbc);
}

// If the client IP address is not allowed, they must login to upload files
if(!ipAllowed($ip)) {

	if($_POST['verify_password'] == true) {

		if(checkPasswordInDb($_POST['check_password'])) {
			// User entered a password that matches one in the database

			// Echoing the variables $userName, $folder, $full_url, and $password still show their values as set in the checkPasswordInDb function

			setcookie("fileUploader", $password);
			header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
			exit;
		}
		else {
			echo '<script type="text/javascript">
				alert("Invalid password entered!");
			</script>';
		}
	}

	// Show the authentication form if the cookie (if any) doesn't match the password
	if($_COOKIE['fileUploader'] != $password) {
		// This is where the login form is built, putting the html code into the $password_form variable
	}
} // End If !ipAllowed

// Don't allow submit if $password_form hasn't been populated
if(($_POST['submit'] == true) AND ($password_form == "")) {

	// The actual file uploads are handled here

	if(($error == "") AND ($success == "")) {
		$error .= "<b>FAILED:</b> No files selected.<br />";
	}

	$display_message=$success.$error;

} // End $_POST AND !$password_form
?>
<!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>
	<title>File Uploader</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body>

	<div>

		<?php
		if($password_form) {

			echo $password_form;

		} else {
		// User entered a valid password - display the file upload form

		// The variables $userName, $folder, $full_url, and $password are set back to their original values (all empty strings except $password = 1)

		?>

		<form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" name="fileUploader">
			<!-- Form to allow file uploads -->
		</form>

		<?php
		} ?>
	</div>
</body>
</html>

 

It's still quite a bit, I know, but I'm not sure what else I can omit and still provide the info you guys need to help me out.

 

ANY help will be greatly appreciated!!!

Link to comment
Share on other sites

Ok, to completely simplify, your problem is that regardless of what permission a user has based on a value in the db, every upload by any/every user is going to the same folder?

 

Need to keep things short and sweet 'cause I have a feeling this isn't a very difficult problem to solve, but becomes more difficult as 100's of lines of code come into play.

Link to comment
Share on other sites

Ok, well it's easy to see that you're losing your values because of the header() redirect you're issuing for some reason.

 

Your code is working like this:

 

1. User fills out form and loads page/script.

 

2. Script executes ipAllowed() function, assuming it checks for, well, an allowed IP.

 

3. Script checks if 'verify_password' is true.

 

4. Script executes checkPasswordInDb() function.

 

5. Script redirects and quits.

 

Do you see the problem?  Your (the scripts) logic is completely messed.  As soon as you execute header(Location) you lose all your $_POST/form values.

 

ADDITION: You want to alter this block of code:

 

if(checkPasswordInDb($_POST['check_password'])) {
		// User entered a password that matches one in the database

			setcookie("fileUploader", $password);
			sleep(1); // Seems to help some installations
			header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
			exit;
		}

 

Get rid of these lines in substitution for your file upload block:

 

sleep(1); // Seems to help some installations
header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

 

You don't want to redirect anywhere, instead you want to begin the file upload process, etc.  That should sort you out.

Link to comment
Share on other sites

mrMarcus - I do believe you've hit on where the issue lies - it took me a while to see it (I'm pretty new to PHP, so this project has been a big challenge), but I thought I was losing all of the variables after the header(location) line.

 

In your last post you removed the setcookie and exit lines and said "Get rid of these lines in substitution for your file upload block". Could you clarify that statement?

 

Once the $folder, $full_url, etc variables are set, how do I retain those values for use in the file upload process? (I'm thinking you may have answered that question in your post, but I'm not fully understanding how to implement it...)

Link to comment
Share on other sites

I'm on lunch, so I will expand in a little bit, however, I did not say to eliminate the setcookie() function as I do not know what it's doing yet.  You'll see the bottom of my last post I said to remove the sleep() ('cause it makes no sense to delay the script for a second), and obviously the header() redirect.  As long as the setcookie() is being used, keep it.

Link to comment
Share on other sites

Ok, you gotta go back and read what I have already posted 'cause I mentioned what to do to fix that ;)

 

EDIT: Meh, I'll save you the time:

 

Get rid of these lines in substitution for your file upload block:

 

Pseudo code:

 

<?php
if(checkPasswordInDb($_POST['check_password'])) {
// User entered a password that matches one in the database

// Echoing the variables $userName, $folder, $full_url, and $password still show their values as set in the checkPasswordInDb function

setcookie("fileUploader", $password);
//header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); //removed;

/**
  * HERE YOU WANT TO INITIALIZE THE IMAGE UPLOAD, ETC.
  */

// Don't allow submit if $password_form hasn't been populated
if(($_POST['submit'] == true) AND ($password_form == "")) {

	// Tally the size of all the files uploaded, check if it's over the ammount
	if(array_sum($_FILES['file']['size']) > $max_combined_size * 1024) {

		$error .= "<b>FAILED:</b> All Files <b>REASON:</b> Combined file size is too large.<br />";

	//rest of code here...
}

 

Of course, this is not guaranteed to work as I don't really feel like creating a working copy since I do have work of my own, but it's setting the logic on track for a working script.  You need to study the logic.  What blocks of code need to execute and when .. and why.

Link to comment
Share on other sites

Okay, I think I see what you're getting at: I'm guessing your key statement is "Get rid of these lines in substitution for your file upload block", meaning put the file upload process in place of those two lines.

 

But I'm pretty sure that a simple substitution like that won't work on my form, as it is currently written. I say that because there's nothing to build the web page without the redirect, meaning the user has no means to upload the files, meaning there's nothing to process - I think you get the picture.

 

I really hate to suggest this, but if you go back and look at the file I attached to my original post you'll see the context in which the php code we've been discussing is used. The redirect is what loads the html and in that there is a check in php code at the top of the body tag that determines whether to display the password form or the file upload form.

Link to comment
Share on other sites

Okay, I think I see what you're getting at: I'm guessing your key statement is "Get rid of these lines in substitution for your file upload block", meaning put the file upload process in place of those two lines.

 

But I'm pretty sure that a simple substitution like that won't work on my form, as it is currently written. I say that because there's nothing to build the web page without the redirect, meaning the user has no means to upload the files, meaning there's nothing to process - I think you get the picture.

 

I really hate to suggest this, but if you go back and look at the file I attached to my original post you'll see the context in which the php code we've been discussing is used. The redirect is what loads the html and in that there is a check in php code at the top of the body tag that determines whether to display the password form or the file upload form.

Well ya, it hurts my eyes looking at this code.  There is really no "fixing it" as by the time we'd be done fixing it, would have just made more sense to tear down and rebuild from scratch.

 

Did you try and put the header() after a successful file upload?

Link to comment
Share on other sites

Well ya, it hurts my eyes looking at this code.  There is really no "fixing it" as by the time we'd be done fixing it, would have just made more sense to tear down and rebuild from scratch.

 

I was beginning to thing it was coming to that. Well, no better way to learn that to jump in with both feet!

 

I thank you for your help and patience (unless you've been shaking your fist in frustration at me this whole time! ;) ). Wish me luck!

Link to comment
Share on other sites

Yes.  Cookies, like sessions can't be stored and accessed as long as the cookie is valid and the session state is open.  Regardless of a redirect.  Just watch as they can create lazy code as well.  They are not needed (session vars more so) as people tend to think.

 

When developing PHP applications, planning ahead is crucial.  I suggest losing the code you have there (use it for something to reference at best, even then the code seems outdated), and write out your logic first.  PHP is all logical.  Say it out loud, ie.

 

IF user submits the form, validate the incoming form data and execute necessary functions (image upload, database queries, etc.) in order of requirements.

 

ELSE send user back to form and inform them of errors.

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.