[PHP] File Upload

Skilled Illusionist
Joined
Jul 1, 2007
Messages
367
Reaction score
1
Okay, RaGEZONE.
I've started writing my own Image Board script, and I'm having trouble with the hardest part - the images.
For some reason, the browser outputs a message telling me the file is uploaded, but I check the directory and it is not there.

I've been working off of the File Upload Script from W3Schools, so I have no idea what is wrong with it.
Also, my directory for the uploaded file's CHMOD is 777, so that isn't a problem.

Edit
-
In my script, what I am trying to do, is upload the image with a different name, by the way.


Do you have any clue why I'm failing? If so, thanks.

/scripts/newthread.php:
PHP:
<?php
	// New Thread Function
	$con = mysql_connect('localhost', '*****', '*****') or die(mysql_error());
	mysql_select_db('*****', $con) or die(mysql_error());
	
	# OP's Details
	$name		= $_POST['name'];
	$tripcode	= $_POST['tripcode'];
	$email		= $_POST['email'];
	$subject	= $_POST['subject'];
	$comment	= $_POST['post-text'];
	$date		= date("F j, Y, g:i a");
	#-> Filter Details
	if ($name == "")
	{
		$name = "Anonymous";
	}
	if ($tripcode != "")
	{
		$tripcode = md5($tripcode . "#*(UWEJn");
	}
	
	# Begin Script:
	
	if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/pjpeg")
		|| ($_FILES["file"]["type"] == "image/jpg")
		|| ($_FILES["file"]["type"] == "image/png")
		))
	{
		if ($_FILES["file"]["error"] > 0)
		{
			echo "Error: Invalid File.";
		}
		else
		{
			$filename	= $_FILES["file"]["name"];
			$filesize	= $_FILES["file"]["size"];
			$filename_encrypted = rand(100000000000, 999999999999);
			if (file_exists("/bimages/" . $filename_encrypted) == true)
			{
				echo "Error: File Error, please try again";
			}
			else
			{
				// Save thread
				$SQL = "INSERT INTO `threads` (name, tripcode, email, subject, comment, date, image, encimage)
					VALUES ('$name', '$tripcode', '$email', '$subject', '$comment', '$date', '$filename', '$filename_encrypted')";
				mysql_query($SQL) or die(mysql_error());
				
				// Save file
				move_uploaded_file($_FILES["file"]["name"], "/bimages/" . $filename_encrypted . ".png");
				echo "Thread created, file <i>" . $filename . "</i> uploaded!<br>
					Now going to your new thread.";
			}
		}
	}
	else
	{
		echo "Error: Invalid file type.";
	}
?>
 
/bimages/ and the upload directory both are chmod 777?

"/bimages/" is the upload directory. And is CHMOD 777, yes.
Edit - Re-read my first post, I'll add to my description :)

Also, I've just changed the 'move_uploaded_file()' to:
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"], "bimages/" . $_FILES["file"]["name"]);

