Unable to move_uploaded_file when adding user avatars - php

Back again with another newbie question. I've been working on a document that will allow users to upload their own avatars to a blog that I'm creating to learn some PHP. I've been working on this document for two days now and I've spent over six hours of searching and trying different things to fix it but I just can't get it to get past this:
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
It does send the "bad message" finally after about an hour of trying different solutions but I'm not quite sure why it is giving me the "bad message", to me everything looks okay.
FULL CODE:
<?php
session_start();
if (isset($_SESSION['username'])){
if (isset($_POST['submit']) && isset($_FILES['avatar'])) {
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('webserver', $con);
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$id = $row['id'];
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
}else{
echo "38";
}
}
?>
<form enctype="multipart/form-data" action='uploadavatar.php' method='POST'>
<table>
<tr>
<td>
Upload an avatar:
</td>
</tr>
<td>
<input type='file' name='avatar'>
</td>
</tr>
</table>
<p>
<input enctype='multipart/form-data' type='submit' name='submit' value='Submit'>
</p>
</form>
By the way I'm sorry there is probably a bunch of useless code in there, I have spent a bunch of time just getting it far enough to give me an error.

The location where the uploaded file is stored on disk is $_FILES['avatar']['tmp_name']. You want to move that, not $_FILES['avatar']['name'].

