...

View Full Version : move_uploaded_file not working



savagebeauty
11-11-2011, 09:14 PM
I am trying to add a profile page to my website that allows users to add an avatar. Adding the avatar will update the users table. So far I have:




<?php
include("functions/globals.php");
include("databasefunctions.php");
include("functions/userfunctions.php");



error_reporting(E_ALL);

?>

<?php session_start(); ?>

<?php
if($_SESSION['user'])
{?>

Welcome: <?php echo $_SESSION['user']->username; ?>
<?php
}?>


<?php

if($_POST['submit'] == 'Upload')
{
//get file attributes
$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];


if ($name)
{
//start upload process
$location = 'avatars';
foreach ($_FILES["avatar"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["avatar"]["tmp_name"][$key];
$name = $_FILES["avatar"]["name"][$key];

move_uploaded_file($tmp_name,"$location/$name");
}
}
$result = QuickQuery("UPDATE users SET imagelocation='$location' WHERE username='$username'");

die("Your avatar has been uploaded <a href='view.php'>Home</a>");
}
else
if(!$name)
$error = "Please select an image";

}


?>
<form action='profile.php' method='post' enctype='multipart/form-data'>
Upload:<input type='file' name='avatar'><input type='submit' name='submit' value='Upload'>
</form>


I am not getting any errors, but files are not being uploaded to the "avatars" folder.

Would appreciate any help!

Thanks!

mlseim
11-11-2011, 09:34 PM
Troubleshooting problems like this ...
Insert some echoes so you can see what is happening.

