PHP File Uploading

please click here for more wordpress cource

In PHP, you can upload files to a server using a form with the enctype="multipart/form-data" attribute. Here is an example form:

<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="fileToUpload"> <input type="submit" value="Upload"> </form>

The action attribute specifies the URL of the script that will handle the upload, and the method attribute specifies the HTTP method (POST in this case).

In the upload.php script, you can access the uploaded file using the $_FILES superglobal variable. Here is an example script that saves the uploaded file to the server:

<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);

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

The move_uploaded_file function moves the uploaded file from the temporary location to the specified directory on the server.

Note that you should always validate the uploaded file to ensure that it is safe to use, and that you should not trust the filename provided by the client. You can use the pathinfo function to get the extension of the uploaded file, and check it against a list of allowed file types.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *