PHP – how to save a file to a folder on the server? A simple task – but … is it so simple, especially for a beginner?
So, we will have the following technical task:
1. Creating a form with which we will receive the name of the file that we want to send to a folder on the server
2. Data processing in this form
3. Sending a file to the server
Go!
To solve the problem of creating a form – create it (who does not know how – you can read here). The form will consist of a “File” field and a button that submits data:
From the interesting – in the field with the “File” data type, we specifically narrow the possibility of uploading extraneous files to the server – we only allow images to be uploaded. This is done using accept=”image/*
As you can see from the form code, the add_to_base.php file will be responsible for data processing. It looks like this:
?php $path = "pic/".$_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'],$path)) { echo $_FILES['photo']['name'].' loaded'; } ?
Let’s look at the code in more detail:
$path = "pic/".$_FILES['photo']['name']
- the $path variable, which is formed from the directory where we will save the image on the server, and the file – which we receive from the form on the previous page (this file is passed here by name = “photo”).
if(move_uploaded_file($_FILES['photo']['tmp_name'],$path)) {
echo $_FILES['photo']['name'].' loaded';
move_uploaded_file – a function that checks if the file has been uploaded to the specified location or not? If yes, we display a notification.
As you can see, everything is simple 🙂
In the near future we will deal with the question: how to display a file located on our server on the site?
If you have any questions – write to mail, or Telegram.
Support the Blog!
Running a blog takes a lot of effort, time, and passion. Your donations help improve the content, inspire new ideas, and keep the project going.
If you’ve enjoyed the blog’s materials, any support would mean the world to me. Thank you for being here! ❤️