Develop an efficient file uploading API in PHP that is constantly updating and adapting

I have been working on developing a file upload API in PHP. Currently, I have created a simple PHP script that enables the uploading of files from an HTML page to a server. However, the code I have written has a fixed name for the file upload control, which means I need to pass that specific name in my PHP code to upload the file. My goal is to create this API to be used by third parties. If anyone requests the API, I want to provide them with a link that they can consume. Can someone please assist me in transforming this into a more dynamic solution?

Below is the HTML code:

<html>
<head>
 </head>
 <body>

 <h2>Upload Image </h2>
<form action="http://mvcangularworld.com/api.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="filename" value="" />
<br />
<input type="submit" value="Upload File"  />
</form>

</body>

</html>

And here is the PHP code for api.php:

<?php

// Path to move uploaded files
$target_path = 'images/';


$response = array();


$file_upload_url = $target_path;
$filename = $_POST['filename']; 
 if (isset($_FILES['filename']['name'])) 
{
    $target_path = $target_path . basename($_FILES['filename']['name']);
    // reading other post parameters
    echo $_FILES['filename']['name']."<br />";
    echo $_FILES['filename']['tmp_name']."<br />";

    $response['file_name'] = basename($_FILES['filename']['name']);

    try 
    {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) 
        {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }

        // File successfully uploaded
         //echo $file_upload_url . basename($_FILES['filename']['name']);
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['filename']['name']);
    } 
    catch (Exception $e) 
    {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} 

// Echo final JSON response to client
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>

Here is the API link:

Please assist me in making this API more dynamic.

Answer №1

To easily tackle this issue, consider incorporating a concealed field with the same name as the file field:

<input type="hidden" name="fileFieldName" value="filename" />

Then, on the server side:

$fileFieldName = $_POST['fileFieldName'];
move_uploaded_file($_FILES[$fileFieldName]['tmp_name']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send a PHP array back to jQuery AJAX and dynamically populate a list using conditional statements

Looking to create a dynamic contact list that can be sorted using AJAX. When selecting one of the 3 menu options, a new list with updated information should be displayed. I've been doing some research but haven't come across useful information o ...

Stop duplicate submissions made through ajax requests

I am currently using AJAX to generate a list of replies. At the end of the reply list, I have included a textarea form that allows users to add their own reply (also using AJAX). However, I am encountering an issue where I call my JavaScript in my main P ...

Uploading multiple files using PHP on an Ubuntu server

I have encountered an issue while attempting to upload multiple files in tsv and csv formats using PHP. The following HTML and PHP script has been included below. It successfully uploads files when executed with XAMPP on a Windows system. However, when I a ...

Bending the rules for inventory levels in WooCommerce

Currently, I am directing users to a Contact 7 Form and adding items to the cart using a specific href link: http://example.com/checkout/?add-to-cart=1000 I am faced with a unique scenario where if there is only 1 item left of product 1000, and the user s ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

Entering a string into Angular

Within my function, I trigger the opening of a modal that is populated by a PHP file template. Within this template, there exists a div element containing the value {{msg_text}}. Inside my JavaScript file, I initialize $scope.msg_text so that when the mod ...

Python program that runs a loop through a file, sends API requests using the `requests` library, and saves the results

Currently working on a program to loop through movie titles in a text file and make API calls to store the responses. The text file contains a single title on each line, for example: Titanic Avatar A Star Is Born The API being used is from a website ca ...

Challenges with integrating Wampserver PHP 5.3.1 and Pear:DB

After successfully installing PHP5.3.1 on top of 5.3.0 on my Windows 7 Pro laptop, along with Smarty, Pear and relevant Pear packages, I have encountered a strange issue. I have separate development and production sites set up using a config.php file - the ...

What is the most efficient way to load a PHP page once the webpage has completely finished loading?

I'm relatively inexperienced when it comes to PHP and JQuery, so please bear with me if my knowledge is limited. Currently, I'm facing an issue where loading a small HTML table that contains information queried from game servers (like shown in t ...

What is the most effective method for storing large volumes of data on a daily basis that can be categorized for statistical analysis?

I am currently creating a unique tracking tool tailored for marketing campaigns. This specialized tool acts as a mediator between advertisements and landing pages, responsible for recording all user data including user-agent information, IP addresses, clic ...

QCubed/QCodo LoadAll is not properly defined

Currently working on my application using the Qcubed framework and encountering the following error: Fatal error: Call to undefined method Users::LoadAll() in C:\xampp\htdocs\andret\admin\users.php on line 183 Any insights into w ...

Utilizing string manipulation with the help of preg_replace or str_replace

I have a requirement to swap one word with another. However, the following code snippet: $var= str_replace($linklabel[$k], $linklabelmod[$k], $var); is not producing the expected outcome. For instance, consider the input string: $var="the theory of them ...

Is there a requirement to download and set up any software in order to utilize Highchart?

I've been working on a project to create a program that displays highcharts, but all I'm getting is a blank page. Here's my code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charse ...

Decoding PHP Webservice Output on Android

I am currently working on consuming a PHP Web service using JSON in an Android app. After making a request to the server, I received the following response data: string(170) "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19" ...

Tips for selecting an <select> option value based on an URL parameter automatically

I have a 2-step form where I am successfully passing the first name in the URL from step 1 to step 2, but I am struggling to do the same for a select field. Here's an example of what I have: In the URL: ?firstname=Bob Form Field: <input type= ...

Hide elements forever once the form is submitted

I'm seeking help to figure out how to make certain elements disappear after a form submission on my website's dashboard page. Specifically, I need to hide three elements once the user has submitted a form. Elements that need to be hidden: .vc_t ...

PHP Prepared Statements with MySQLi: Slow Retrieval of Blob Field

To enhance security measures, I have incorporated a function that handles prepared statements. However, an issue has arisen when attempting to retrieve base64 encoded blob data (approximately 30-50KB) through this method. Unsurprisingly, executing the qu ...

The value of the variable increases, but when I pass it to a function, it does not behave as anticipated

I am experiencing a small issue with some code that I am using to determine if a browser is IE6 or IE7. I suspect that the problem lies in the $browserCheck variable. My initial goal was to have the $browserCheck variable increment, but for testing purpo ...

Error message "Authorization issue occurred while trying to call a function in the PHP webservice."

I am facing an issue with calling a web service. It successfully connects and returns its methods, however, when I call one of the functions, it throws an unauthorized error. Here is my code try { $service = new SoapClient("http://www.go-to-orbit.com/oo ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...