And it makes me have the following error:
Warning: move_uploaded_file(bimages/1208169998283s.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/xenzone/public_html/lulzchan.com/scripts/newthread.php on line 53

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpDExsnc' to 'bimages/1208169998283s.jpg' in /home/xenzone/public_html/lulzchan.com/scripts/newthread.php on line 53
Thread created, file 1208169998283s.jpg uploaded!
Now going to your new thread.
 
Try giving it an absolute path instead of just "bimages".

Btw, lulzchan.. :(

4chan is teh win

Doesn't work either. Meh, I'll figure it out and run Wakaba in the meantime. Thank you, anyways!
PS: 4chan is full of fail these days. Except the NoCussingClub raid which happened yesterday.

Edit -
I tried to run Wakaba, but my server doesn't run Perl at this moment and I am inpatient.
Anyone have any ideas with my problem?
 
Do it in steps,

PHP:
                // Save file
                if(!file_exists('/bimages'))
                     mkdir('/bimages');
                if(!file_exists('/bimages/'.$filename_encrypted.'.png'))
                {
                     copy($_FILES["file"]["name"], '/bimages/'.$filename_encrypted.'.png');
                     echo 'Thread created, file <i>' . $filename . '</i> uploaded!<br>
                     Now going to your new thread.';
                } else
                     echo 'File already exists.';
This should work just fine

Edit: I used the copy method as well
 
Do it in steps,

PHP:
                // Save file
                if(!file_exists('/bimages'))
                     mkdir('/bimages');
                if(!file_exists('/bimages/'.$filename_encrypted.'.png'))
                {
                     copy($_FILES["file"]["name"], '/bimages/'.$filename_encrypted.'.png');
                     echo 'Thread created, file <i>' . $filename . '</i> uploaded!<br>
                     Now going to your new thread.';
                } else
                     echo 'File already exists.';
This should work just fine

Edit: I used the copy method as well

I get this:
Warning: copy(120px-O_U.jpg) [function.copy]: failed to open stream: No such file or directory in W:\www\newthread.php on line 23
 
Well, what should I check for?

I don't really know, I don't work with apache a whole lot on permissions and such, I usually just go through the php ini and httpd.conf and see if anything sticks out like it might be causing a problem. Most likely in php.ini though, things like safe mode, upload options, etc etc.
 
Umm... do you guys REALLY know PHP ? or are you grasping at straws ?

else
{
// Save thread
$SQL = "INSERT INTO `threads` (name, tripcode, email, subject, comment, date, image, encimage)
VALUES ('$name', '$tripcode', '$email', '$subject', '$comment', '$date', '$filename', '$filename_encrypted')";
mysql_query($SQL) or die(mysql_error());

// Save file
move_uploaded_file($_FILES["file"]["name"], "/bimages/" . $filename_encrypted . ".png");
echo "Thread created, file <i>" . $filename . "</i> uploaded!<br>
Now going to your new thread.";
}

YOU CAN'T MOVE A FILE THAT HAS NOT BEEN UPLOADED !
before you use move_uploaded_file(src, desc); you have to call copy(src, dest);

move_uploaded_file only checks and moves already uploaded files, it does NOT upload the file for you beforehand, that you have to do yourself.
 
Umm... do you guys REALLY know PHP ? or are you grasping at straws ?



YOU CAN'T MOVE A FILE THAT HAS NOT BEEN UPLOADED !
before you use move_uploaded_file(src, desc); you have to call copy(src, dest);

move_uploaded_file only checks and moves already uploaded files, it does NOT upload the file for you beforehand, that you have to do yourself.

You don't make any sense.

I've made many professional applications handling file uploads with no problem, I don't believe you really understand what's going on.


In addition, what's this nonsense about copy? It is absolutely not required.

http://us.php.net/manual/en/function.move-uploaded-file.php

This is very basic.

Also, Cask, from that page:

Note: move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Have you checked both of these in the INI file?
 
Not the finished product, gotta clean it up and add some more stuff later.

PHP:
<?php
	/*
		MySQL Connection here, wasn't needed so took it out for RZ.
															*/
	
	$name		= $_POST['name'];
	$tripcode	= $_POST['tripcode'];
	$email		= $_POST['email'];
	$subject	= $_POST['subject'];
	$comment	= $_POST['post-text'];
	$date		= date("F j, Y, g:i a");
	if ($name == "")
	{
		$name = "Anonymous";
	}
	if ($tripcode != "")
	{
		$tripcode = substr(md5($tripcode . "RE@#"), 1, 6);
	}
	
	if ((($_FILES["file"]["type"] == "image/gif")
	|| ($_FILES["file"]["type"] == "image/jpeg")
	|| ($_FILES["file"]["type"] == "image/png")
	|| ($_FILES["file"]["type"] == "image/pjpeg"))
	&& ($_FILES["file"]["size"] < 20000))
	  {
	  if ($_FILES["file"]["error"] > 0)
	    {
		    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
	    }
	  else
	    {
	    if (file_exists("bimages/" . $_FILES["file"]["name"]))
	      {
			echo $_FILES["file"]["name"] . " already exists. ";
	      }
	    else
	      {
				// Create Thread
				$encimage = rand(1000000000, 9999999999) . rand(1000000000, 9999999999);
				$SQL = "INSERT INTO `threads` (name, tripcode, email, subject, image, encimage, comment, date)
					VALUES ('$name', '$tripcode', '$email', '$subject', '" . $_FILES["file"]["name"] . "', '$encimage', '$comment', '$date')";
				mysql_query($SQL);
				
				// Save File
				move_uploaded_file($_FILES["file"]["tmp_name"], "bimages/" . $encimage . ".jpg");
				echo 'File uploaded, now going to your thread.';
				
				// Get the thread ID (will be latest thread `ID` in `threads`)
				$sql = mysql_query("SELECT * FROM `threads` WHERE `ID` = (SELECT MAX(ID) FROM `threads`)");
				while ($get == mysql_fetch_array($sql)) { $latest_thread = $get['ID']; }
				$threadID = $latest_thread + 1;
				gopage("/thread.php?id=$threadID", "3");
	      }
	    }
	  }
	else
	  {
		  echo "Invalid file";
	  }
?>
 
Not the finished product, gotta clean it up and add some more stuff later.

PHP:
<?php
    /*
        MySQL Connection here, wasn't needed so took it out for RZ.
                                                            */
 
    $name        = $_POST['name'];
    $tripcode    = $_POST['tripcode'];
    $email        = $_POST['email'];
    $subject    = $_POST['subject'];
    $comment    = $_POST['post-text'];
    $date        = date("F j, Y, g:i a");
    if ($name == "")
    {
        $name = "Anonymous";
    }
    if ($tripcode != "")
    {
        $tripcode = substr(md5($tripcode . "RE@#"), 1, 6);
    }
 
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/png")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 20000))
      {
      if ($_FILES["file"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        if (file_exists("bimages/" . $_FILES["file"]["name"]))
          {
            echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
                // Create Thread
                $encimage = rand(1000000000, 9999999999) . rand(1000000000, 9999999999);
                $SQL = "INSERT INTO `threads` (name, tripcode, email, subject, image, encimage, comment, date)
                    VALUES ('$name', '$tripcode', '$email', '$subject', '" . $_FILES["file"]["name"] . "', '$encimage', '$comment', '$date')";
                mysql_query($SQL);
 
                // Save File
                move_uploaded_file($_FILES["file"]["tmp_name"], "bimages/" . $encimage . ".jpg");
                echo 'File uploaded, now going to your thread.';
 
                // Get the thread ID (will be latest thread `ID` in `threads`)
                $sql = mysql_query("SELECT * FROM `threads` WHERE `ID` = (SELECT MAX(ID) FROM `threads`)");
                while ($get == mysql_fetch_array($sql)) { $latest_thread = $get['ID']; }
                $threadID = $latest_thread + 1;
                gopage("/thread.php?id=$threadID", "3");
          }
        }
      }
    else
      {
          echo "Invalid file";
      }
?>

Instead of a rand like that, just use time(), this is what the real 4chan does. You may rather append to the current time() a random 5 or so digit numeric string to ensure that you don't get collisions from posts made almost at the same time.
 
Back