Jump to content

[SOLVED] adding username to image


runnerjp

Recommended Posts

hey guys... i got

 <?php
      if ($_POST['Submit']) {
        if ($_POST['MAX_FILE_SIZE'] >= $_FILES['file']['size']) {
          //print_r($_FILES);
                   $photo = addslashes(fread(fopen($_FILES['file']['tmp_name'], "r"),
$_FILES['file']['size']));
           $query = sprintf("INSERT INTO image(Image, FileType) VALUES
('%s', '%s')", $photo, $_FILES['file']['type']);
           if (mysql_query($query)) {
            $messages[] = "Your files is successfully store in database"; 
           } else {
            $messages[]= mysql_error();
           }
          } else {
           $messages[]="The file is bigger than the allowed size please resize";
          }
        }
      ?>

 

but how would i add it so the username would be the name of the image so i can upload username.jpg or g.f ect as there image profile

Link to comment
Share on other sites

  • Replies 128
  • Created
  • Last Reply

<?php
  if ($_POST['Submit']) {
    if ($_POST['MAX_FILE_SIZE'] >= $_FILES['file']['size']) {
      //print_r($_FILES);
      $photo = addslashes(
                 fread(
                   fopen($_FILES['file']['tmp_name'], "r"),
                   $_FILES['file']['size']
                 )
               );
      $query = sprintf("INSERT INTO image(Image, FileType) VALUES ('%s', '%s')",
                       $photo, $_FILES['file']['type']);
      if (mysql_query($query)) {
        $messages[] = "Your files is successfully store in database"; 
      } else {
        $messages[]= mysql_error();
      }
    } else {
      $messages[]="The file is bigger than the allowed size please resize";
    }
  }
?>

 

There's a few problems with your code.

 

The first is that you are comparing $_POST['MAX_FILE_SIZE'] with the uploaded file size.  Since $_POST['MAX_FILE_SIZE'] is coming from the client via a hidden parameter, it is unreliable.  The client can change the value of this field so you should not be using it for validation.

 

Second, in your fopen() call, you are opening the file with "r" which will cause the file to be treated as text.  You need to open in binary mode, "rb".

 

Third, you are relying on $_FILES['file']['type'] to determine the file's type.  This is provided by the browser and can be faked.  You should look into fileinfo:

http://www.php.net/fileinfo

 

but how would i add it so the username would be the name of the image so i can upload username.jpg or g.f ect as there image profile

Since you are storing the file directly in the database, this is irrelevant.  You are storing the raw image info in the database so no filename is necessary.  Which leads me to...

 

Fourth, this is not a problem with your code, but a recommendation.  Instead of storing the raw file information in the database, you should save the file on disk.  Then you store just enough information in the database to be able to find the file on the disk via a filepath.  How much information you're required to store in the DB in order to find the file again depends on what folder structure you choose.  In any case, when dealing with file uploads you should use the functions is_uploaded_file() and move_uploaded_file().  The second of those functions requires that you assign the file a name on the file system.  This is where you would rename the file to the user's name.

Link to comment
Share on other sites

ok guys i now got this

<?php
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","1000"); 

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
//and it will be changed to 1 if an errro occures.  
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit'])) 
{
	//reads the name of the file the user submitted for uploading
	$image=$_FILES['image']['name'];
	//if it is not empty
	if ($image) 
	{
	//get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['image']['name']);
	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
		$extension = strtolower($extension);
	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "bmp") &&($extension != "png") && ($extension != "gif")) 
		{
	//print error message
			echo '<h1>Unknown extension!</h1>';
			$errors=1;
		}
		else
		{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) 
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}

//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors) 
{
	echo "<h1>File Uploaded Successfully! Try again!</h1>";
}

?>

<!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data"  action="">
<table>
	<tr><td><input type="file" name="image"></td></tr>
	<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>	
</form>
  

 

bu how can i make it so a user can find it for their profile picture?

Link to comment
Share on other sites

However if you're using MyISAM tables and not InnoDB tables then you have no way to CASCADE any key changes, thus if someone changes their username you are scuppered. Thus it is common to use an id (auto_increment) as then use that as the primary key lookup and as a foreign key in other tables. If however you are using InnoDB tables then go ahead and use the username (just remember to put in your FOREIGN KEY references with cascades).

Link to comment
Share on other sites

ok i have nealry got it but still stuck

 

<?php

// Connect to database

$errmsg = "";
session_start();
  require_once '../settings.php';


// Insert any new image into database