The problem here is that, you're using move_uploaded_file() in wrong way.
The first parameter requires a filename with its extension, without base path, like
mypic.jpg. The second requires a destination where that file should be uploaded.
As for your code,
Replace this,
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['temp'], $target)){
with
// I'd assume that dirname(__FILE__) refers to your root
//Directory to save stuff
$destination = sprintf('%s/images/useravatars/%s', dirname(__FILE__), $_FILES['avatar']['name']);
//Save the avatar
if (move_uploaded_file($_FILES['avatar']['tmp_name'], $destination)) {

Related

PHP Form is Updating SQL Table Even When SQL Table Column Isn't Blank

I am trying to make a PHP form that will only allow the user to update the MySQL Table column photo, if the photo column is blank. Currently, the form will still update the photo column even if there is data other than "blank" data. For example, the photo column contains the data "columbia.jpg" and the user submits the form with the image "Jefferson.jpg" in the first input. The image column's data gets replaced from columbia.jpg to jefferson.jpg when it is not supposed to replace it at all. Instead it should return an error message stating that the user must first delete the old image before adding a new one. The column data should only get replaced when the column data is equal to "blank". (Not the word "blank" but "".)
Here is my full PHP page code:
<?php
if (isset($_GET["id"])) {
$sn = (int)($_GET["id"]);
?>
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
Photo 1: <input type="file" name="photo"><br>
<input name="add_image" id="add_image" type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
<?php
if(isset($_POST['add_image']))
{
$dbLink = new mysqli('daom', 'sm', 'aer', 'kabm');
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array=mysqli_fetch_assoc($result);
if($query = " "){
//Writes the information to the database
$query1 =
"UPDATE used_trailers ".
"SET photo = '$pic' ".
"WHERE id = $sn" ;
// Execute the query
$results = $dbLink->query($query1);
// Check if it was successfull
if($results) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to Photo 1, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your image.";
}
} else {
echo '<p>You must first delete the "Photo 1" image, $array, in order to add a new photo. This is to prevent the server from overloading with too many images.</p>';
}
}
}
echo "$query1";
?>
Thank you for any help. All help is appreciated.
There are some errors in your script. First of all if ($query = " ") will always return true, because you are assigning the variable $query the string " ". To correctly check this, you'd need to use if ($query == " ").
However, this won't solve your problem as $query is the query - not the result. This should work
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array = mysqli_fetch_assoc($result);
if (empty($array['photo'])){
//etc.
}

Why does this add data to the database multiple times?

Basically I have created a set of php files that have a simple job:
Allows a user to log in.
Allows that user to upload a file.
Then Allows the user to see all files they have uploaded.
Strangely though, when I upload a file through 1 user name, the file list result shows the same result 4 times then I uploaded a second file, it appeared 5 times. With another user it displays it 5 times.
I checked the place the files get stored after upload, and there is only 1 copy of each file there. Below is my code, any help?
index.php - This has login form, file upload form and finally the download list
<?
break;
}
?>
<?php if ($_SESSION['username']): ?>
<h1>Welcome, <?php echo $_SESSION["username"] ?></h1></br>
<?php
//include ("config.php");
//Connect to mysql server
$link = mysql_connect($host, $dbuser, $dbpwd);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db($dbname);
if(!$db) {
die("Unable to select database");
}
?>
Select File To Upload
<div style="width:100%; margin:5px;">
<form action="uploadclientfile.php" method="post" enctype="multipart/form-data" name="upload" style="margin:5px;">
<label> File</label>
<input name="uploaded_file" type="file" class="input-xlarge" required/>
<input type="hidden" name="" value="<?php $_SESSION['username'] ?>" />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /><br /><br />
<input name="Upload" type="submit" value="Upload" class="btn" />
</form>
</div></br></br>
File list:</br>
<?php
$userfiles = mysql_query("SELECT filename, filelocation FROM cfiles WHERE userid='{$_SESSION['username']}'" );
while ($row = mysql_fetch_assoc($userfiles)) {
$filename = $row['filename'];
$filelocation = $row['filelocation'];
echo "" .$filename . "<br />";
} ?>
<?php endif; ?>
Log-in | Log-out<br />
</body>
</html>
and also upload.php
<?php
session_start();
echo( "<pre>" );
print_r( $_POST );
print_r( $_FILES );
echo( "</pre>" );
$target = "userfiles/";
$target = $target . basename( $_FILES['uploaded_file']['name']);
$new_file_name = str_replace(' ', '_', $target);
//This gets all the other information from the form
$userid = $_SESSION['username'];
$file = basename( $_FILES['uploaded_file']['name'] );
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
//Writes the file to the server
if( #move_uploaded_file( $_FILES['uploaded_file']['tmp_name'], $new_file_name ) )
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploaded_file']['name'] ). " has been uploaded, and your information has been added to the directory.";
}
else
{
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
So there are the 2 main files used in this process. Any help as to why my file is appearing in the download list and mysql database multiple times? It is only appearing once in the folder it is stored.
This part of your code:
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
Loops through how ever many users you have and adds a new file entry for each. So if you have 5 users you add 5 entries into cfiles for the $userid of the person that's logged in. This will increase with more users.
Is this what you meant to do? You probably just want to add one entry for that user, and not other users, correct?
If you remove the loop and replace that code with this:
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
You'll only get one entry
This code confuses me:
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
What are you trying to do here? It appears that you're inserting the uploaded file into the database multiple times, one time for each user who exists. Why are you doing that? Is that why the file is appearing multiple times? (Seems likely to me)

Why do I get this error when trying to upload an image?

When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.

how to upload image?

I want upload images in php here is my code
if (isset($_FILES['userfile']['name'])) {
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
$from = $_FILES['userfile']['tmp_name'];
$to = "/var/www/html/images/".$_FILES['userfile']['name'];
$res = move_uploaded_file($from, $to);
if($res)
{
print 'upload success';
}
else
{
print 'fail';
}
here i got output fail please tell me correct process
thanks in advance
for images/ have you checked the Permission on Linux it will be 755 or 777.
Note: You don't need absolute path for that you can even do like below.
$to = "images/".$_FILES['userfile']['name'];
The code looks OK, so either the script cannot write to unsifficient rights on the /var/www/html/images/ directory, or that directory does not exist at all.
Please check the existance of the directory, and then try to write another file (not through upload) to that directory. Check the directory permissions accordingly.
Please try this, it is already tested and working fine.
<?php
mysql_connect("localhost","root","");
mysql_select_db("kerala");
error_reporting(0);
?>
<?php
if($_POST[sub1]=="Upload")
{
#mkdir("image");
$link="image/".time()."-".$_FILES[fil][name];
copy($_FILES[fil][tmp_name],$link);
$sql2="insert into `details`(`photo`) values('$link')";
$query2=mysql_query($sql2);
header("location:photo.php");
}
$sql3="select * from `details`";
$query3=mysql_query($sql3);
while ($row=mysql_fetch_array($query3))
{
//echo "<a href=`$row[photo]`><img src='$row[photo]' height='100' width='100'>$row[photo]</a>";
echo "<img src='$row[photo]' height='100' width='100'>";
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fil">
<input type="submit" name="sub1" value="Upload">
</form>

User uploading images to specific directories

So basically I have a site in which certain members are allowed to upload images (comic pages) to their own image galleries (to a specific comic). I have a successful image uploading script that I used to upload profile/avatar images for each member, but now that I want to upload files to a more specific place I'm having a little trouble.
Here's what I have so far:
(This is what appears at the top of the page)
<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
(This is the uploading script)
<?php
// Here we run a login check
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = ""; //numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "comics/$comicid/".$newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
Ideally, I would like to be able to upload an image like this: comics/comic_id/chapter_id/uploaded_file.extension
With the user profile image uploader, I was able to grab the $ID from the $_Session['id'] variable, but with the comics, I don't really know how to grab that information and use it to set the comic_id directory (chapter_id will be selected on the form so I'm not too worried about that one).
Any thoughts?
You can upload a file to wherever you choose. This will save the comic in a folder of its id and chapter, but retaining the filename. If you wanted to use the comic id as the filename I am sure you can work that out.
$basepath = "/home/path/to/www/comics/member_" . $member_id . "/";
function construct_path($chapter_id,$comic_id)
{
$saveimagepath = $basepath . $comic_id . $chapter
}
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = $saveimagepath . $_FILES['uploadedfile']['tmp_name'];
//numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
The $_SESSION variable is available at any site you started with session_start(). So if the id is set right after the login, you can access this value at any other page in the same way with $_SESSION['id']. Make sure that the value of id won't kill your filesystem or leads to security issues!

Categories