Ok I am to the point of pulling my hair out. I have been trying all day to get this to work right and nothing. Right now what this script is doing is when you go to upload the file it goes to the page and there is no image. I have no clue why aint it working right. I am still new at this file/image upload thing. I have tried a few different ways and nothing. Here is the upload.php code:
<?php
function dbConnect(){
// Connect to the database
$hostname="localhost";
$database="myDatabase";
$mysql_login="myLogin";
$mysql_password="myPassword";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
echo "This is the home page. I have successfully made a connection to my database and everything
is working as it should.";
}
}
$aryImages=array("image/jpeg","image/png");
$aryDocs=array("application/msword","application/pdf","video/x-msvideo");
$filename=filenameSafe($_FILES['upload']['name']);
$fileType=$_FILES["upload"]["type"];
if (in_array($_FILES["upload"]["type"],$aryImages)){
createThumb($fileType,$_FILES['upload']['tmp_name'],$filename,100,100);
}
elseif (in_array($_FILES["upload"]["type"],$aryDocs)){
move_uploaded_file($_FILES['upload']['tmp_name'],
"/home/valerie2/public_html/elinkswap/imagefolder/".$filename);
$aryColumns=array("sessionID"=>$curSess,"fileName"=>$filename,"fileType"=>$fileType,"thumbFileName"=>$thumbFilename,"dateCreated"=>date('Y-m-d H:i:s'));
dbInsert($filename,$aryColumns,$_FILES["upload"]["type"]);
}
else{
echo "File Uploaded";
}
}
function createThumb($type,$tmpname,$filename,$new_w,$new_h){
$thumbFilename="tmb-".$filename;
echo $type;
echo "<br>".$tmpname;
if (is_numeric(strpos($type,"jpeg"))){
$src_img=imagecreatefromjpeg($tmpname);
}
if (is_numeric(strpos($type,"png"))){
$src_img=imagecreatefrompng($tmpname);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y) {
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (is_numeric(strpos($type,"jpeg"))){
imagejpeg($dst_img,"/home/valerie2/public_html/elinkswap/upload/".$thumbFilename);
imagejpeg($src_img,"/home/valerie2/public_html/elinkswap/upload/".$filename);
}
if (is_numeric(strpos($type,"png"))){
imagepng($dst_img,"/home/valerie2/public_html/elinkswap/upload/".$thumbFilename);
imagepng($src_img,"/home/valerie2/public_html/elinkswap/upload/".$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
dbInsert($filename,$thumbFilename,$type);
}
function filenameSafe($filename) {
$temp = $filename;
// Lower case
$temp = strtolower($temp);
// Replace spaces with a ’_’
$temp = str_replace(" ", "_", $temp);
// Loop through string
$result = "";
for ($i=0; $i<strlen($temp); $i++) {
if (preg_match('([0-9]|[a-z]|_|.)', $temp[$i])) {
$result = $result.$temp[$i];
}
}
dbConnect();
$SQL="SELECT fileID FROM upload WHERE fileName='".$result."'";
//echo $SQL;
$rs=mysql_query($SQL);
echo mysql_num_rows($rs);
if(mysql_num_rows($rs)!=0){
$extension=strrchr($result,'.');
$result=str_replace($extension,time(),$result);
$result=$result.$extension;
}
return $result;
}
function dbInsert($filename,$thumbFilename,$type){
dbConnect();
$SQL="INSERT Into upload (fileName,thumbFileName,fileType) values('".$filename."','".$thumbFilename."','".$type."')";
//echo $SQL;
mysql_query($SQL);
}
?>
And this is my index.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File Upload</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
Select File: <input type="file" name="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
<input name="Submit" type="submit" value="Upload File">
</form>
</html>
Both these files are inside a folder name imagefolder only with a folder called upload. I have read so many things on the file/image and so many videos but I still aint understand why the picture wont show up.I even tried to do another way but it kept telling me invaild file type.
Your upload.php defines a lot of functions, but are they actually called somewhere? Some are calling each other, but none of them seems to be called from "always executed" code. You have to add some code which is executed in every case at executing this php file, e.g. after your dbInsert function:
function dbInsert($filename,$thumbFilename,$type){
dbConnect();
$SQL="INSERT Into upload (fileName,thumbFileName,fileType) values('".$filename."','".$thumbFilename."','".$type."')";
//echo $SQL;
mysql_query($SQL);
}
dbConnect();
But from a cursory glance I could't really determine if dbConnect is really the proper function to call - your functions seem a bit randomly interconnected; why is dbConnect calling createThumb, when createThumb is calling dbInsert, which in turn is calling dbConnect again? That will create an infinite recursion loop.
If I were you I'd start without any functions for testing the wanted behavior. You can always extract functionality to functions later on.
There seem to be a whole lot of functions, but they never get called, so nothing will happen I suppose.
Check the folder's Permission and simplify your code and try to echo something in each function in order to debug and then determine where does it stop then we can help you more
But most likely its a permission issue
Related
I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!
I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link
This is suppose to be pretty straight forward and is driving me mad!
I'm trying to upload a file in PHP and writing the file to MySQL as a blob.
Problem is that the site throws a "Undefined index" all the time when I'm trying to use the
$_FILES['file']['tmp_name'] property.
Here is my code :
<head>
<title>Upload Worksheet</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000" />
File :
<input type="file" name"file" id="file"><input type="submit" value="Upload">
</form>
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
?>
</body>
This is what the error message looks like :
I haven't even gotten to the database side, as I can't get past this stage.
I'm a PHP noob, so any help would be greatly appreciated!
You recieve that error message because the form is not sent, yet. When you hit the upload button, the form is sent to your server and PHP populates the $_POST and $_FILES array with data. However, the arrays are empty until that point. It is therefore good practice to check whether or not your data is set, like so:
if (isset ($_POST['upload']))
{
// upload logic here
if(!isset($_FILES['file']) || ($_FILES['file']['tmp_name'] == ''))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
This assumes you have a submit button named "upload".
The Above answer is perfect because you should check the for post values in order to run any code on those values but you can also try the following
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
if(isset($_POST))
{
if(array_key_exists('file',$_FILES))
{
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
?>
I am using textpad to create php scripts. Now is there anything I can use with textpad, or is there a way to debug with textpad. I am a few of my code echo out and I am still not getting the results I am wanting my page to do. So I am thinking my code needs some debugging. I will post the code below and I am sure many of you will agree it needs debugging too. I know alot of people are probally saying I should not use what I am using but this is what I am being tought to use.
<?php
function dbConnect(){
// Connect to the database
$hostname="localhost";
$database="tblFile";
$mysql_login="*****";
$mysql_password="*****";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
echo "I have successfully made a connection to my database and everything
is working as it should.";
}
}
$aryImages=array("image/jpeg","image/png");
$aryDocs=array("application/msword","application/pdf","video/x-msvideo");
$filename=filenameSafe($_FILES['upload']['name']);
$fileType=$_FILES["upload"]["type"];
if (in_array($_FILES["upload"]["type"],$aryImages)){
createThumb($fileType,$_FILES['upload']['tmp_name'],$filename,100,100);
}
elseif (in_array($_FILES["upload"]["type"],$aryDocs)){
move_uploaded_file($_FILES['upload']['tmp_name'],
"/home/valerie2/public_html/elinkswap/snorris/upload/".$filename);
$aryColumns=array("sessionID"=>$curSess,"fileName"=>$filename,"fileType"=>$fileType,"thumbFileName"=>$thumbFilename,"dateCreated"=>date('Y-m-d H:i:s'));
dbInsert($filename,$aryColumns,$_FILES["upload"]["type"]);
}
else{
echo "File Uploaded";
}
function createThumb($type,$tmpname,$filename,$new_w,$new_h){
$thumbFilename="tmb-".$filename;
echo $type;
echo "<br>".$tmpname;
if (is_numeric(strpos($type,"jpeg"))){
$src_img=imagecreatefromjpeg($tmpname);
}
if (is_numeric(strpos($type,"png"))){
$src_img=imagecreatefrompng($tmpname);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y) {
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (is_numeric(strpos($type,"jpeg"))){
imagejpeg($dst_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$thumbFilename);
imagejpeg($src_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$filename);
}
if (is_numeric(strpos($type,"png"))){
imagepng($dst_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$thumbFilename);
imagepng($src_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
dbInsert($filename,$thumbFilename,$type);
}
function filenameSafe($filename)
{
// Lower case
$filename = strtolower($filename);
// get extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// Replace spaces with a ’_’
$filename = str_replace(" ", "_", $filename);
// Replace non-alphanumerics (except underscores)
$filename = preg_replace('/\W/', '', $filename);
// append the timestamp
$filename = $filename . time();
// create an md5 hash
$result = md5($filename);
// ensure the string is safe for the db query
$result = mysql_real_escape_string($result);
dbConnect();
$SQL="SELECT fileId FROM tblFile WHERE fileName='".$result.".$ext'";
$rs = mysql_query($SQL);
if (mysql_num_rows($rs) > 0) {
$result = str_replace(".$ext", time(), $result);
$result = "$result.$ext";
}
return $result;
}
function dbInsert($filename,$thumbFilename,$type){
dbConnect();
$SQL="INSERT Into tblFile (fileName,thumbFileName,fileType) values('".$filename."','".$thumbFilename."','".$type."')";
//echo $SQL;
mysql_query($SQL);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File Upload</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
Select File: <input type="file" name="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
<input name="Submit" type="submit" value="Upload">
</form>
</html>
I have look up myself to see if there is anyway of debugging in textpad but I am getting nothing.
IMHO the easiest way to debug PHP with a non-PHP-IDE is establishing an external logfile.
In your .htaccess you can specify something like
php_value display_errors 1
php_value error_reporting 2147483647
php_value error_log /var/log/php/php_error.log
Make sure this file is writable for your webserver/php process.
Withing your code you can simply use the method error_log
to log stuff into your file.
I'm afraid you have to switch to a "bigger" IDE to be able to do some serius debugging. You must try Eclipse or NetBeans with Xdebug. If you do a Google search you will find lot of tutorial to setup a debugging environment with eclipse php xdebug or netbeans php xdebug.
If you need something very very simpler, but better than calling everytime an echo or a var_dump, you should try FirePHP with FirePHP extension for Firefox.
just by a simple copy paste in a editor with syntax highlight I saw that all the functions you wrote are in the dbConnect function and this doesn't look normal.
also, if you would indent your code it would be a lot easier to read it, so to spot problems. if your server has error reporting and error display on you should get some messages
How can I do a php and xhtml form that allows users to upload images and on submitting all the data is send to my e-mail?
By searching for tutorials on Google and learing it yourself. This is too broad a question to post on this site. Try it out yourself, and if you can come up with an specific question you don't have the answer for, ask it here. Here's something to get you started:
http://www.reconn.us/file_uploading.html
http://www.tizag.com/phpT/fileupload.php
http://www.litfuel.net/tutorials/mail2.htm
The main PHP site itself also includes some good information on the recommended practices and pitfalls, as well as some sample code - see the 'Handling file uploads' section.
Try this
<?
//print_r($_POST);
if($_POST["action"] == "Upload Image")
{
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['image_file']))
$error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['image_file']['name']);
//echo $imagename;
if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";
if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}
}
?>
<form method="POST" enctype="multipart/form-data" name="image_upload_form" action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>
<?
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>\n";
}
}
?>