foreach ($_FILES["avatar"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["avatar"]["tmp_name"][$key];
$name = $_FILES["avatar"]["name"][$key];

echo "tmp_name: ".$tmp_name." &nbsp;&nbsp; loc/name: ".$location."/".$name."<br />";

move_uploaded_file($tmp_name,"$location/$name");
}


Report back on what you see.


.

savagebeauty
11-11-2011, 10:04 PM
I added the code and still get the same thing on submit:

"Your avatar has been uploaded."

mlseim
11-11-2011, 10:32 PM
Are you saying you never saw the echoed part that you added?
If so, that means it never got to that part of your script.

That's a clue ...

Keep that echo there and add another one ... let's see where the script is going ...

if ($name)
{
echo "we made it through the 'if($name)' statement. <br />";


You can add echo statements anywhere you want to troubleshoot this problem.



.

savagebeauty
11-11-2011, 11:06 PM
This one echoed correctly. Yes, nothing on the first one you gave me echoed out anything. It only said the file was uploaded.

What else to do?

Thanks for helping!

mlseim
11-11-2011, 11:38 PM
OK ... that means the problem is within this scripting ...

foreach ($_FILES["avatar"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["avatar"]["tmp_name"][$key];
$name = $_FILES["avatar"]["name"][$key];

move_uploaded_file($tmp_name,"$location/$name");
}


The "foreach" line is suspicious to me.
There must not be any 'true' values for the "foreach" line ... so it does nothing.

You put the word "avatar" in those lines.
Can you show me the original script that you copied from somewhere.
Where did you get this script from?


.

savagebeauty
11-12-2011, 12:04 AM
<?php
include("functions/globals.php");
include("databasefunctions.php");
include("functions/userfunctions.php");



error_reporting(E_ALL);

?>

<?php session_start(); ?>

<?php
if($_SESSION['user'])
{?>

Welcome: <?php echo $_SESSION['user']->username; ?>
<?php
}?>


<?php

$username = $_SESSION['username'];
if($_POST['submit'] == 'Upload')
{
//get file attributes
$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

$location = "avatars/$name";
move_uploaded_file($tmp_name, $location);

$result = QuickQuery("UPDATE users SET imagelocation='$location' WHERE username='$username'");

die("Your avatar has been uploaded <a href='view.php'>Home</a>");
}
else
die("Please select a file.");

}



?>
<form action='profile.php' method='post' enctype='multipart/form-data'>
Upload:<input type='file' name='avatar'><input type='submit' name='submit' value='Upload'>
</form>



This is the original script. I think I made a mistake adding foreach...I think that is for adding multiple files. I only need users to add their avatar. This original code does not move the file either.

The script came from phpacademy tutorial. I was trying!

MattF
11-12-2011, 12:23 AM
I think I made a mistake adding foreach...I think that is for adding multiple files. I only need users to add their avatar.

Then ditch it.



if ($_FILES["avatar"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["avatar"]["tmp_name"];
$name = $_FILES["avatar"]["name"];

if (move_uploaded_file($tmp_name,"$location/$name"))
{
[put your DB insert line here instead of further down the script]
exit('Your avatar was uploaded successfully');
}
}

savagebeauty
11-12-2011, 12:39 AM
<?php

$username = $_SESSION['username'];
if($_POST['submit'] == 'Upload')
{
//get file attributes

$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

}

$location = "avatars/$name";
if (move_uploaded_file($tmp_name,"$location/$name"))
{
$result = QuickQuery("UPDATE users SET imagelocation='$location' WHERE username='$username'");
exit("Your avatar was uploaded successfully <a href='view.php'>Home</a>");

}
}


?>


Tried updating this part of the code to your suggestion-- do not receive "File uploaded" now. Nothing happens at all on submit.

MattF
11-12-2011, 12:43 AM
Tried updating this part of the code to your suggestion

Then post the complete code which you are currently trying. Showing what you've replaced without showing what with is pointless.

savagebeauty
11-12-2011, 12:57 AM
wow dude, aren't you pleasant. Thanks to msleim who is helping me without the attitude. By the way I DID post the entire code:




<?php
include("functions/globals.php");
include("databasefunctions.php");
include("functions/userfunctions.php");



error_reporting(E_ALL);

?>

<?php session_start(); ?>

<?php
if($_SESSION['user'])
{?>

Welcome: <?php echo $_SESSION['user']->username; ?>
<?php
}?>


<?php

$username = $_SESSION['username'];
if($_POST['submit'] == 'Upload')
{
//get file attributes

$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

$location = "avatars/$name";
if (move_uploaded_file($tmp_name, $location));
{
$result = QuickQuery("UPDATE users SET imagelocation='$location' WHERE username='$username'");
}
exit("Your avatar has been uploaded <a href='view.php'>Home</a>");
}
else
die("Please select a file.");

}



?>
<form action='profile.php' method='post' enctype='multipart/form-data'>
Upload:<input type='file' name='avatar'><input type='submit' name='submit' value='Upload'>
</form>

savagebeauty
11-12-2011, 01:21 AM
I've made some sort of progress. The avatar is going into the database, but not attaching to the user who is logged in. It is also not in the avatars folder. The code has two parts. 1st part is still in profile.php. Second part is in userfunctions.php

profile.php



<?php
include("functions/globals.php");
include("databasefunctions.php");
include("functions/userfunctions.php");



error_reporting(E_ALL);

?>

<?php session_start(); ?>

<?php
if($_SESSION['user'])
{?>

Welcome: <?php echo $_SESSION['user']->username; ?>
<?php
}?>


<?php

$username = $_SESSION['username'];
if($_POST['submit'] == 'Upload')
{
//get file attributes

$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

$location = "avatars/$name";
if (move_uploaded_file($tmp_name, $location));
{
AddAvatar($location);
}
exit ("Your Avatar ". $_FILES['avatar']['name'] ." has been uploaded.\n<a href='view.php'>Home</a>");
}
else
die("Please select a file.");

}



?>
<form action='profile.php' method='post' enctype='multipart/form-data'>
Upload:<input type='file' name='avatar'><input type='submit' name='submit' value='Upload'>
</form>

Here is the second part in userfunctions.php




function AddAvatar ($location)
{
global $usertable;
openDatabase();
$location = mysql_real_escape_string($location);
$result = QuickQuery("UPDATE users SET imagelocation='{$location}' WHERE username='{$username}'");
closeDatabase();
}



Mlseim, can you see from this why the avatar is not attaching to username or moving into the avatars folder? In the database it says avatars/me.jpg which is the name of the pic

mlseim
11-13-2011, 12:16 AM
I don't think you need to use tmp_name ....

Change this:

$tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

$location = "avatars/$name";
if (move_uploaded_file($tmp_name, $location));


to this:

// comment this out for now ... $tmp_name = $_FILES['avatar']['tmp_name'];

