How to upload files to

How to upload files to

How do you upload your files to a web server?

This article shows you how to publish your site online using file transfer tools.

Prerequisites:You must know what a web server is and how domain names work. You must also know how to set up a basic environment and how to write a simple webpage.
Objective:Learn how to push files to a server using the various file transfer tools available.

Summary

If you have built a simple web page (see HTML basics for an example), you will probably want to put it online, on a web server. In this article we’ll discuss how to do that, using various available options such as SFTP clients, RSync and GitHub.

There are several SFTP clients out there. Our demo covers FileZilla, since it’s free and available for Windows, macOS and Linux. To install FileZilla go to the FileZilla downloads page, click the big Download button, then install from the installer file in the usual way.

Note: Of course there are lots of other options. See Publishing tools for more information.

Open the FileZilla application; you should see something like this:

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Logging in

We have just opened an account and received this info from them:

Congratulations for opening an account at Example Hosting Provider.

Your account is: demozilla

Your website will be visible at demozilla.examplehostingprovider.net

To publish to this account, please connect through SFTP with the following credentials:

Let’s first look at http://demozilla.examplehostingprovider.net/ — as you can see, so far there is nothing there:

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Note: Depending on your hosting provider, most of the time you’ll see a page saying something like «This website is hosted by [Hosting Service].» when you first go to your web address.

To connect your SFTP client to the distant server, follow these steps:

Your window should look something like this:

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Now press Connect to connect to the SFTP server.

Note: Make sure your hosting provider offers SFTP (Secure FTP) connection to your hosting space. FTP is inherently insecure, and you shouldn’t use it.

Here and there: local and remote view

Once connected, your screen should look something like this (we’ve connected to an example of our own to give you an idea):

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Let’s examine what you’re seeing:

Uploading to the server

Our example host instructions told us «To publish on the web, put your files into the Public/htdocs directory.» You need to navigate to the specified directory in your right pane. This directory is effectively the root of your website — where your index.html file and other assets will go.

Once you’ve found the correct remote directory to put your files in, to upload your files to the server you need to drag-and-drop them from the left pane to the right pane.

Are they really online?

