Having issues with PHP File Upload - php

I am trying to upload a file to my site but for some odd reason its not working. The exists=true is triggering so this means it should be working right? Its giving me the $error=true;. Below is my code:
HTML:
<input size="30" enctype="multipart/form-data" name="profile_icon" id="register-profile_icon" class="elgg-input-file" type="file">
PHP:
$profile_icon = $_FILES["profile_icon"];
if($profile_icon){
$exists=true;
}
$error = false;
if(empty($profile_icon["name"])){
register_error(elgg_echo("profile_manager:register_pre_check:missing", array("profile_icon")));
$error = true;
}

Use $_FILES["profile_icon"]["tmp_path"] for file path.
$_FILES["profile_icon"] This will contains arrays of values like name, tmp_path, type, size etc.
On another note you need to add enctype attribute to your <form>.
And there is function available for moving upload function move_uploaded_file();

Related

numerous errors handling file upload in php

I'm using this code to process uploaded files:
mkdir("files/" . $id, 0700);
$path = "files/" . $id;
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
foreach($_FILES['attachments']['name'] as $f => $name)
{
if($_FILES['attachments']['error'][$f] == 4)
{
continue;
}
if($_FILES['attachments']['error'][$f] == 0)
{
if(move_uploaded_file($_FILES["attachments"]["tmp_name"][$f], $path.$name))
{
$count++;
}
}
}
}
$id is a random number taken from the database. Besides, I'm using this markup:
<input type="file" id="attachments" name="attachments[]" multiple="multiple" accept="*">
While the exact same code had worked brilliantly before, it now throws numbers of errors I can't really deduce:
1: mkdir(): File exists in ... on line ... (<-- now, it doesn't for granted!)
2: Undefined index: attachments in ... on line ... (well, it's defined also using form method post!)
3: Invalid argument supplied for foreach() in ... on line ... (which is quite clear as the above stated errors do prevent the foreach from doing its job correctly)
Yes, I made sure that I'm actually using POST. I also tried changing the file input's name from attachments to any other, however, scenario remains the same.
Adding enctype="multipart/form-data" has done it.
1] Check for the folder rights 0777. Weather you are able to create directory or not
2] After posting form. Make sure your form has enctype = multipart/form-data tag.
In you file please check with
echo "<pre>";
print_r($_FILES);
exit;
If you are getting any data or not? If getting data then move ahead.
First check if your $id really contain something, secondly your form should have attribute of enctype = multipart/form-data for using input type file.
<form action="test.php" method="post" enctype="multipart/form-data">
Now in your case you will get the array of files you before your perform any work, see print_r of attachments:
echo "<pre>";
print_r($_FILES);
exit;

File upload php, get only file name

Is it possible to get the filename of a file, without a complete upload
Meaning after the user chose a file, dont upload that file, just get the filename and save to database?
yes it is possible you can use the code as given below
$filename=$_FILES['nameofyourfileinput']['name'];
echo $filename;
you can echo the $filename;
OR You can use jquery to get this value like
$('#inputid').change(function(){
var value =$(this).val();
alert(value);
})
ya it is possible.You can also do this before uploading the file basename() is enough for extracting name.
$next=$pfet['f_name']; //fetched file from database
$next1 = basename($next);
The accepted answer doesn't prevent the file upload, it simply provides a way to get the file name independent of the file contents.
Preventing file upload, is best looked at the other way: what enables uploading a file. The answer to that is the enctype attribute on the form tag (multipart/form-data).
HTML:
<form action="upload.php" method="post" enctype="application/x-www-form-urlencoded">
Select:
<input name="upload[]" type="file" multiple="multiple" />
<input type="submit" value="Update" name="submit">
</form>
PHP:
$total = count($_POST['upload']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
$fileName = $_POST['upload'][$i];
}

php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array

Ok. I give up on this. When uploading multiple files to the server using php, what is a fail safe method to return the count of files the user has actually uploaded?
Whatever I have done so far, returns the count of all the fields in the form, and the count of the files a user uploads. So if the total fields in the form were 3 and a user uploaded only 2 files, I still get 3 as the count of file uploaded.
One place suggested using array_filter to do this, but that's totally beyond me.
echo count($_FILES['file']['tmp_name']); //3
echo count($_FILES['file']); //3
Any fail safe method you follow and can suggest other than looping through the FILES array size to check for this?
My form is structured like any other:
<form action="process.php" method="post" enctype="multipart/form-data">
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="submit"></div>
</form>
Exactly as they told you, just simply use array_filter().
echo count(array_filter($_FILES['file']['name']));
It will return the right number
$count = 0;
foreach($_FILES as $file) {
if(isset($file["file"]["tmp_name"]) && !empty($file["file"]["tmp_name"]))
$count++;
}
Try this
$count = 0;
$fileCount=count($_FILE['file']['name'];)
$fileSize=$_FILES['file']['size'];
for($i=0;$i<$ fileCount;$i++) {
if ($fileSize[$i] > 0) {
$count++;
}
}

Not able to upload and save image in PHP

I'm trying to upload a image in PHP but the image is not getting saved in the directory on the server. However I'm able to save the path of the image in the database. Please help. Here is the piece of code. I'm not getting any error in the web page.
<?php
error_reporting(E_ALL);ini_set('display_errors', 'On');
session_start();
$logged_user_name = $_SESSION['user_name'];
$logged_user_type = $_SESSION['user_type'];
$logged_user_team_id = $_SESSION['team_id'];
$logged_user_team_name = $_SESSION['team_name'];
$uploaded_profile_image = $_POST['propic'];
//$uploaded_profile_image = $_FILES['propic']['name'];
include_once("classes/doEverything_framework.php");
function upload_image()
{
$db_connection_obj = new database_connection;
$db_connection = ($db_connection_obj -> open_database_connection());
global $logged_user_name;
global $uploaded_profile_image;
$profile_image_upload_dir = 'images/uploaded_profile_pics/';
if ($uploaded_profile_image != null || $uploaded_profile_image != "")
{
//file_put_contents($uploaded_profile_image);
move_uploaded_file($uploaded_profile_image, $profile_image_upload_dir);
//file_put_contents($uploaded_profile_image,$profile_image_upload_dir);
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image;
$sql = "UPDATE user_login_table SET user_profile_image = '$uploaded_profile_image_link' WHERE user_name = '$logged_user_name'";
mysql_query($sql, $db_connection);
}
$db_connection_obj -> close_database_connection($db_connection);
}
?>
HTML Code:
<form enctype="multipart/form-data" name="uploadprofileimage" onsubmit="" action="" method="post">
<input type="file" name="propic" id="propic" onclick="" >
<input type="submit" value="Upload" name="upload" id="submit" >
<br>
<label for="propic" id="picerrorlabel"></label>
</form>
<?php
if(isset($_POST['upload'])) //This ensures the function runs only when the submit button is clicked.
{
upload_image();
}
The correct way to access selected File is as follows
$uploaded_profile_image = $_FILES['propic']['name'];
Make sure you are uploading file within limit of configured file size in php.ini (upload_max_filesize). rest all should work.
Correction 1:-
Your are passing only directory name in move_uploaded_dir. I think you should pass complete image path. and $uploaded_profile_image should be your image tmp_name.
move_uploaded_file($_FILES['propic']['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image);
Correction 2:- You can't get image name in $_POST. so it should be
$uploaded_profile_image = $_FILES['propic']['name'];
You cannot get image or any file in $_POST['propic']; the correct way to access file or image is by using $_FILES
so you should use $uploaded_profile_image = $_FILES['propic']['name'] in move_uploaded_file function. Make sure to check upload_max_filesize limit in php.ini.
To upload a file in php use move_uploaded_file()
$path="upload/".$_FILES["file"]["name"]; // This specifies the path to save file
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
First You cant get file value in POST method so you need to user $_FILE to get file. So you need to replace line no 5 with this :
$uploaded_profile_image = $_FILES['propic'];
Another mistake in your code is while moving uploaded file where source params is expected to be temporary location of file :
move_uploaded_file($uploaded_profile_image['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image['name']);
Now in line no 27 you can get file name to store in database this way :
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image['name'];

PHP: multiple files upload without ajax

I want any php script which can demonstrate me how to upload multiple files in PHP. In my application I have given a link "Add Image" & 'Remove Image', on click of "Add Image" I am adding a new upload field on the page using javascript, using which user can upload more and more images, no limit on number of images for now. On click of delete i am removing that element.
I am just not getting the concept on how to process them in the POST request in PHP. I know in HTML if we give the name of field like myimages[] then it will create a PHP array, but how to process this.
I don't want to use AJAX/JavaScript for uploading, want to do it with traditional POST request in PHP.
If anyone have any link or code which shows such functionality, then pleas provide it will be really helpful.
Thanks!
combine this uploading multiple files & move_uploaded_file
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
$uploads_dir = '/uploads';
foreach ($_FILES["userfile"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Uploaded files are not in the POST array, they are in the FILES array.
http://www.php.net/manual/en/features.file-upload.multiple.php
The files are uploaded to a temp area with "safe" names. The array will contain the name of the file and the tmp file. You can then move them to where you want.
Name file input fields as file[] in HTML, then just run a loop from 0 do count($_FILES) in PHP...
for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++){
$tmp = $_FILES['file']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "File '$tmp' uploaded successfully";
}else{
echo "Uploading '$tmp' failed";
}
}
I've implemented something similar in the past as follows:
Have a hidden JavaScript form variable (e.g.: "numuploads") that stores the number of file inputs currently in the form. This will need to be incremented/decremented when you add/remove an input on the front end.
Name each of the inputs on the front end using a pattern such as "upload_X", where X is the next in the sequence. (Effectively the same as the counter above -1.)
On the PHP landing page, simply scan the $_FILES superglobal, looking for each "upload_X" where X is zero thru numuploads - 1.
You can then carry out the required logic for each of the uploaded files, other form elements, etc.

Categories