Upload picture

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Locked
User avatar
sguy
Forum Commoner
Posts: 61
Joined: Sun Aug 10, 2003 2:44 am

Upload picture

Post by sguy »

I try to upload a picture & store the info about the picture
I faced some problem here, hope that u all can help me.....
the error message is "Can't open file!"
any codes need the be improved?
thanx...

If i use this code, i just can upload the file to the folder, not the info to the database....

Code: Select all

<?php
$uploaddir = './image/';
$uploadfile = $uploaddir . $_FILES['userfile']['name'];

print "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   print "File is valid, and was successfully uploaded. ";
   print "Here's some more debugging info:\n";
   print_r($_FILES);
} else {
   print "Possible file upload attack!  Here's some debugging info:\n";
   print_r($_FILES);
}
print "</pre>";
?>

upload.php

Code: Select all

<body bgcolor="#FFFFFF" text="#000000">
<form enctype="multipart/form-data" action="test.php" method="post">
 <input type="hidden" name="MAX_FILE_SIZE" value="50000" />
 Send this file: <input name="userfile" type="file" />
 <input type="submit" value="Send File" />
</form>
test.php

Code: Select all

<?php
include "./common.inc";
// Max packet size
   define("MAX_SQL",50000);
   $filehandle = fopen($tmp, "rb") or die( "Can't open file!" ); 
   $query=    "INSERT INTO files (name, type, size) VALUES(".
             $DB->quote($name).", ".
             $DB->quote($type).", ".
             $DB->quote($size).
             ")";

   // Execute Query
   $result = $DB->query($query);
   $file_id = mysql_insert_id();

// Copy the binary file data to the filedata table in sequential rows each containing MAX_SQL bytes
// Your table should have an index set to auto_increment
// Store the file_id to identify the data fragments
   while (!feof ($filehandle)) { 
       $data = base64_encode(fread($filehandle,MAX_SQL)); 
       $query = "INSERT INTO filedata (file_id, data) VALUES($file_id,"".$data."")";
       $result = $DB->query($query); 
   }
   fclose ($filehandle); 
?>

Decode the data fragments and recombine them:
<?php
   $file_id =$_GET ['file_id']; 
   $query ="select file_id, name, type, size from files where file_id='$file_id'";
   $result = $DB->query($query);
   $row= mysql_fetch_array ($result); 
   $type = $row ["type"]; 
   $name = $row ["name"]; 
   $size = $row ["size"]; 
   $file_id = $row ["file_id"]; 

   // get the file data
   $query = "select id, data from filedata where file_id='$file_id' ORDER by id";
   $result = $DB->query($query);

// decode the fragments and recombine the file
   $data = "";
   while ($row = mysql_fetch_array($result)) {
       $data .= base64_decode($row ["data"]);  
   }
   
// output the file
   header ("Content-type: $type"); 
   header ("Content-length: $size"); 
   header ("Content-Disposition: attachment; filename=$name"); 
   header ("Content-Description: PHP Generated Data"); 
   echo $data;
?>
common.inc

Code: Select all

<?php
$dbhost = "localhost";
$dbusername = "root";
$dbuserpassword = "";
$default_dbname ="upload";

