John Davidson

php - How to send $_FILES to $_SESSION variable properly?

0 comments
Message:


I've recently started working on an Image Upload web application in PHP, and I plan on sending an $_FILES variable to another form, after being taken from a previous form.


For example:
form1 has an <input type="file" name="image">. After that,
form2 takes it using $_FILES['image'] and wants to send it to form3 via $_SESSION['image'] = $_FILES['image'].


The problem is, after I try to move_uploaded_file() using that session variable, the file isn't moved into the directory. My upload directory (in which I store all the images) is empty.


That's how I tried moving the file:


$file = "upload/".$link.".".pathinfo($_SESSION['file']['name'], PATHINFO_EXTENSION);
move_uploaded_file($_SESSION['file']['tmp_name'], $file);

Don't worry about $link. That's just some "key" I use in my links (a way to auto-generate the links).


I also tried declaring another $_FILES variable and assigning it the value of $_SESSION['file'], and then use it in move_uploaded_file(), but still didn't work.


My question is: is it possible to correctly pass a $_FILES variable to $_SESSION? If yes, how does it come that it doesn't work in my case. What did I do wrong?


If you need more code and (or) information, feel free to leave a comment and I'll provide it to you as soon as possible.



My Answer:
It is not recommended to store the $_FILES variable in the $_SESSION variable as it can lead to security vulnerabilities and potential issues with file uploads. Instead, you should store the file path or other necessary information in the $_SESSION variable and then use that information to move the uploaded file.

Here is an example of how you can achieve this:

In form1, after the file is uploaded, store the file path in the $_SESSION variable:

php
$_SESSION['image_path'] = 'upload/' . $link . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);


Then, in form2, retrieve the file path from the $_SESSION variable and use it to move the uploaded file:

php
$file = $_SESSION['image_path'];
move_uploaded_file($_FILES['image']['tmp_name'], $file);


This way, you are not storing the entire $_FILES variable in the $_SESSION variable, but just the necessary information to move the uploaded file. This should help resolve the issue you are facing with moving the file to the upload directory.

Rate this post

3 of 5 based on 8680 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us