Skip to content
Advertisement

File Upload form using php

i’m working on app that takes a shot from the camera and upload the picture to the server so this is my code:-

JavaScript

and upload.php :-

JavaScript

the problem is that this upload script is uploading the picture but its corrupted file with size of 0mb so how can i fix this problem

Advertisement

Answer

Some problems with your code…

onsubmit="event.preventDefault(); ...

…prevents the form from submitting the file provided by <input type="file" ... to the form action target: upload.php conventionally, such as clicking the submit button.

~

JavaScript

…your upload.php file simply writes a string that, if properly called for, gets sent from the server to the browser by way of HTTP.

NO Javascript is executed at this point.

If the browser calls upload.php by loading the page, you leave the current page and only load that string in the browser. If the browser calls upload.php by way of XHR, or Fetch, the page remains but you need to use Javascript to capture the STRING and do something with it.

~

JavaScript

In the PHP file, on the server, you are writing a string of Javascript code, which is sent as text to the browser to be executed there later. The browsers gets something like:

JavaScript

It’s okay to use PHP to send a Javascript string to the browser—however the problem is you’re providing a file path on the server. Once the Javascript string gets to the browser and evaluated it does not have access to the server file and directory structure, such as: uploads/filename.png

Since you’re attempting to execute a Javascript function named readfile(...) it appears you’re trying to use Javascript FileReader to access the file uploaded to the server, but FileReader only handles files on the client, and provided through a Javascript File or Blob object, or an input type="file" element, or a drag and drop process.


Keep in mind that PHP executes on the server, and only text gets sent to the browser. The browser then receives the text from the server and processes and renders it.

The PHP context on the server cannot execute Javascript, and the browser context (Javascript/DOM events) on the client cannot execute PHP.

You only have a text channel between the two. And the text channel is only invoked by a page load, or without a page load by using XHR, or Fetch. If you use XHR or Fetch you then need to use Javascript to handle the text received back from the server.


To take a photo, upload it to the server, and display the photo on the page, without reloading the page:

camera.html

JavaScript

upload.php

JavaScript

Get more information on this approach here: How to use HTML5 to capture a camera image .

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement