PHP Form Upload Error When Input File Field Is Empty - php

Here is the code for a form that will recreate the issue:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
print_r($_FILES['fileToUpload']);
if (!file_exists($_FILES['fileToUpload']['tmp_name']) || !is_uploaded_file($_FILES['fileToUpload']['tmp_name']))
$primaryImage = file_get_contents($_FILES['fileToUpload']['tmp_name']);
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image">
</form>
When clicking "Upload Image" with no file uploaded, PHP 8 will create this error (I've included the print_r($_FILES['fileToUpload']) output for reference).
Array ( [name] => [full_path] => [type] => [tmp_name] => [error] => 4 [size] => 0 )
Fatal error: Uncaught ValueError: Path cannot be empty in C:\xampp\htdocs\cole\cms\phpExample.php:6 Stack trace: #0 C:\xampp\htdocs\cole\cms\phpExample.php(6): file_get_contents('') #1 {main} thrown in C:\xampp\htdocs\cole\cms\phpExample.php on line 6
I have tried to wrap the issue in a try...catch... block, various checks like the if statement in the above to check for the emptiness of the path. Note, if you upload a file in the form and then click submit, no error will occur.
How can I prevent an error from being thrown while checking the presence of the $_FILE['my_file'] information in PHP 8?

You can check with:
if($_FILES['fileToUpload']['size'] > 0){
// code here
}
which will ensure that you have submitted a file, and its size is not 0

Related

How to set php variable as value of input in html form for those input with type "file"

we can set PHP variable as the value of input in HTML form like this
<input type="number" name="price" value="<?php echo $editprice;?>" >
but this doesn't work for input with type file.
I try it this way
<?php
$sqlch15="SELECT image1 FROM pc where id=$idtoe";
$resultch15= mysqli_query($db, $sqlch15);
while ($row = mysqli_fetch_array($resultch15))
{
$editimg1 = "<img src='images/" .$row['image1']."'>";
}
?>
<input type="file" name="image1" value = "<?php echo $editimg1;?>">
but it doesn't work what is my mistake help me.
The value property contains the complete path of the file.
The value property of the input:file element is read-only, because of security reasons.
if you press that button you upload a picture into the /tmp folder of the server (or another folder designed for that)
You will create a Array variable called $_FILES['image']
[_FILES] => Array
(
[image1] => Array
(
[name] => example.png
[type] => image/png
[tmp_name] => /tmp/phpq0JHjV // that is the upload folder
[error] => 0
[size] => 10847
)
)
So the only thing that would make a little sense is to fill in the name of the file
<input type="file" name="image1" value="<?=$_FILES['image']['name'];?>">
But as I said it makes no much sense because the info about the path to this file on the client is missing.

Cloudinary upload php failed, how to fix it?

I try using cloudinary for upload my image and video for my personal blog but it's a fail. I watch this video tutorial https://www.youtube.com/watch?v=oZCQLjfq97o. the error says :
Notice: Undefined index: file in >C:\xampp7\htdocs\lovantoBlog\cloudinary\index.php on line 8
Notice: Undefined index: file in >C:\xampp7\htdocs\lovantoBlog\cloudinary\index.php on line 9
Fatal error: Uncaught Cloudinary\Error: Missing required parameter - file in C:\xampp7\htdocs\lovantoBlog\cloudinary\vendor\cloudinary\cloudinary_php\src\Uploader.php:558 Stack trace: #0 C:\xampp7\htdocs\lovantoBlog\cloudinary\vendor\cloudinary\cloudinary_php\src\Uploader.php(407): Cloudinary\Uploader::call_api('upload', Array, Array, NULL) #1 C:\xampp7\htdocs\lovantoBlog\cloudinary\vendor\cloudinary\cloudinary_php\src\Uploader.php(100): Cloudinary\Uploader::call_cacheable_api('upload', Array, Array, NULL) #2 C:\xampp7\htdocs\lovantoBlog\cloudinary\index.php(11): Cloudinary\Uploader::upload(NULL, Array) #3 {main} thrown in C:\xampp7\htdocs\lovantoBlog\cloudinary\vendor\cloudinary\cloudinary_php\src\Uploader.php on line 558
This is my code for upload :
require 'vendor/autoload.php';
require 'config.php';
if (isset($_POST['Simpan'])) {
$nama = $_POST['nama'];
$slug = $_POST['slug'];
$gambar = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
\Cloudinary\Uploader::upload($file_tmp, array('public_id' => $slug));
}
and this is the code for form :
<form method="POST">
<input type="text" name="nama">
<input type="text" name="slug">
<?php echo cl_image_upload_tag('image_id');?>
<input type="submit" name="Simpan" value="Simpan">
</form>
The cl_image_upload_tag is used to perform direct uploading from the browser to Cloudinary. When you submit the form you there is no file parameter sent to your backend and thus the Cloudinary::Uploader::upload call fails with the error Missing required parameter - file.
If you would like to upload the file from your backend then you need to replace the cl_image_upload_tag with a regular file input field element. Once a file is selected and the form submitted your backend can use the same code to upload the file to Cloudinary.
On the other hand, if would like to use cl_image_upload_tag then please see the direct uploading section of the Cloudinary documentation that describes setting this up.
https://cloudinary.com/documentation/php_image_and_video_upload#direct_upload_file_tag

How to get the httppost filename on the php server

I used FileEntity httppost to post a file to a php apache server,but I do not want to change the name of the file.
How can I get the name of the file from the server using php? I have already get the file:
$filename='test.zip';//自定义的名字
file_get_contents('php://input');
file_put_contents($filename,$data);
HTML (test.html):
<!-- Make sure you have enctype and a name on your file input -->
<form method="post" action="test.php" enctype="multipart/form-data">
<input type="file" name="test" />
<button>Submit</button>
</form>
PHP (test.php):
// Since we've set our file input to name 'test' and
// we've posted form-data, we can use $_FILES
print_r( $_FILES['test'] );
Just use $_FILES.
Array
(
[name] => test.jpg
[type] => image/jpeg
[tmp_name] => /tmp/pasd41l3FmFr
[error] => 0
[size] => 15476
)
glob — Find pathnames matching a pattern
foreach (glob("*.*") as $filename) {
print $filename. "\n";
}

Why does image upload fail php's is_uploaded_file check?

I have a html form that allows image uploads, but the image uploaded now fails the "is_uploaded_file" check for some reason.
So why does the upload fail the is_uploaded_file check?
HTML:
<form enctype="multipart/form-data" id="RecipeAddForm" method="post"
action="/recipes/add" accept-charset="utf-8">
<!--- Omitted Markup -->
<input type="file" name="data[Recipe][image]" value="" id="RecipeImage" />
<!--- Omitted Markup -->
</form>
PHP:
// returns false
echo is_uploaded_file($file['tmp_name'])?'true':'false';
I did a dump on the $file or $_FILES array:
Array
(
[name] => add or remove.jpg
[type] => image/jpeg
[tmp_name] => E:\\xampp\\tmp\\phpB9CB.tmp
[error] => 0
[size] => 71869
)
File size is not too large, and the error was 0. So why does it fail the is_uploaded_file check?
Might be a problem with windows, since it's case sensitive and will not match if the path is different. Try using realpath($file['tmp_name'])
try with
if (is_uploaded_file($_FILES['data[Recipe][image]']['tmp_name']))
remember $_FILES is reserve PHP superglobal variable ..so always write in capital
u can retrieve the correct path of file using
$filename = basename($_FILES['userfile']['name']);
NOTE: why u using array in the name attribute ( name="data[Recipe][image]" ) ?
if there is no specific reason then alwayz make simple code
<input type="file" name="RecipeImage" value="" id="RecipeImage" />
and check simply
if (is_uploaded_file($_FILES['RecipeImage']['tmp_name']))
Remember KISS
After you have used the uploaded image (move_uploaded_file) the function is_uploaded_file always returns false.

PHP file uploading headache

I am having a tough time trying to upload files through PHP.
My form:
<form action="blah.php" enctype="multipart/form-data" method="post">
<p> Upload file: <input type="file" name="xmlfile"/>
<input type="submit" name="upload_submit" value="Upload" /> </p>
</form>
Checklist:
No 'smart' quotes in sight. Fine.
Proper enctype. Fine.
name attrib in input tag. Fine.
My /tmp directory has the following permissions: drwxrwxrwt. Fine.
post_max_size = 50M, upload_max_filesize = 50M, file_uploads = On. Fine.
print_r($_FILES) gives Array(). Useless. Tried on images, xml files, etc. Nothing works.
What I don't understand even further is that there are pages on which file uploading works on the same server. The only thing different from what I can gather is that the page I am working on has a few other forms which aren't of enctype="multipart/form-data". Should this matter?
PHP code as requested:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['upload_submit'])){
print_r($_FILES);
exit();
...
}
}
Gives an empty array regardless of print_r's position; I also tried it right after the if($_SERVER['REQUEST_METHOD'] == 'POST'){
Are you sure that you are submitting the right form or you are dealing with the submitted data in the right place/script? Provide some of the PHP code please.
your from, this php script (as blah.php)
edit for debugging, dump $_POST if is false
error_reporting(E_STRICT);
ini_set('display_errors', 'on');
if(array_key_exists('xmlfile', $_FILES)) {
echo 'file ' , $_FILES['xmlfile']['name'] , ' recieved';
echo '<pre>'
, print_r($_POST, true)
, print_r($_FILES, true)
, '</pre>';
} else {
echo '<pre>'
, print_r($_POST, true)
, '</pre>';
}
(possible) output:
file rapid-gui-development-with-qtruby_p1_4.mobi recieved
Array
(
[upload_submit] => Upload
)
Array
(
[xmlfile] => Array
(
[name] => rapid-gui-development-with-qtruby_p1_4.mobi
[type] => application/octet-stream
[tmp_name] => /private/tmp/phpEyV3vy
[error] => 0
[size] => 556846
)
)
You mention having other forms on the page... are those properly closed? For instance, if you have:
<form method="post">
blah blah blah
<input type="submit" />
<!-- oops forgot to </form> here -->
<form method="post" enctype="multipart/form-data">
...
<input type="submit" />
</form>
Then the FIRST <form> tag could be taking precendence and submitting without the enctype set.
If you're on Firefox, I'd suggest using Firebug/HTTPFox/LiveHTTPHeaders (all available in FF's add-ons library) to see what's being sent over the wire, and running your page through a validator to make sure there's no goofy HTML bugs causing this.

Categories