So far, so good, but are the files really online? You can double-check by going back to your website (e.g. http://demozilla.examplehostingprovider.net/ ) in your browser:

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

And our website is live!

Rsync

Rsync is a local-to-remote file synchronizing tool, which is generally available on most Unix-based systems (like macOS and Linux), but Windows versions exist too.

It is seen as a more advanced tool than SFTP, because by default it is used on the command line. A basic command looks like this:

You’d need to get such details from your hosting provider.

You can find more details of what is needed at How To Copy Files With Rsync Over SSH.

Rsync GUI tools

GUI tools are available for Rsync (for those who are not as comfortable with using the command line). Acrosync is one such tool, and it is available for Windows and macOS.

Again, you would have to get the connection credentials from your hosting provider, but this way you’d have a GUI to enter them in.

GitHub

GitHub allows you to publish websites via GitHub pages (gh-pages).

We’ve covered the basics of using this in the Publishing your website article from our Getting started with the Web guide, so we aren’t going to repeat it all here.

However, it is worth knowing that you can also host a website on GitHub, but use a custom domain with it. See Using a custom domain with GitHub Pages for a detailed guide.

Other methods to upload files

The FTP protocol is one well-known method for publishing a website, but not the only one. Here are a few other possibilities:

How to Upload Files to a Server with Plain JavaScript and PHP

Writing the code to upload images to a server from scratch seems like a very daunting task. I’m going to make a very simple upload form to demonstrate how file data works and can be transferred.

In this tutorial, we’re going to build an upload form with HTML, send the files with JavaScript, and process and upload them with PHP.

Note that this is not meant to be fully functional, secure, validated, production code. It is simply meant to demonstrate in a simple and straightforward manner how to make your first upload form.

As mentioned in the prerequisites, you must have a basic knowledge of PHP and local server environments.

If you already know how to use PHP and local environments, skip to the next section.

In the Terminal application, which I’ll open by pressing SPACEBAR + COMMAND and typing Terminal, navigate to the directory you created your file in.

You should now be able to go to http://localhost:8888/test.php and see the output of the code.

If you’re on Windows, or you don’t want to use the command line, set up MAMP.

Building an Upload Form in HTML

In the root of your local server, create an index.html file. We’ll just create a quick skeleton.

In this form, we’re using the POST HTTP method, which how we send data. The multipart/form-data value is required for uploading files in forms.

Finally, we have a submit button. Since the next step will be to add a script, let’s just add a link to the JavaScript file we’ll create.

And that’s all we need for the view.

Sending Form Data via JavaScript

Right now, clicking submit on the form doesn’t go anywhere. Since we don’t have an action that leads to a URL, the form will just post to itself by default. Since index.html is an html file, not a PHP file, no form processing can happen on this page. Instead, we’ll send the form to PHP through JavaScript.

Create a file called upload.js.

We’re going to add an event listener to watch for the form being submitted, but we’ll prevent the default action from firing.

For each file that has been submitted, append it to the files[] array.

Finally, use the built-in Fetch API to POST the data to the URL we specified. Print the response to the console (for testing purposes).

Here is the completed upload.js.

Once you have this file, attempt uploading a few files through the form. I made a phplogo.png and testfile1.txt to test with, and uploaded the file.

In Developer Tools, under the Console, you should see a response like this:

Now we know the proper files, along with all their associated data, have gone through. Success!

Processing Form Data with PHP

Now that we’re gathering all the files from the form and sending them to process.php with JavaScript, we have to move the file data with PHP.

First, we’ll want to make sure the code only runs when a POST request hits the file.

We also want to make sure files have gone through.

Create a directory in the root of your project called uploads. This directory will need to have 755 permissions to accept incoming files.

At this point, we’ll create an array for errors, set the path of the directory where uploads should go, and set the approved extensions.

Now, for each file we’ll get the file name, temporary file data, type, size, and extension.

Now we can set a few rules for the files. If the file type in not in the approved list of extensions, or the file is too large, we’ll add it to the error array. I set a file size of 2 megabytes.

If there were no errors, we can go ahead and move the file to the uploads folder with the move_uploaded_file command.

Put it all together, and here’s process.php.

Now test it out. If you use the form to upload some files, you’ll see them in the uploads folder. If you try to upload a file that’s too large or of the wrong type, you’ll see the errors in the Network response.

The complete source is on GitHub.

Note that this is not a complete, secure, production process. Here are a few things to take into consideration:

Thanks for reading. I can also make one about uploading to Amazon S3 and/or DigitalOcean Spaces if there’s interest.

Comments

About me

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Hello and thanks for visiting! My name is Tania Rascia, and this is my website and digital garden. 🌱

I’m a software developer who writes articles and tutorials about things that interest me. This site is and has always been free of ads, trackers, social media, affiliates, and sponsored posts.

I hope you enjoy the post and have a nice day.

How to Upload a File in PHP (With an Example)

In this article, I’ll explain the basics of file upload in PHP. Firstly, we’ll go through the PHP configuration options that need to be in place for successful file uploads. Following that, we’ll develop a real-world example of how to upload a file.

Configure the PHP Settings

There are a couple of PHP configuration settings that you’ll want to check beforehand for successful file uploads. In this section, we’ll go through every important option in regards to PHP file upload. These options can be configured in the php.ini file.

If you’re not sure where to find your php.ini file, you can use the php_ini_loaded_file() to locate it. Just create a PHP file on your server with the following line, and open it from the browser.

Here’s an excerpt from a setup file with some useful defaults.

The Key Settings

file_uploads

upload_max_filesize

The upload_max_filesize directive allows you to configure the maximum size of the uploaded file. By default, it’s set to 2M (two megabytes), and you can override this setting using the .htaccess file as well. Two megabytes isn’t very much by today’s standards, so you might have to increase this. If you get an error that file exceeds upload_max_filesize when you try to upload a file, you need to increase this value. If you do, be sure to also increase post_max_size (see below).

upload_tmp_dir

Sets a temporary directory which will be used to store uploaded files. In most cases, you don’t need to worry about this setting. If you don’t set it, the system default temp directory will be used.

post_max_size

max_file_uploads

max_input_time

It’s the maximum number of seconds a script is allowed to parse the input data. You should set it to a reasonable value if you’re dealing with large file uploads. 60 (60 seconds) is a good value for most apps.

memory_limit

max_execution_time

It’s the maximum number of seconds a script is allowed to run. If you’re facing issues when uploading large files, you can consider increasing this value. 30 (30 seconds) should work well for most apps.

Now let’s build a real-world example to demonstrate file upload in PHP.

Create the HTML Form

Once you’ve configured the PHP settings, you’re ready to try out the PHP file upload capabilities.

Our GitHub repo has some sample code which I’m going to discuss throughout this article. So, if you want to follow along, go ahead and download it from GitHub.

We’re going to create two PHP files: index.php and upload.php. The index.php file holds code which is responsible for displaying the file upload form. On the other hand, the upload.php file is responsible for uploading a file to the server.

Also, a file will be uploaded in the uploaded_files directory, so you need to make sure that this folder exists and is writable by the web-server user.

In this section, we’ll go through the key parts of the index.php file.

Let’s take a look at the index.php file on GitHub:

You can use the following CSS to give the form a more appealing look.

The CSS basically hides the original file input and styles its accompanying span and label elements.

Although it may look like a typical PHP form, there’s an important difference in the value of the enctype attribute of the tag. It needs to be set to multipart/form-data since the form contains the file field.

The enctype attribute specifies the type of encoding which should be used when the form is submitted, and it takes one of the following three values:

Next, we output the file field, which allows you to select a file from your computer.

Apart from that, we’ve displayed a message at the top of the form. This message shows the status of the file upload, and it’ll be set in a session variable by the upload.php script. We’ll look more at this in the next section.

So that sums up the index.php file. In the next section, we’ll see how to handle the uploaded file on the server side.

Create the Upload Logic

In the previous section, we created the HTML form which is displayed on the client side and allows you to upload a file from your computer. In this section, we’ll see the server-side counterpart which allows you to handle the uploaded file.

Pull in the code from the upload.php file on GitHub. We’ll go through the important parts of that file.

In the upload.php file, we’ve checked whether it’s a valid POST request in the first place.

After validating the POST request, we check that the file upload was successful.

If the file upload is successful, we initialize a few variables with information about the uploaded file.

As the uploaded file may contain spaces and other special characters, it’s better to sanitize the filename, and that’s exactly we’ve done in the following snippet.

It’s important that you restrict the type of file which can be uploaded to certain extensions and don’t allow everything using the upload form. We’ve done that by checking the extension of the uploaded file with a set of extensions that we want to allow for uploading.

Finally, we use the move_uploaded_file function to move the uploaded file to the specific location of our choice.

The move_uploaded_file function takes two arguments. The first argument is the filename of the uploaded file, and the second argument is the destination path where you want to move the file.

Finally, we redirect the user to the index.php file. Also, we set the appropriate message in the session variable, which will be displayed to users after redirection in the index.php file.

How It All Works Together

Don’t forget to create the uploaded_files directory and make it writable by the web-server user. Next, go ahead and run the index.php file, which should display the file upload form which looks like this:

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files toHow to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Click on the Browse button—that should open a dialog box which allows you to select a file from your computer. Select a file with one of the extensions allowed in our script, and click on the Upload button.

That should submit the form, and if everything goes well, you should see the uploaded file in the uploaded_files directory. You could also try uploading other files with extensions that are not allowed, and check if our script prevents such uploads.

Resolving Common Errors

File Is Too Large

UPLOAD_ERR_INI_SIZE and UPLOAD_ERR_FORM_SIZE occur when the size of an uploaded file is more than the value specified in php.ini or the HTML form respectively. You can get rid of this error by increasing the upload size limits or letting users know about them beforehand.

Temporary Folder Is Missing

UPLOAD_ERR_NO_TMP_DIR is reported when the temporary folder to upload the file is missing. UPLOAD_ERR_NO_FILE is reported when there is no file to upload.

Partial Upload or Can’t Write to Disk

You will get UPLOAD_ERR_PARTIAL if the file could only be uploaded partially and UPLOAD_ERR_CANT_WRITE if the file could not be written to the disk.

A PHP Extension Stopped the File Upload

Sometimes, you will get the error UPLOAD_ERR_EXTENSION because some extension stopped the file upload. This one will require more investigation by you to figure out which extension caused the problem.

Learn PHP With a Free Online Course

Today, we discussed the basics of file upload in PHP. In the first half of the article, we discussed the different configuration options that need to be in place for file upload to work. Then we looked at a real-world example which demonstrated how file upload works in PHP.

If you want to learn more PHP, check out our free online course on PHP fundamentals!

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

10 useful HTML file upload tips for web developers

Subscribe to my newsletter and never miss my upcoming articles

Introduction

The ability to upload files is a key requirement for many web and mobile applications. From uploading your photo on social media to post your resume on a job portal website, file upload is everywhere.

As a web developer, we must know that HTML provides the support of native file upload with a bit of help from JavaScript. With HTML5 the File API is added to the DOM. Using that, we can read the FileList and the File Object within it. This solves multiple use-cases with files, i.e, load them locally or send over the network to a server for processing, etc.

In this article, we will discuss 10 such usages of HTML file upload support. Hope you find it useful.

At any point in time, if you want to play with these file upload features, you can find it from here,

The source code of the demo is in my Github repo. ✋ Feel free to follow as I keep the code updated with examples. Please give a ⭐ if you find it useful.

1. Simple file upload

We can specify the input type as file to use the file uploader functionality in a web application.

An input file type enables users with a button to upload one or more files. By default, it allows uploading a single file using the operating system’s native file browser.

On successful upload, the File API makes it possible to read the File object using simple JavaScript code. To read the File object, we need to listen to the change event of the file uploader.

First, get the file uploader instance by id,

Then add a change event listener to read the file object when the upload completes. We get the uploaded file information from the event.target.files property.

Observe the output in the browser console. Note the FileList array with the File object having all the metadata information about the uploaded file.

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Here is the CodePen for you with the same example to explore further

2. Multiple file uploads

We can upload multiple files at a time. To do that, we just need to add an attribute called, multiple to the input file tag.

Now, the file browser will allow you to upload one or more files to upload. Just like the previous example, you can add a change event handler to capture the information about the files uploaded. Have you noticed, the FileList is an array? Right, for multiple file uploads the array will have information as,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Here is the CodePen link to explore multiple file uploads.

3. Know about file metadata

Whenever we upload a file, the File object has the metadata information like file name, size, last update time, type, etc. This information can be useful for further validations, decision-making.

Here is the output for single file upload,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Use this CodePen to explore further,

4. Know about file accept property

We can use the accept attribute to limit the type of files to upload. You may want to show only the allowed types of images to browse from when a user is uploading a profile picture.

Note, in this case, the file browser automatically sets the file selection type as custom instead of all. However, you can always change it back to all files, if required.

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Use this CodePen to explore the accept attribute,

5. Manage file content

You may want to show the file content after a successful upload of it. For profile pictures, it will be confusing if we do not show the uploaded picture to the user immediately after upload.

We can use the FileReader object to convert the file to a binary string. Then add a load event listener to get the binary string on successful file upload.

Try selecting an image file in the CodePen below and see it renders.

6. Validate file size

As we have seen, we can read the size metadata of a file, we can actually use it for a file size validation. You may allow users to upload an image file up to 1MB. Let us see how to achieve that.

Try uploading a file of different sizes to see how the validation works,

7. Show file upload progress

The better usability is to let your users know about a file upload progress. We are now aware of the FileReader and the event to read and load the file.

The FileReader has another event called, progress to know how much has been loaded. We can use HTML5’s progress tag to create a progress bar with this information.

How about you try uploading a bigger file and see the progress bar working in the CodePen below? Give it a try.

8. How about directory upload?

Can we upload an entire directory? Well, it is possible but with some limitations. There is a non-standard attribute(at least, while writing this article) called, webkitdirectory that allows us to upload an entire directory.

Though originally implemented only for WebKit-based browsers, webkitdirectory is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative.

You can specify this attribute as,

This will allow you to select a folder(aka, directory),

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

User has to provide a confirmation to upload a directory,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Once the user clicks the Upload button, the uploading takes place. One important point to note here. The FileList array will have information about all the files in the uploaded directory as a flat structure. But the key is, for each of the File objects, the webkitRelativePath attribute will have the directory path.

For example, let us consider a main directory and other folders and files under it,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Now the File objects will have the webkitRelativePath populated as,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

You can use it to render the folder and files in any UI structure of your choice. Use this CodePen to explore further.

9. Let’s drag, drop and upload

Not supporting a drag-and-drop for file upload is kinda old fashion, isn’t it? Let us see how to achieve that with a few simple steps.

First, create a drop zone and optionally a section to show the uploaded file content. We will use an image as a file to drag and drop here.

Get the dropzone and the content areas by their respective ids.

Add a dragover event handler to show the effect of something going to be copied,

How to upload files to. Смотреть фото How to upload files to. Смотреть картинку How to upload files to. Картинка про How to upload files to. Фото How to upload files to

Next, define what we want to do when the image is dropped. We will need a drop event listener to handle that.

Try to drag and drop an image file in the CodePen example below and see how it works. Do not forget to see the code to render the dropped image as well.

10. Handle files with objectURLs

There is a special method called, URL.createObjectURL() to create an unique URL from the file. You can also release it by using URL.revokeObjectURL() method.

The DOM URL.createObjectURL() and URL.revokeObjectURL() methods let you create simple URL strings that can be used to reference any data that can be referred to using a DOM File object, including local files on the user’s computer.

A simple usage of the object URL is,

Use this CodePen to explore the object URL further. Hint: Compare this approach with the approach mentioned in #5 previously.

Conclusion

I truly believe this,

Many times a native HTML feature may be enough for us to deal with the use-cases in hands. I found, file upload is one such that provides many cool options by default.

Let me know if this article was useful to you by commenting below. You may also like,

If it was useful to you, please Like/Share so that, it reaches others as well. Please hit the Subscribe button at the top of the page to get an email notification on my latest posts.

You can @ me on Twitter (@tapasadhikary) with comments, or feel free to follow me.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!

How to upload files with PHP correctly and securely

in this post, I’ll show you how to upload files to your server using HTML and PHP and validate the files. I hope it’s useful for some of you and now happy coding 🙂

Security information

As you can see, there is a lot we need to take care of. Maybe it’s worth considering to use an already existing service. With Uploadcare you can upload and manage files quickly and easily via their PHP integration.

So, let’s move on and create our own, secure, file upload.

HTML Setup

Before PHP can handle files, we send them to PHP using a basic HTML form:

Exit fullscreen mode

PHP Validation

Now, let’s validate the file in the upload.php file.

Exit fullscreen mode

Exit fullscreen mode

Now we have the real information, let’s validate the filesize. We don’t want to allow users to upload empty files, so first, we check if the file size is greater than 0:

Exit fullscreen mode

And if anyone can upload files, you might want to set a limit of how large a file can be:

Exit fullscreen mode

Exit fullscreen mode

You can find a list of MIME-Types here (It’s in german, but there is a great table with all MIME-Types and file extensions).

Now let’s check if the type of the file is allowed:

Exit fullscreen mode

And we’re done with validating! In the last step, we move the file to our uploads directory (or wherever you want to). For this, I define a variable with my target directory, then grab the current filename and extension and build the new, target file path:

Exit fullscreen mode

Finally, move the file:

Exit fullscreen mode

That’s it! Now you have a secure file upload where you can strictly define which files can be uploaded and which not!

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *