toiteam
toiteam

Reputation: 61

Uploading Image with PHP to .txt File

I want to add an image upload field to my PHP contact form. I have contact.html which posts to contact.php. I write all data to a errors.txt file.

I want to be able to upload images and move it to an "upload" folder on the server while registering it in errors.txt file.

I have marked sections of upload with NOT WORKING comment. Please guide me.

contact.html

<html>
<head>
</head>

<body>
<form name="form1" method="post" enctype="multipart/form-data" action="contact.php"> 

<h1>Basic Info</h1>

Username: <input type="text" name="user">    
<br>Email: <input type="text" name="mail">
<option value="intermediate">Intermediate</option> <option value="advanced">Advanced</optio></select> 

    <!-- Image Upload Code - NOT WORKING -->
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">

<br> <input type="submit" name="submit" value="submit"> 

</form>
</body>

</html>

contact.php

<?php
if(isset($_POST['submit']))
{
    $username = $_POST['user'];

    $email = $_POST['mail'];

    $experience = $_POST['exp'];

    // IMAGE UPLOAD CODE - NOT WORKING

    $target_file = "uploads/" . basename ($_FILES["fileToUpload"]["name"]);

    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);


    //the data

    $data = "$username | $email | $experience | $target_file\n";


    //open the file and choose the mode

    $fh = fopen("errors.txt", "a");

    fwrite($fh, $data);


    //close the file

    fclose($fh);


    print "User Submitted";
}
?>

Upvotes: 0

Views: 1328

Answers (2)

Arsonik
Arsonik

Reputation: 2316

Maybe your HTML is malformed! Missing open <select> tag ?

Which cause your input type="file" to be ignored by your browser. Try this :

Username: <input type="text" name="user">    
<br>Email: <input type="text" name="mail">
<select name=exp>
<option value="intermediate">Intermediate</option>
<option value="advanced">Advanced</option>
</select>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<br> <input type="submit" name="submit" value="submit"> 

Upvotes: 1

Indra Kumar S
Indra Kumar S

Reputation: 2935

Your Upload folder name is upload or uploads ??. In your query, you said "upload" folder.

     $target_file = "uploads/" . basename ($_FILES["fileToUpload"]["name"]);

Upvotes: 1

Related Questions