if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"/images");
        $instr = fopen("images","rb");
        $image = addslashes(fread($instr,filesize("/images")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
        $title = htmlspecialchars($row[title]);
        $bytes = $row[imgdata];
} else {
        $errmsg = "There is no image in the database yet";
        $title = "no database image available";

}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>

 

it does not upload the image to the image folder  move_uploaded_file($_FILES['imagefile']['tmp_name'],"/images");

 

and i dont get how to add the users id and then call it from profile page??

Link to comment
Share on other sites

ok i now have simplyfield it

 

  <?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "username", "password");

//Select database, database_name needs to be changed
mysql_select_db("database_name");

if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" 
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>

<?
}else{
//if the form hasn't been submitted then:

//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved 
//into the database. The image is named after the persons IP address until it gets moved into the database

//get users IP
$id= get_username ( $_SESSION['user_id'] );

//don't continue if an image hasn't been uploaded
if (!empty($image)){

//copy the image to directory
copy($image, "./images/".$id."");

//open the copied image, ready to encode into text to go into the database
$filename1 = "./images/" get_username ( $_SESSION['user_id'] );
$fp1 = fopen($filename1, "r");

//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));

//close the file
fclose($fp1);

//encode the image into text
$encoded = chunk_split(base64_encode($contents1)); 

//insert information into the database
mysql_query("INSERT INTO images (img,data)"."VALUES ('NULL', '$encoded')");

//delete the temporary file we made
unlink($filename1);
}

//end
}
?> 

 

i am getting the error Parse error: syntax error, unexpected T_STRING in /home/runningp/public_html/members/upload.php on line 37

 

ould this work then by calling ther userid area in my db should get their image :D

Link to comment
Share on other sites

Have you still not fixed the error?

 

If not, then read the error:

Parse error: syntax error, unexpected T_STRING in /home/runningp/public_html/members/upload.php on line 37

 

These are the key parts:

unexpected T_STRING

upload.php

line 37

 

Here is line 37:

$filename1 = "./images/" get_username ( $_SESSION['user_id'] );

 

You forgot the . between "./images/" and get_username

$filename1 = "./images/" . get_username ( $_SESSION['user_id'] );

Link to comment
Share on other sites

doh lol didnt see that messed around with it for like an hour lol but now this wee lil problem occured

 

Warning: copy(./images/) [function.copy]: failed to open stream: Is a directory in /home/runningp/public_html/members/upload.php on line 31

 

Warning: unlink(./images/) [function.unlink]: Is a directory in /home/runningp/public_html/members/upload.php on line 50

 

 

even though i have www.website.com/members/images set up :S have i not done it right?

Link to comment
Share on other sites

The error is complaining about line 31:

if (!empty($image)){

 

I do not see $image being used before that line.

 

Place this before your current line 31 and tell me what it outputs:

echo '<pre style="text-align: left;">' . print_r($image, true) . '</pre>';

Link to comment
Share on other sites

I'm going to assume that $image is the uploaded file then.  If that's the case, don't use the copy() function.

 

Use move_uploaded_file().

 

If you reread my first post in this thread:

In any case, when dealing with file uploads you should use the functions is_uploaded_file() and move_uploaded_file().  The second of those functions requires that you assign the file a name on the file system.  This is where you would rename the file to the user's name.

 

Link to comment
Share on other sites

nooo now im getting

 

Warning: move_uploaded_file(./images/) [function.move-uploaded-file]: failed to open stream: Is a directory in /home/runningp/public_html/members/upload.php on line 31

 

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpbFtMG2' to './images/' in /home/runningp/public_html/members/upload.php on line 31

 

Warning: unlink(./images/) [function.unlink]: Is a directory in /home/runningp/public_html/members/upload.php on line 50

Link to comment
Share on other sites

this is the whole code... thanks for helping me out so much

 

 

<? session_start();
  require_once '../settings.php';?>

  <?php
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" 
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>

<?
}else{
//if the form hasn't been submitted then:

//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved 
//into the database. The image is named after the persons IP address until it gets moved into the database

//get users IP
$id= get_username ( $_SESSION['user_id'] );

//don't continue if an image hasn't been uploaded
if (!empty($image)){
echo '<pre style="text-align: left;">' . print_r($image, true) . '</pre>';
//copy the image to directory
move_uploaded_file($image, "./images/".$id."");

//open the copied image, ready to encode into text to go into the database
$filename1 = "./images/".  get_username ( $_SESSION['user_id'] );
$fp1 = fopen($filename1, "r");

//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));

//close the file
fclose($fp1);

//encode the image into text
$encoded = chunk_split(base64_encode($contents1)); 

//insert information into the database
mysql_query("INSERT INTO images (img,data)"."VALUES ('NULL', '$encoded')");

//delete the temporary file we made
unlink($filename1);
}

//end
}
?> 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • 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.