FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Uplaoding images using php form :::: Help needed





salman_500
hey,

as the topic heading states so....

how can i do this...

i have a php form and i want it to upload the images it links to.....

i want it to work in such a way that it automatically assigs that image a name e.g. "000012" and then enters this value into the database so that when that field is requested the image is shown..

plz help me on this...

i know how to display the image... just want a form that works in uploadin an image, assigning it a name, and then entering that name into database....

payin 30 Firh$'s to the one who helps me !!!
Maryndor
Unfortunately I haven't enought time to explain you this well, but will just give you some tips.

First of all your form should start like this:
<form id="gallery" name="gallery" method="post" action="upload.php" enctype="multipart/form-data">

please note that it's normal form tag but with enctype

and the input field (with "browse..." button) is this

<input name="image" type="file" id="image" maxlength="255">

also normal tag, just the difference is the type which is "file"

after submitting the file, it is automatically saved in temporary folder in server. then you should handle it from php.

there you have the $_FILE array variable. just like $_GET or $_POST.
in our case we should use $_FILE["image"] (because the input is named image)
the full file's path is stored in $_FILE["image"]["tmp_name"]. The file name is ["name"]
You can just use the function:
move_uploaded_file($_FILE["image"]["tmp_name"], "c:\storage\".$_FILE["image"]["name"]);
which is like copy&paste function from tmp_name to the c:\storage\ folder.

but if you wish some extras like preventing the same filenames use this code:

Code:
   $nr = 0;
   $forbidden_chars = strtr("$/\\:*?&quot;'&lt;&gt;|`", array('&amp;' => '&', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>'));
   $picture_name = strtr($_FILES["image"]["name"], $forbidden_chars, str_repeat('_', strlen("$/\\:*?&quot;'&lt;&gt;|`")));
   if (!preg_match("/(.+)\.(.*?)\Z/", $picture_name, $matches)){
      $matches[1] = 'invalid_fname';
      $matches[2] = 'xxx';
   }

   if ($matches[2]=='' || !stristr("GIF/PNG/JPG/JPEG/TIF/TIFF", $matches[2])) {
       die("<b>Invalid file or extension.</b>");
   }

   $picture_name = $matches[1] . '.' . $matches[2];
   while(file_exists("c:\storage\" . $picture_name)){
      $picture_name = $matches[1] . '~'. $nr++ .'.' . $matches[2];
   }


this first checks is the file's extension is gif/png etc. and second adds ~1 , ~2 etc after filename (ex. image~1.jpg) if image.jpg exsists.

now you can save (move) the file where you wish (in our case c:\storage\)

Code:

   if(!move_uploaded_file($_FILES["image"]["tmp_name"], "c:\storage\".$picture_name))
      die("<b>Error with file moving.</b>");



That's the basics. If you need some more help or more explanation just write me.
salman_500
hmm....
thnx for the reply...

this seems kinda confusing but i made somthin outta it....

now first of all...... wat does "c:/storage/" mean...... like is this the folder in the server that i will have to make in order for it to be moved there??

and can you also plz tell me where i have to add the codes... like that function... wher do i add it???

also i want it to be done that when a file is uploaded to a directory.... it is given a name... like i said before a numeric name... ...... like each new image is given a digit as a name which is next to the last... like 1.gif, 2.gif , 3.png, 4.jpg, etc ....... and then this vaule e.g. "1.gif" is then entered into the database along with all other fields that exist in the form.....

i hope you understand what i mean...

oh yea.... i got and example... like you upload a avatar for your phpbb forum or somthin......

plz help me with this... im still going to pay once i succesfully make this work for me.....

thnx ! Very Happy
Maryndor
Well, I rarely give an code to people, just trying to lead them to make code themself, but I'll make another exception. I'll make you code today (of the HTML and PHP) and will post it here plus some tries of explanation. Just wait a little. Wink

edit:

So, so.. here it is:

First of all I would like to tell you that you can download the files here. It's an .rar archive with needed files and structure.

So what I've done.
Created an folder "images". (this is an sub folder where is the php script). In that folder we are saving our images.

Created a file called file.dat and as content wrote just "1". Because you wish your files to be called 1.gif, 2.jpg, 3.png, 4.jpg as I understood. I use a flat file (simple file) to store the next number which will be used for file naming. Instead of file you can use Database to store your file numbering. I'm leaving this to yourself. Why I used file? Well, if I use loop the script could be slowed too much if there's hundred files in example.

Here's the html file - index.html

Code:
<!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 http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>Untitled Document</title>
</head>

<body>
<p>Please, click the <strong>Browse...</strong> button and choose your image.<br />
  Then click <strong>Submit</strong>.</p>
<form id="form1" name="form1" method="post" action="upload.php" enctype="multipart/form-data">
<input name="image" type="file" id="image" maxlength="255">
<br />
<input name="submitButton" type="submit" id="submitButton" value="Submit" />
</form>
</body>
</html>


A simple form, nothing more, nothing less. After pressing the "Submit" button it calls the upload.php which is like this:
Code:
<?php
/**
 * Uploading image
 * by Maryndor
 */

// some configuration
$folder = "images/";   // this is the folder where the images will be saved
                  // it is a sub-folder of where the php script is
                  // so be sure it's created and if linux server
                  // make it writable chmod 777

$filename = "file.dat"; // this is where we storage the next name of the file
                  // in our case number ;)

// First we check is the user clicked the "submit" button
// this is just passing some risks
if (isset($_POST["submitButton"])) {
   
  // After we are sure that user has been clicked button our job from now on
  // is to get that img and put in the wanted directory
 
  // Firstly we are doing some checks, like
  // is the file empty or goes something wrong with it like missing in example
  if($_FILES["image"]["tmp_name"] == "") {
     // Yup something wrong. We stops the execution of php script
    die("<b>ERROR:</b>The file is empty or no file specified");
   
  } else {
     // Well all is okay we continue

   // Here we are checking for valid filename and of course we must be sure
   // that file extension is some of our known for extension. We do not
   // wish to upload an .exe file, just we don't need it ;)
   $matches = array();
   $forbidden_chars = strtr("$/\\:*?&quot;'&lt;&gt;|`", array('&amp;' => '&', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>'));
   if (get_magic_quotes_gpc()) $_FILES["image"]["name"] = stripslashes($_FILES["image"]["name"]);
   $picture_name = strtr($_FILES["image"]["name"], $forbidden_chars, str_repeat('_', strlen("$/\\:*?&quot;'&lt;&gt;|`")));

   if (!preg_match("/(.+)\.(.*?)\Z/", $picture_name, $matches)) {
      $matches[1] = 'invalid_fname';
      $matches[2] = 'xxx';
   }
   
   if ($matches[2]=='' || !stristr("GIF/PNG/JPG", $matches[2])) {
      // Wrong .extension we stop the script. We accept only GIF PNG JPG
       die("<b>Invalid file or extension.</b> ".$matches[2]);
   }

   // Create a unique name for the uploaded file
   
   // Here we are number the file. 1.gif, 2.gif etc.
   // We are saving the number in file.dat
   // may be better use DB but here is just an example and I'm just giving you
   // a point. If we use loop (while,for etc) the script can be too slow
   // if there's hundred files, so we need to write our number somewhere (DB or
   // file like now). Later you can upgrade your script and make it better.
   // Personally I do not want to use numbering 1,2,3 but just original names
   // of the file, anyway you wish to be like that and here it is.
   
   $handle = fopen($filename, "r+");         // open the file
   $nr = fread($handle, filesize($filename));   // getting the contents
   rewind($handle);                     // rewind file ;)
   fwrite($handle, $nr+1);                  // writing our next number
   fclose($handle);                     // close file
   
   // Now we are naming our file (first in variable)
   // $matches[1] is the original name of the file
   // $matches[2] is the extension (.gif/.jpg)
   // we use $nr + $matches[2] which means in example, 1.gif
   
   $picture_name = $folder . $nr .'.' . $matches[2];

   // moving the file to our folder
   if(!move_uploaded_file($_FILES["image"]["tmp_name"], $picture_name ))
      die("<b>Error with file moving.</b>");

   // Change file permission
   chmod($picture_name, octdec("0644"));

   echo("image uploaded");
   
   // below you can write your code to save the file info to db maybe
  }
   
} else {
   echo("script should be called from index.html");
}

?>


Almost all is commented in there. I recommend you to download the archive with files, test it and if it works try to understand it Wink (or if you're feeling like pro, copy/paste from here , but need to understand my blah-blah writings - what where should be placed Wink)
If any more help needed - PM or write here.

That's it... I hope I helped you somehow.
salman_500
hey thnx !! Very Happy Very Happy

i havent tested it yet... but it most probably works !! Very Happy Very Happy

well just a two more things......

first of all .... i alrady have a form... this is its code.

Code:
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>">
                      ............(other fields)............
                        <br>
                        Image : * <br>
                        <input name="image" type="text" id="image">
                        <br>
                        </span>(<span class="style10"> <br>
                        <br>
                       ............(other fields)............
                </form>


how can i make this field into a field that uploads the image????


also one more thig... how can i do so that when a new name is assigned to the image... that new name is then entered/inserted into the database just like the other fields are doing..... i want it so that the image is uplaoded, renamed and then the new name is entered into the database so i can the display it the same way as i do with other fields of the database...

tell me this.. and you fre to go with some good amount of Froh$'s !! Very Happy Very Happy Smile Surprised Laughing Cool
Maryndor
1:

As I told you in my first post here, you should add enctype. So,

Code:
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>">


should looks like

Code:
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>" enctype="multipart/form-data">


and the input field, as I said should be type="file". In other words this:

Code:
<input name="image" type="text" id="image">


should be:

Code:
<input name="image" type="file" id="image">


The following code should be added in upload.php just after
Code:
echo("image uploaded");

in place of "// below you can write your code to save the file info to db maybe".

So, about the DB. I don't know where are you gonna use this script and I hope you know how to handle mysql Razz. But if you need to connect to mysql use this:

Code:
// Connecting to db
$db = @mysql_connect('localhost', 'your_db_username', 'your_db_password');

// selecting your database
@mysql_select_db('your_database_name', $db);


Here we are saving the filename in the db:
Code:
$imageFilename = $nr .'.' . $matches[2];
// inserting the record
mysql_query('insert into `images` set `filename`='".$imageFilename."';', $db);


If you're useing the connecting code, add as final this: mysql_close($db);
Just we wish to be nice with server Smile.

I think I've done my job, right?!
Philip
uhm, there is filename and extension detector Smile
cool man Smile

but i don't get although --"
*sorry*
can some one explain it for me ?

how is ths work ??
Code:
// Here we are checking for valid filename and of course we must be sure
   // that file extension is some of our known for extension. We do not
   // wish to upload an .exe file, just we don't need it ;)
   $matches = array();
   $forbidden_chars = strtr("$/\\:*?&quot;'&lt;&gt;|`", array('&amp;' => '&', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>'));
   if (get_magic_quotes_gpc()) $_FILES["image"]["name"] = stripslashes($_FILES["image"]["name"]);
   $picture_name = strtr($_FILES["image"]["name"], $forbidden_chars, str_repeat('_', strlen("$/\\:*?&quot;'&lt;&gt;|`")));

   if (!preg_match("/(.+)\.(.*?)\Z/", $picture_name, $matches)) {
      $matches[1] = 'invalid_fname';
      $matches[2] = 'xxx';
   }
   
   if ($matches[2]=='' || !stristr("GIF/PNG/JPG", $matches[2])) {
      // Wrong .extension we stop the script. We accept only GIF PNG JPG
       die("<b>Invalid file or extension.</b> ".$matches[2]);
   }
salman_500
hey ... your job almost done... i just done know how to do this...

you in my form tag i did this

Code:
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>" enctype="multipart/form-data">


but you may see that im not actually calling in "upload.php"..... how can i do this??? do i have to enter some code into the "$editFormAction" .. i dunno wat to add so heres the code of it... maybe you can figure ir out..

Code:
<?php
$currentPage = $_SERVER["PHP_SELF"];

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}


if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO housesale (...others..., image, ...others...) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       .....other string values...............
                       GetSQLValueString($_POST['image'], "text"),
                       .....other string values...............

  mysql_select_db($database_conn, $conn);
  $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());

  $insertGoTo = "index.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}


so do i need to add an include or require or somthin.... coz i dunno wat exactly to do heere.....


oh and yea by the way... when i tested your html index and tried uploading... i got this "

"Parse error: parse error in C:\Program Files\Apache Group\Apache2\htdocs\Real Estate\realestate\upload.php on line 91"

where line 91 happens to be this in my case:

here.... maybe the problem is that im not assigning it to enter the data into a field... i treid change the "image" below to the name of the database... but im not sending it into a field "image".... maybe u missed somthin out.....

"mysql_query('insert into `image` set `filename`='".$imageFilename."';', $db);"

so maybe somthin is rong here...

and i entered the mysql query in "upload.php" like this :

Code:
// moving the file to our folder
   if(!move_uploaded_file($_FILES["image"]["tmp_name"], $picture_name ))
      die("<b>Error with file moving.</b>");

   // Change file permission
   chmod($picture_name, octdec("0644"));

   echo("image uploaded");
   
   // Connecting to db
   $db = @mysql_connect('localhost', 'root', '');

   // selecting your database
   @mysql_select_db('realestate', $db);

   $imageFilename = $nr .'.' . $matches[2];
   // inserting the record
   mysql_query('insert into `image` set `filename`='".$imageFilename."';', $db);

   mysql_close($db);
  }
   
} else {
   echo("script should be called from index.php");
}

?>





just these last things and im all sett and you can go..lol Surprised

Thnx man.. really appreciate your effort ! i learnt alot Very Happy
Maryndor
Code:
mysql_query('insert into `image` set `filename`='".$imageFilename."';', $db);


should be

Code:
mysql_query("insert into `image` set `filename`='".$imageFilename."';", $db);


just my mistake I wrote ' instead of " Wink This should work.
About the upload.php, here it is I knew that you will use other script. Well you can use include('upload.php'); at the beggining maybe, just after <?php
and you shouldn't have problems.

--

Philip, this works with regular expressions. I'm chopping the filename and I have three arrays $matches[0] is whole name [1] is the filename [2] is the extension, I'm checking the extension with stristr function.
I saw your post about checking file, will write there.
salman_500
hey,

that correction works perfectly fine with html file that you sent... but do you think the code for upload.php is coming in conflict with my add.php

can you plz check this for me as i think you being the riter of thr upload script mite know what is botherin it....

this is the code that enters all other data present in the same form as the field "image"... i have 10 other fields and 1 text area..... so it all has to go in one form because all goes in one database that is named "housesale" .. the image field is known as image, that contains the name of the image...

Note : This is a Real Estate site Very Happy

Code:
<?php
$currentPage = $_SERVER["PHP_SELF"];

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}


if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO housesale (address, society, `size`, portions, bedrooms, bathrooms, kitchens, owner, mobile, office, image, description) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['address'], "text"),
                       GetSQLValueString($_POST['society'], "text"),
                       GetSQLValueString($_POST['size'], "text"),
                       GetSQLValueString($_POST['portions'], "text"),
                       GetSQLValueString($_POST['bedrooms'], "text"),
                       GetSQLValueString($_POST['bathrooms'], "text"),
                       GetSQLValueString($_POST['kitchens'], "text"),
                       GetSQLValueString($_POST['owner'], "text"),
                       GetSQLValueString($_POST['mobile'], "int"),
                       GetSQLValueString($_POST['office'], "int"),
                       GetSQLValueString($_POST['image'], "text"),
                       GetSQLValueString($_POST['description'], "text"));

  mysql_select_db($database_conn, $conn);
  $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());

  $insertGoTo = "index.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>


i tried the include option to put in the upload file in the "$editFormAction" but it did not work... instead it displayed this "script should be called from index.php" on the top left corner of the page above all other images all the time even before submiting....

and when i enterted data and browsed to the image and pressed submit...

this error was shown:

"script should be called from add.php
Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\Apache Group\Apache2\htdocs\Real Estate\realestate\upload.php:97) in C:\Program Files\Apache Group\Apache2\htdocs\Real Estate\realestate\add.php on line 125"

and line 125 in my age hapens to be this:

"
Code:
header(sprintf("Location: %s", $insertGoTo));
"

(also present in the code provided above, last line)

i tried removing this line...... and i also tried removing this "
Code:
else {
   echo("script should be called from add.php");
}


from upload.php...... but in both cases i got no success...

wen i removed the line fomr upload.php, i was redirected to the page i assigned it to using dreamweaver... the data was entered but image was not uploaded (i did this with "include" in my code).

in the other case... i was back on the same page with the error message on top of the page, message i stated above...

i know you mite be starting to get sick of this ... but plz plz plz help me solve this error.... ill pay you not 30 but 50 Frih$'s !!! Very Happy Smile

plz !!! Sad
Code:
Lyrics Center
dude for a simple and easy upload script go to www.zymic.com and click PHP theres an upload script there and its really easy to use you only need to set the permissions and add a few stuff thats shown there Neutral so you dont really need to giv ny one 30 FRi
salman_500
i know that.. but you see this way i can get customized scripsts so they work like i want them to.... thnx though but as you see these friH$'s are of no use to me now... as i got my own hosting and stuff... so i can use em to learn new stuff... Very Happy
Maryndor
I'm doing the job, just wait a little again. Wink
salman_500
thnx maryndor,

but i already have managed to make the script work for me....

its now wroking perfectly fine !!! Very Happy

wat i did was i devided the process in two steps.... the first being where we link to the file to be uploaded... the second being the upload itself.... i copied the script into a page that is step 2... there i just take the name of the file that is represented as "$imageFilename" into a hidden field and its value is uploaded to the database.. and hence the link to the uploaded file works !!! Very Happy

im a genius !!!!!!!!!!!11 Razz Cool
Maryndor
Heh, well, congratulations then ! Very Happy I'm glad it's all working fine. You can combine the two php files if you feel that you wish to do some tests, anyway congrats again. I'm glad that I could help you in some or other way Smile

Good Luck with PHP Smile
Related topics
[tutor] How to protect images without htaccess using PHP
Includ Images using PHP.
How to start using PHP? Help!
Website Designing using PHP
Php form.
I am trying to build a contact form using php and flash
Communicating between web pages
PHP Nuke Help
PHP Form Question
PHP, FORM HELP
Using php to change content of a .txt
Help needed with images in php include files
php project help needed please
Help displaying pdfs using PHP
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.