if ($name)
{

//start upload process

$location = "avatars/$name";
if (move_uploaded_file($name, $location));




.

savagebeauty
11-13-2011, 03:04 AM
That didn't change anything. But I did figure out something that might help solve this. On the page where I have the avatar form, I also have the registration form. Both forms use if($_POST['submitted'] and then different values-- one is register and the other upload.

This is why the avatar image is going into the database. If I change the upload to submit instead, it doesn't go into the database at all.

Not sure what else to do.

mlseim
11-13-2011, 03:09 AM
Show us that script.

savagebeauty
11-13-2011, 03:59 AM
<?php
include("functions/globals.php");
include("databasefunctions.php");
include("functions/userfunctions.php");

error_reporting(E_ALL);

?>

<!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 name="google-site-verification" content="" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

<!-- Required CSS -->
<link href="css/movingboxes.css" media="screen" rel="stylesheet">
<!--[if lt IE 9]>
<link href="css/movingboxes-ie.css" rel="stylesheet" media="screen" />
<![endif]-->

<link href="css/demo.css" media="screen" rel="stylesheet">

<!--[if lte IE 7]>
<style>
.content { margin-right: -1px; } /* this 1px negative margin can be placed on any of the

columns in this layout with the same corrective effect. */
ul.nav a { zoom: 1; } /* the zoom property gives IE the hasLayout trigger it needs to correct

extra whiltespace between the links */
</style>
<![endif]-->

<link rel="stylesheet" type="text/css" href="css/style.css" />
<link href="css/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<link href="css/pup-slider.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="java/jquery.js"></script>
<script type="text/javascript" src="java/cross-slide.js"></script>



<script type="text/javascript">
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
</script>

<style type="text/css">

#rightlogin {
z-index:1000;
}

div.panel,p.flip
{
margin:0px;
padding:5px;
text-align:left;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel
{
height:auto;
display:none;
}
</style>


<script src="java/SpryMenuBar.js" type="text/javascript"></script>

<!-- Required for slider script -->
<script type="text/javascript" src="java/jquery.min.js"></script>
<script type="text/javascript" src="java/jquery.movingboxes.min.js"></script>

<!-- Demo only -->
<script type="text/javascript" src="java/demo.js"></script>

<script type="text/javascript" src="java/pup-slider.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#rightlogin').pupslider({ stick: 'right', speed: 500, opacity: 0.9 });
});
</script>
</head>

<body>

<?php
include_once("functions/mysqlinfo.php");
include_once("functions/databasefunctions.php");
include_once("functions/article.php");
include_once("functions/common.php");
?>

<div id="topgoogleadd">
<script type="text/javascript"><!--
google_ad_client = "";
/* adds */
google_ad_slot = "";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="container">

<?php
if($_GET['logout'] == 'logout')
{
session_destroy();
Redirect("index.php");
}
if($_POST['submit'] == "login")
{
// echo ValidateUser("Me", "password");
//CreateAccount($name, $password, $email, $type);
if(ValidateUser($_POST['username'], $_POST['password']) == 1)
{
$_SESSION['user'] = new cUser;
$_SESSION['user']->username = $_POST['username'];
$_SESSION['user']->usertype = GetUserType($_POST['username']);
$_SESSION['user']->userid = GetUserID($_POST['username']);
Redirect("index.php");
}
// CreateAccount("test", "test", "Me@aol.com", "user");
}
?>

<?php
if($_POST['submitted'] == "register")
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpwd = $_POST['confirmpwd'];
if(!$firstname)
$error = "Invalid First Name";
else
if(!$lastname)
$error = "Invalid Last Name";
else
if(!$username)
$error = "Invalid User Name";
else
if(!$email)
$error = "Invalid Email";
else
if(!$password)
$error = "Invalid Password";
}
?>

<?php
if($_POST['submitted'] && !$error)
{
$result = QuickQuery("SELECT username FROM users WHERE username='{$username}'");
if(mysql_numrows($result) > 0)
$error = "Be More Creative. Someone Already is Using That Username.";
else
{
$result = QuickQuery("SELECT email FROM users WHERE email='{$email}'");
if(mysql_numrows($result) > 0)
$error = "Email Already Being Used. Maybe you already registered.";
else
if($confirmpwd != $password)
$error = "Matching passwords means the second password must be exactly like the first.";

else
{
CreateAccount($firstname, $lastname, $username, $password, $email, "user");
Redirect("thankyou.php?message=register");
exit;

}
}
}
?>
<?php Error($error);?>

<div class="header"><img src="images/header.png" width="600px" height="156" style="background:

#fff; display:block;" />
<div id="rightlogin">
<!--rightlogin starts here-->

<div class="btn-show">
<p>Login</p>
</div>

<div class="pushup-form">
<div class="btn-close">
Close
</div>
<div class="clear">
</div>

<p style="font-size:14px">Login</p>
<form action="index.php" method="post">

