upload a file in php

To upload a file using PHP, you'll need to use some HTML to create a form with the enctype attribute set to "multipart/form-data" to allow file uploads. The file will be sent to the server, where you'll need to write some PHP code to handle the upload.

Here's an example of how to upload a file using PHP:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file">Choose file to upload:</label>
    <input type="file" name="file" id="file">
    <input type="submit" name="submit" value="Upload">
</form>
233 chars
6 lines

The form's action attribute is set to "upload.php", which is where the PHP code to handle the upload will go. The form's method attribute is set to "post", since we're sending data to the server.

Notice the enctype attribute on the form element. This tells the browser that the form contains binary data (i.e. a file upload), so it needs to be encoded differently before it is sent to the server.

Now, let's take a look at the PHP code that will handle the file upload. In this example, we'll just move the uploaded file to a folder on the server:

main.php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
    echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
307 chars
9 lines

We first define a target directory where we want to save the uploaded file. We then use the move_uploaded_file function to move the uploaded file from its temporary location (specified by $_FILES["file"]["tmp_name"]) to the target directory with its original name (specified by basename($_FILES["file"]["name"])). If the file was moved successfully, we display a success message to the user. Otherwise, we display an error message.

gistlibby LogSnag