I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link
Related
I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!
I have two php document. form.php and upload.php. Form.php displays my upload file button and it is visible to the enduser. upload.php carries out the action and it is not visible to the user but has the include("form.php"); statement so anything i echo on this page goes back to my form.php page to be displayed.
first i want to know how i check my upload code with an if statement to see if the file was correctly uploaded to the server. my upload code is
code
move_uploaded_file($_FILES['file']['tmp_name'],"./medetrax_backup/{$_FILES['file']['name']}");.
secondly if the upload was successful i want the if statement to echo "the file was uploaded" or else echo "the file was not uploaded."
finally since the echoes are echoed back to my form.php i want to know how to echo the message in a specific div in my form.php. Rather than it echoing at the bottom of the page.
move_uploaded_file returns true on success. In upload.php;
<?php
....
$res = move_uploaded_file($_FILES['file']['tmp_name'],"./medetrax_backup/{$_FILES['file']['name']}");
$_SESSION["res"]=true;
if ($res) {
header("Location:form.php?res=success");
} else {
header("Location:form.php?res=error");
}
And in form.php;
<?php
.....
$res = $_GET["res"];
......
?>
<div>
<?php if ($res == "success" && !empty($_SESSION["res"])) {
echo "File uploaded";
} else {
echo "Error occured";
}
unset($_SESSION["res"]);
?>
</div>
.....
In upload.php, use this:
<?php
....
try
{
$res = move_uploaded_file($_FILES['file']['tmp_name'],"./medetrax_backup/{$_FILES['file']['name']}");
}
catch(Exception $e)
{
echo "An exception occurred while uploading the file. Process will quit now";
die;
}
if (isset($res))
{
header("Location:form.php?res=success");
}
else
{
header("Location:form.php?res=error");
}
?>
And in form.php, check using this:
<?php
.....
$res = isset($_GET["res"])?$_GET["res"]:false;
......
?>
<div>
<?php if ($res)
{
if($res=="success")
echo "File uploaded";
else
echo "Failed to upload file";
}
else
{
//draw your upload button here, in same file.
}
?>
</div>
.....
In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?
You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}
if (empty($_FILES['cover_image']['name']))
simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty
check after the form is posted the following
$_FILES["cover_image"]["size"]==0
if (!$_FILES['image']['size'][0] == 0){ //}
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }
$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}
This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}
UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}
When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.
How can I do a php and xhtml form that allows users to upload images and on submitting all the data is send to my e-mail?
By searching for tutorials on Google and learing it yourself. This is too broad a question to post on this site. Try it out yourself, and if you can come up with an specific question you don't have the answer for, ask it here. Here's something to get you started:
http://www.reconn.us/file_uploading.html
http://www.tizag.com/phpT/fileupload.php
http://www.litfuel.net/tutorials/mail2.htm
The main PHP site itself also includes some good information on the recommended practices and pitfalls, as well as some sample code - see the 'Handling file uploads' section.
Try this
<?
//print_r($_POST);
if($_POST["action"] == "Upload Image")
{
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['image_file']))
$error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['image_file']['name']);
//echo $imagename;
if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";
if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}
}
?>
<form method="POST" enctype="multipart/form-data" name="image_upload_form" action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>
<?
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>\n";
}
}
?>