Search code examples
phpphpmyadminwebserver

How to store uploaded files in a directory of the main domain from a subdomain upload form


please how can store uploaded file in my main domain directory should it be like this:

move_uploaded_file(https://example.com/uploads)

Solution

  • First step is to start here with handling uploaded files:
    http://php.net/manual/en/function.move-uploaded-file.php

    The first example is almost exactly what you want:

    <?php
    $uploads_dir = '/uploads';
    foreach ($_FILES["pictures"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
            // basename() may prevent filesystem traversal attacks;
            // further validation/sanitation of the filename may be appropriate
            $name = basename($_FILES["pictures"]["name"][$key]);
            move_uploaded_file($tmp_name, "$uploads_dir/$name");
        }
    }
    ?>
    

    You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:

    $uploads_dir = __DIR__ . '/../public_html/uploads';
    

    __DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.

    The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.