Ok so I have a HTML form which is using javascript to display an image thats uploaded here is my HTML code
<form action="/inc/sendtochan.php" method="post">
<label for="fname">Title:</label><br>
<input type="text" id="fname" name="title" value="" size="64"><br>
<label for="discription">Enter content description:</label><br>
<textarea name="discription" rows="10" cols="60"></textarea><br>
<label for="link">Link to content:</label><br>
<input type="text" id="lcontent" name="lcontent" value="" size="64"><br>
<label for="link">Select Image:</label><br>
<div class="profile-picture">
<h1 class="upload-icon">
<i class="fa fa-plus fa-2x" aria-hidden="true"></i>
</h1>
<input
class="file-uploader"
type="file"
onchange="upload()"
accept="image/*"
name ="imageurl"
/>
</div><br><br>
<input type="submit" name="submitcontent" value="Send Content to Channel">
</form>
The javascript involved which displays a box, which then changes to a preview of the image selected
function upload() {
const fileUploadInput = document.querySelector('.file-uploader');
if (!fileUploadInput.value) {
return;
}
const image = fileUploadInput.files[0];
if (!image.type.includes('image')) {
return alert('Sorry Only images are allowed!');
}
if (image.size > 10_000_000) {
return alert('Maximum upload size is 10MB!');
}
const fileReader = new FileReader();
fileReader.readAsDataURL(image);
fileReader.onload = (fileReaderEvent) => {
const profilePicture = document.querySelector('.profile-picture');
profilePicture.style.backgroundImage = `url(${fileReaderEvent.target.result})`;
}
}
Everything works perfect and the image displays, now to the php from the post request, what I am trying to get is the url of the image to be posted, in my /inc/sendtochan.php I am reading the data from the post request with
$imageurl = trim($_POST['imageurl']);
But when I echo this, it basically is just returning the image name, what I want the post form to actually post is the image url. Any help would be appricated.
Thank you
I can get the image url to display straight away when its selected by adding this to the javascript
return alert(`url(${fileReaderEvent.target.result})`);
So I just need to actually have that url sent with the post request, now the image name
2
Answers
Since you are using a
<form>
already, you can easily add a hidden field to the POST request:and write into it with your JavaScript function
then you can access it in PHP with
The content of the file being uploaded in the POST request is not in the
$_POST
array, it is in the$_FILES
array. w3schools.com has a good tutorial on this: PHP File Upload.The
upload()
function that you created is just fine. Then, when you click the submit button the form should just do an ordinary POST request (MIME typemultipart/form-data
) without you having to do anything else. And then you can find the file in the$_FILES
array using PHP.