Volkan
Volkan

Reputation: 546

Pass POST data into a PHP function

I want to upload an image file with PHP. How can I pass POST data to a PHP function in another file, which will be executed when the submit button is clicked...

here is the form:

 <!-- edit users profile picture -->
<form method="post" action="edit.php" name="user_edit_profile_picture">
    <input type="file" name="profil_slika" id="profil_slika">
    <input type="submit" name="user_edit_submit_profile_picture">

    <?php
        $con = mysqli_connect("localhost","root","","login");
        $q = mysqli_query($con,"SELECT * FROM users WHERE user_name = '".$_SESSION['user_name']."'");
        while($row = mysqli_fetch_assoc($q)){
            echo $row['user_name'];
            if($row['image'] == ""){
                echo "<img width='100' height='100' src='profile_pictures/default_user.png' alt='Default Profile Pic'>";
            } else {
                echo "<img width='100' height='100' src='profile_pictures/".$row['image']."' alt='Profile Pic'>";
            }
            echo "<br>";
        }
    ?>
</form>

and this is another PHP file with function:

elseif(isset($_POST["user_edit_submit_profile_picture"])) {
                $this->editUserPicture($_POST['profil_slika']);
            }

and function body:

public function editUserPicture($profilimage){

        $slika = $_FILES[$profilimage]['tmp_name'];
echo $slika;
        move_uploaded_file($_FILES[$profilimage]['tmp_name'],"profile_pictures/".$_FILES[$profilimage]['name']);

}

Currently I am getting this error message when I click on submit:

Notice: Undefined index: image.jpg in C:\xampp\htdocs\advanced\classes\Login.php on line 55

Thank you in advance!

Upvotes: 1

Views: 3215

Answers (2)

Iffi
Iffi

Reputation: 588

Please replace your form tag with this and try:

<form method="post" action="edit.php" name="user_edit_profile_picture" enctype="multipart/form-data">

Function:

elseif(isset($_POST["user_edit_submit_profile_picture"])) {
    $this->editUserPicture('profil_slika');
}

Function body:

public function editUserPicture($profilimage){
        $slika = $_FILES[$profilimage]['tmp_name'];
        echo $slika;
        move_uploaded_file($_FILES[$profilimage]['tmp_name'],"profile_pictures/".$_FILES[$profilimage]['name']);

}

Upvotes: 1

user1544337
user1544337

Reputation:

Change this:

$this->editUserPicture($_POST['profil_slika']);

To this:

$this->editUserPicture('profil_slika');

And also add enctype="multipart/form-data" to the attributes of the HTML <form>.

The reason is that profil_slika will not be passed to the $_POST array. It will be in the $_FILES array, with key profil_slika. In other words, the key you need to use for the $_FILES array is the name of the HTML input, you don't need to use $_POST at all.

Upvotes: 1

Related Questions