<p>Username:<input type="text" name="username" style="font-size:12px;"/></p>


<p>Password:<input type="password" name="password" style="font-size:12px;"/></p>


<p><input class="login" type="submit" name="submit" value="login" /></p>


<p><a href="pwd.php?pwd=lostpwd" style="font-size:10px">Forgot Username or Password?</a></p>


</form>

<div class="panel">
<form action="index.php" method="post">

<p>First Name:<input type="text" name="firstname" value="<?php echo $firstname;?>" /></p>


<p>Last Name:<input type="text" name="lastname" value="<?php echo $lastname;?>" /></p>


<p>Username:<input type="text" name="username" value="<?php echo $username;?>" /></p>


<p>Email:<input type="text" name="email" class="clear" value="<?php echo $email;?>" /></p>


<p>Password:<input type="password" name="password" value="<?php echo $password;?>" /></p>


<p>Confirm Password:<input type="password" name="confirmpwd" value="<?php echo $confirmpwd;?>" /></p>

<p class="clear">
<p><input class="register" type="submit" name="submitted" value="register"/></p>


</p>
</form>


</div>
<p style="text-align:center;" class="flip">Need to Register?</p>



<!--pushup content bar ends here-->
</div>
</div><!-- end .header -->

<?php if($_SESSION['user'])
{?>
<ul><li><div class="loginwelcome"><a href="index.php?logout=logout">Logout</a></div>
<center><li><font face="garamond" font size="5px">Confidential: <?php echo $_SESSION['user']->username; ?>'s Profile</font></li></center>

<li><a style="float:right" href="pwd.php?pwd=changepwd">Change Password</a></li>

<?php if($_SESSION['user']->usertype == "admin") {?>
<li><a style=" float:right;" href="editarticle.php">Edit Article</a></li>
<li><a style="float:right" href="addarticle.php">Add Article</a></li></ul>
<?php } ?>

<?php
}?>
<div id="topnavigation">
<div id="searchcontainer">
<form method="post" action="searchresults.php">
<input type="text" name="search" class="inputfield" />
<input type="submit" value="Go" id="gobutton" />

</form></div>
<ul id="MenuBar1" class="MenuBarHorizontal">
<li><a class="MenuBarItemSubmenu" href="http://www.mysite.com">Home</a>
<ul>
<li><a href="#">Item 1.1</a></li>
<li><a href="#">Item 1.2</a></li>
<li><a href="#">Item 1.3</a></li>
</ul>
</li>
<li><a href="#">Fiction</a>
<ul>
<li>
<a href="#"><img src="images/windytree.png" width="196" height="133" /><p>Latest Review: James Redfield "The Secret of Shambhala"</p></a></li>

<li><a href="#">Item 2.2</a></li>
<li><a href="#">Item 2.3</a></li>
</ul>
</li>
<li><a class="MenuBarItemSubmenu" href="#">Item 3</a>
<ul>
<li><a class="MenuBarItemSubmenu" href="#">Item 3.1</a>
<ul>
<li><a href="#">Item 3.1.1</a></li>
<li><a href="#">Item 3.1.2</a></li>
</ul>
</li>
<li><a href="#">Item 3.2</a></li>
<li><a href="#">Item 3.3</a></li>
</ul>
</li>
<li><a href="#">Item 4</a></li>
</ul>

</div>
</div>


<?php


if($_POST['submitted'] == 'Upload')
{
//get file attributes

$name = $_FILES['avatar']['name'];
$tmp_name = $_FILES['avatar']['tmp_name'];
$location = "avatars/$name";
$about = $_POST['about'];

if(!$about)
$error = "Please tells us a little bit about yourself.";
if ($name)
{

//start upload process


if (move_uploaded_file($name,$location));
{
UpdateProfile($location, $about, "user");
}
exit ("Your Avatar ". $_FILES['avatar']['name'] ." has been uploaded.\n<a href='view.php'>Home</a>");
}

else
die("Please select a file.");

}



?>
<form action='profile.php' method='post' enctype='multipart/form-data'>
Bio:<input type="text" name="about" style="width:175px; height: 220px; background:#ccc; float:left;"/>
Upload:<input type='file' name='avatar'/>
<input type='submit' name='submitted' value='Upload'>
</form>




here is userfunctions.php




<?php
include_once("databasefunctions.php");

$userdbtable = "users";