$MYSQL_ERRNO = '';
$MYSQL_ERROR = '';
function db_connect() {
global $dbhost, $dbusername, $dbuserpassword, $default_dbname;
global $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbusername, $dbuserpassword);
if(!$link_id) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection failed to the host $dbhost.";
return 0;
}
else if(empty($dbname) && !mysql_select_db($default_dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error() {
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO: $MYSQL_ERROR";
}
?>

database table

create table files(
name varchar(50),
type varchar(30),
size varchar(30));

create table filedata(
file_id int auto_increment primary key,
data varchar(30));
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

In test.php before the line:
$filehandle = fopen($tmp, "rb") or die( "Can't open file!" );
put:
echo 'tmp is : '.$tmp.'<br />';

What does that output?
User avatar
sguy
Forum Commoner
Posts: 61
Joined: Sun Aug 10, 2003 2:44 am

Post by sguy »

the output:

tmp is :
Can't open file!
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

So $tmp isn't set. I don't see anywhere where you set it.

Also you'de be better off leaving the image on the filesystem and just storing the path/name of it in the database. There's no point storing binary data in the database which just stores it on the filesystem anyway, just skip the db step ;)
User avatar
sguy
Forum Commoner
Posts: 61
Joined: Sun Aug 10, 2003 2:44 am

Post by sguy »

i just a noob & start learning PHP, can u correct it for me?
got another way to do it?
thanx... :wink:

http://img.photobucket.com/albums/v202/ ... /photo.jpg

something like this... :wink:
User avatar
sguy
Forum Commoner
Posts: 61
Joined: Sun Aug 10, 2003 2:44 am

Post by sguy »

i want to check the file whether is a picture format..
but i faced some problem...
thanx...

Warning: Wrong parameter count for move_uploaded_file() in c:\phpweb\uploading.php on line 14

Code: Select all

<?php
include "./common.inc";
$conn = db_connect('$db');

$uploaddir = './image/';
$uploadfile = $uploaddir . $_FILES['userfile']['name'];

print "<pre>";
$image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile, $image_types)) {

  $name = $_FILES["userfile"]["name"];
  $size = $_FILES["userfile"]["size"];
  $type = $_FILES["userfile"]["type"];
	
	$result=mysql_query("insert into pic (image_id, image_name, image_type, image_size) values ('','$name','$type','$size')");

   	print "File is valid, and was successfully uploaded. ";
   	print "Here's some more debugging info:\n";
   	print_r($_FILES);

} else {
echo"Invalid picture format or file larger than 100kb.<br/>";
   print "Possible file upload attack!  Here's some debugging info:\n";
   print_r($_FILES);
}
print "</pre>";

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[php_man]move_uploaded_file[/php_man] wrote:bool move_uploaded_file ( string filename, string destination)
move_uploaded_file only takes 2 arguments.

use [php_man]getimagesize[/php_man]() to determine if it's a known image type.. check the returned mime-type against your array of "acceptable types" if in there, move it.. otherwise throw an error..
User avatar
sguy
Forum Commoner
Posts: 61
Joined: Sun Aug 10, 2003 2:44 am

Post by sguy »

thank you for your comments...
i can upload the picture file to the folder..
izit possible to change the picture file name according the the login name?
for example, when i login using ABC, the original picture pic.jpg change to ABC.jpg
thanks...

Code: Select all

<?php
include "./common.inc";
$conn = db_connect('$db');

$uploaddir = './image/';
$uploadfile = $uploaddir . $_FILES['userfile']['name'];

print "<pre>";

$image_info = @getimagesize($_FILES['userfile']['tmp_name']); 
if (!is_int($image_info[2]) || $image_info[2] < 0 || $image_info[2] > 16) { 

echo"Invalid file";
} 
else { 

move_uploaded_file($_FILES['userfile']['tmp_name'], "./image/".$_FILES['userfile']['name']); 

    $pext = getFileExtension($imgfile_name); 
    $pext = strtolower($pext); 

    $imgfile_name="wailoon.$pext";

    $final_filename = str_replace(" ", "_", $imgfile_name); 
    $newfile = $uploaddir . "/$final_filename"; 

 
  $name = $_FILES["userfile"]["name"];
  $size = $_FILES["userfile"]["size"];
  $type = $_FILES["userfile"]["type"];
	
	$result=mysql_query("insert into pic (image_id, image_name, image_type, image_size) values ('','$name','$type','$size')");

   	print "File is valid, and was successfully uploaded. ";
   	print "Here's some more debugging info:\n";
   	print_r($_FILES);
} 
print "</pre>";
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

since this thread is now a duplicate of the other thread, I'm locking it..
Locked