Upload an image to main domain to sub domain With Out Using Database

Upload an image to main domain to sub domain  With Out Using Database

To upload an image to one server and store it on a subdomain server, you can use cURL to perform a file transfer from one server to another. Here's a basic example of how you can structure your PHP script to achieve this:

Image File Form

<?php
<form action="" method="POST" id="imgsubmit">
<div class="image-preview-container">
    <div class="preview">
        <img id="preview-selected-image" />
    </div>
    <label for="file-upload">Upload image</label>
    <input type="file" class="form-control" name="dluserimage"id="file-upload" onchange="previewImage(event);">
</div>
            <input class="btn btn-info float-right" style="margin: 10px;" name="imgsubmit" type="submit" value="Submit">
        </form>
?>

Upload Your File Using Ajax

<script type="text/javascript">
$(document).ready(function() {
    // Event listener for file input change
    $('#file-uploads').on('change', function(event) {
        updateImagePreview(event, '#preview-selected-image_android');
    });

    // Event listener for form submission
    $('#imgandroidsubmit').submit(function(e) {
        e.preventDefault();

        // Form submission using Ajax
        var formData = new FormData(this);
        $.ajax({
            type: 'POST',
            url: './your_php_script.php', // Replace with the actual path to your PHP script
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                try {
                    // Parse the JSON manually
                    var jsonResponse = JSON.parse(response);
                    console.log('Response:', jsonResponse);

                    if (jsonResponse.status === 'success') {
                        console.log('Setting values:', jsonResponse.adminimage);

                        // Update the displayed image and its URL
                        $('#preview-selected-image_android').attr('src', jsonResponse.adminimage);
                        $('.bgimagediv img').attr('src', jsonResponse.adminimage);
                        $('.bgimagediv p').text(jsonResponse.adminimage);
                    }
                } catch (error) {
                    console.error('Error parsing JSON:', error);

                    // Log the response for debugging
                    console.log('Response:', response);
                }
            },
            error: function(error) {
                console.error('Ajax request failed:', error);
            }
        });
    });
});

// Function to update the image preview
const updateImagePreview = (event, previewElement) => {
    const imageFiles = event.target.files;
    const imageFilesLength = imageFiles.length;

    if (imageFilesLength > 0) {
        const imageSrc = URL.createObjectURL(imageFiles[0]);
        $(previewElement).attr('src', imageSrc);
    }
};
</script>

Upload Script (Main server):

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $adminimage_temp = $_FILES['dluserimage_android']['tmp_name'];
    $adminimage = $_FILES['dluserimage_android']['name'];

    // Set the remote upload path on Server B (subdomain)
    $upload_url = 'http://your.com/api/android/save-image.php';
    $upload_path = $upload_url . '?filename=' . $adminimage;
    // Use cURL to upload the file to the remote server
    $ch = curl_init();
    $fp = fopen($adminimage_temp, 'r');

    curl_setopt($ch, CURLOPT_URL, $upload_path);
    curl_setopt($ch, CURLOPT_PUT, 1);
    curl_setopt($ch, CURLOPT_INFILE, $fp);
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($adminimage_temp));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // Enable cURL error reporting
    curl_setopt($ch, CURLOPT_FAILONERROR, true);

    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        echo json_encode(array('status' => 'error', 'message' => 'Curl error: ' . curl_error($ch)));
    } else {
        echo $response;
    }

    curl_close($ch);
    fclose($fp);
} else {
    echo json_encode(array('status' => 'error', 'message' => 'Invalid request method'));
}

?>

Server B (Subdomain Script - save-image.php)

On the subdomain server, you need to have a script that accepts the incoming image and stores it in the desired directory. Ensure that the destination directory on Server B has the necessary write permissions.

Here's a simple example script for the subdomain server:

<?php
// Specify the path to your destination directory
$absolutePath = '/path/to/your/api/';
$destinationDirectory = $absolutePath;

if (!is_writable($destinationDirectory)) {
    error_log('Directory permissions: ' . substr(sprintf('%o', fileperms($destinationDirectory)), -4));
    echo json_encode(array('status' => 'error', 'message' => 'Destination directory is not writable.'));
    exit;
}

$filename = isset($_GET['filename']) ? $_GET['filename'] : 'default1.jpg';
$uploadedImage = file_get_contents('php://input');
file_put_contents($destinationDirectory . $filename, $uploadedImage);

// Provide the URL of the saved image in the response
// Use a relative URL or a full URL accessible from the internet


$imageUrl = 'http://aapi.datelah.com/api/android/' . $filename;

echo json_encode(array('status' => 'success', 'message' => 'Image successfully stored on the subdomain server.', 'imageUrl' => $imageUrl, 'filename' => $filename, 'imageTag' => "<img src='$imageUrl' alt='Uploaded Image'>"));
?>

Remember to replace /path/to/your/api/ with the actual path to your destination directory on Server B. Adjust the script URLs accordingly, and ensure that the permissions on the destination directory are correctly set.

Use PHP to find the current working directory:

  • You can use getcwd() function in PHP to get the current working directory. You can then append the relative path from there.

Here's an example using getcwd():

$relativePath = '/api/android/';
$absolutePath = getcwd() . $relativePath;

Remember that the exact way to obtain the absolute path might vary depending on your hosting environment and server configuration. After obtaining the absolute path, replace the placeholder in $destinationDirectory with the actual path.

$destinationDirectory = '/absolute/path/to/android/folder/';

To implement the solution, you'll need to follow these steps:

Step 1: Update Upload Script on Server A

Update the script on Server A (where the image is initially uploaded) to include cURL logic for transferring the image to Server B (subdomain). Use the PHP code provided in the previous responses for the "Upload Script (Server A)".

Step 2: Create Script on Server B (Subdomain)

Create a PHP script on Server B (subdomain) to handle the incoming image and save it to the desired directory. Use the PHP code provided in the previous responses for the "Subdomain Server (Server B)".

Step 3: Update URLs and Paths

Make sure to update the URLs and paths in both scripts:

  • On Server A, update the $upload_url variable to point to the PHP script on Server B.

  • On Server B, update the $destinationDirectory variable to the actual path where you want to store the images.

Step 4: Test the Solution

  1. Upload an image using the form on Server A.

  2. The script on Server A will use cURL to transfer the image to Server B.

  3. The script on Server B will receive the image, check permissions, and save it to the specified directory.

Example URLs:

Note:

  • Ensure that the destination directory on Server B has the necessary write permissions.

  • Make sure both servers can communicate with each other (no firewall issues).

  • Monitor the error logs on both servers if you encounter any issues.

If you have successfully tested this script and are able to save images on the subdomain server, that's great! You can now use this script as your endpoint for storing images from your main server.

Remember to replace placeholder URLs like http://your-server-a.com and http://YOUR.com with the actual URLs of your servers.

Remember to securely handle user input, especially when using filenames from query parameters. Ensure that the filenames are sanitized to prevent security vulnerabilities such as directory traversal attacks. Additionally, consider validating and sanitizing user input to prevent potential security issues. If you encounter any issues or have specific error messages, let me know so I can assist you further.

"share what you learn keep coding and keep learning !! "