function GetHeaders()
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "To: {$username} <{$email}>" . "\r\n";
$headers .= 'From: The Website <noreply@mywebsite.com>' . "\r\n";
return $headers;
}
function CreateAccount($firstname, $lastname, $username, $password, $email, $type, $activation)
{
global $userdbtable;
openDatabase();
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$email = mysql_real_escape_string($email);
$type = mysql_real_escape_string($type);




$nonencrypted = $password;
$password = sha1($password);
$activation = md5(uniqid(rand(), true));
$result = QuickQuery("INSERT INTO {$userdbtable}(firstname, lastname, username, password, email, type, activation)
VALUES('{$firstname}','{$lastname}','{$username}','{$password}','{$email}','{$type}','{$activation}' )");
if($result)
{
$headers = GetHeaders();
$message = "\"Welcome to the website! Please click on the link below to activate your account.\n\n\"<br />
<br />
Your username is: {$username}<br />
Your password is: {$nonencrypted}<br />
";
$message .= WEBSITE_URL . '/activate.php?email=' . ($email) . "&key=$activation";

mail($email, "Registration Confirmation", $message,$headers);
mail("email@yahoo.com", "Account Created", "{$username} has created a new account", $headers);
}
}

function ValidateUser($username, $password)
{
global $userdbtable;
openDatabase();
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$result = QuickQuery("SELECT * FROM {$userdbtable} WHERE username = '{$username}'");

closeDatabase();

if(!mysql_result($result,0,"username"))//Make sure the user exists
return "User Does Not Exist";

$temppwd=mysql_result($result,0,"password");//Make sure the passwords match
if(sha1($password) != $temppwd)
return "Password Does Not Match";

return 1;
}

function GetUserID($username)
{
global $userdbtable;
openDatabase();
$username = mysql_real_escape_string($username);
$result = QuickQuery("SELECT id FROM {$userdbtable} WHERE username = '{$username}'");
closeDatabase();

if($result)
return(mysql_result($result,0,"id"));//Get the user id
else
return 0;

return(mysql_result($result,0,"id"));//Get the UserID
}

function GetUserType($username)
{
global $userdbtable;
openDatabase();
$username = mysql_real_escape_string($username);
$result = QuickQuery("SELECT type FROM {$userdbtable} where username = '{$username}'");
closeDatabase();

return(mysql_result($result,0,"type"));//Get the user type
}

function GetUserEmail($username)
{
global $userdbtable;
openDatabase();
$username = mysql_real_escape_string($username);
$result = QuickQuery("SELECT email FROM {$userdbtable} WHERE username = '{$username}'");
closeDatabase();

return(mysql_result($result,0,"email"));//Get the user email
}

function ConfirmPassword($id, $password)
{
global $userdbtable;
openDatabase();
$password = mysql_real_escape_string($password);
$password = sha1($password);
$result = QuickQuery("SELECT * FROM {$userdbtable} WHERE id = '{$id}' AND password = '{$password}'");
closeDatabase();

if(!$result)
return 0;
else
return 1;
}

function UpdateProfile ($location, $about)
{
openDatabase();
$location = mysql_real_escape_string($location);
$about = mysql_real_escape_string($about);
$result = QuickQuery("UPDATE users SET imagelocation='{$location}', about='{$about}' WHERE username='{$username}'");
return $result;

}

function ChangePassword($id, $password)
{
global $userdbtable;
openDatabase();
$password = mysql_real_escape_string($password);
$password = sha1($password);
return QuickQuery("UPDATE {$userdbtable} SET password='{$password}' WHERE id={$id}");
}

function ResetPassword($email)
{
global $userdbtable;
openDatabase();
$email = mysql_real_escape_string($email);
$result = QuickQuery("SELECT * FROM {$userdbtable} WHERE email = '{$email}'");

$num = mysql_numrows($result);
if(!$num)
return 0;
$user = mysql_result($result, 0, "username");
$email = mysql_result($result, 0, "email");
$randompwd = RandomPwd();
$temp = sha1($randompwd);
$headers = GetHeaders();
mail($email, "The website password change", "A password change request has been initiated. Your username is: {$user}, and your new password is: {$randompwd}. Try to remember next time.", $headers);
if(QuickQuery("UPDATE {$userdbtable} SET password='{$temp}' WHERE email='{$email}'"))
return 1;
}

function RandomPwd()
{
$length = 10;
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = "";

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}

return $string;
}
?>



I haven't had any problems with the scripts. Just not able to get the avatar thing working.

savagebeauty
11-13-2011, 09:55 PM
solved this one. Thanks for your help!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum