I am currently develop a student database system for my faculty. I am using the PHP together with MySQL. I am thinking to create an option for student to upload their profile photo but I could not find any proper instruction or tutorial of doing that.
Here's the code processing the file uploading:
<?php
/* Script name: uploadFile.php
* Description: Uploads a file via HTTP with a POST form.
*/
if(!isset($_POST[‘Upload’]))
{
include(“form_upload.inc”);
}
else
{
if($_FILES[‘pix’][‘tmp_name’] == “none”)
{
echo “<p style=’font-weight: bold’>
File did not successfully upload. Check the
file size. File must be less than 500K.</p>”;
include(“form_upload.inc”);
exit();
}
if(!ereg(“image”,$_FILES[‘pix’][‘type’]))
{
echo “<p style=’font-weight: bold’>
File is not a picture. Please try another
file.</p>”;
include(“form_upload.inc”);
exit();
}
else
{
$destination=’c:\data’.”\\”.$_FILES[‘pix’][‘name’];
$temp_file = $_FILES[‘pix’][‘tmp_name’];
move_uploaded_file($temp_file,$destination);
echo “<p style=’font-weight: bold’>
The file has successfully uploaded:
{$_FILES[‘pix’][‘name’]}
({$_FILES[‘pix’][‘size’]})</p>”;
}
}
?>
Code for the file upload form:
<!-- Program Name: form_upload.inc
Description: Displays a form to upload a file -->
<html>
<head><title>File Upload</title></head>
<body>
<ol><li>Enter the file name of the product picture you
want to upload or use the browse button
to navigate to the picture file.</li>
<li>When the path to the picture file shows in the
text field, click the Upload Picture
button.</li>
</ol>
<div align=”center”><hr />
<form enctype=”multipart/form-data”
action=”uploadFile.php” method=”POST”>
<input type=”hidden” name=”MAX_FILE_SIZE”
value=”500000” />
<input type=”file” name=”pix” size=”60” />
<p><input type=”submit” name=”Upload”
value=”Upload Picture” />
</form>
</div></body></html>
I got the same outcome which I cant find the file that being uploaded and it is not being uploaded to the location as it should be.
You should change the destination:
$destination=’c:\data’.”\”.$_FILES[‘pix’][‘name’];
Or, if this is not working, try to move the uploaded file somewhere near the script path, like:
$destination= dirname(__FILE__).DIRECTORY_SEPARATOR.$_FILES[‘pix’][‘name’];
If the second one works then is means, you have given a wrong directory for the upload.
I think you should first change your image path.
and than your datatype set to image in mysql manually,
it will be done.
Do you get any error messsage? Do the PHP user have write permissions to the upload directory?
Also, here's two advices possibly not related to your question:
Don't use eregi in any new code. It is deprecated, which means it will be removed in a future version of PHP. Instead, use the preg_ functions, or just strpos in this case.
Why would $_FILES[‘pix’][‘tmp_name’] ever be the string "none"?
Related
I have form which includes a file upload.After the form is submitted the selected filename is saved in the database.And i have a edit form of saved data.In that form in the file upload button,at the position where shows "no file chosen" i need to echo the saved file form the database.
<div class="col-md-3">
<div class="form-group">
<i class="fa fa-fw fa-cloud-upload"></i>
<label for="">File upload</label>
<?php echo $announcements_details['file'] ; ?>
<input type="file" id="captionfile" name="captionfile"></div>\
</div>
I need echo the $announcements_details['file'] in the no file choose chosen part. Can anyone help me?
It is impossible to do this, due to security reasons. you would be able to select and upload any file from the client to your website.
However, you can display a message below it saying a file has been uploaded. Or you could override the input style using css and display the text that way.
Yes, as Jerodev said it is not possible to takeout the same file in place of the choose file button. But there is a work around for this.
If the uploaded file is an image file, then you could pull up the filename from the database, and display a small thumbnail for the image below the choose upload button.
And if it is any other file, (pdf/txt..etc.), then you could display a link to the file below the choose upload button, so that the users can download the file and see what they have uploaded.
Hope this helps.
Thanks.
I have a form with text inputs and file inputs; the text fields are being validated. Is there a way to have the form remember which files the user has already selected if they hit submit but need to go back because one of the text fields didn't validate?
You can't "pre-fill" the contents of a file upload field for security reasons. Also, that would mean the file would get re-uploaded every time the form is submitted, which would not be good.
Instead, do this:
Create a file upload field with name file_upload.
On the server-side, process the upload in any case, even if the rest of the form validation fails.
If the form validation failed, but the file was uploaded, insert a hidden input into the form with name file containing the name of the just uploaded file.
Display a user-visible indication that the file is okay. If it's an image, display a thumbnail version of it. If it's any other file, display its filename and/or icon.
If the user chooses to upload a different file in the file_upload field, process the upload and store the new value in file.
Pseudocode:
<?php
$file = null;
if (!empty($_POST['file'])) {
$file = $_POST['file'];
}
if (!empty($_FILES['file_upload'])) {
// process upload, save file somewhere
$file = $nameOfSavedFile;
}
// validate form
?>
<input type="file" name="file_upload" />
<input type="hidden" name="file" value="<?php echo $file; ?>" />
<?php
if (!empty($file)) {
echo "File: $file";
}
?>
Important note
This mechanism can allow any user to claim other user's files as their own, by including a file name that they guessed exists on your server. You will want to ensure that uploaded files are clearly associated with a specific user to avoid this issue.
files input fields are read-only you can't set an initial value for them
You can upload the Files anyway and display the filenames instead of the file select box. To remember the fields, you can use a $_SESSION variable.
I have an assignment for school, and I'm not sure how the teacher wants us to accomplish a task.
We need to get an uploaded file as a temp file only (index.php)
Output size of file (upload.php)
User can confirm save of file or not (upload.php)
So, I have the majority down, but my problem lies with creating the temp file into a permanent file.
index.php
<html>
<form action="http://mysite.org/~me/upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br />
<input type="submit" value="Now upload it!">
</form>
</html>
upload.php
<?php
if (($_FILES["file"]["type"] == "application/vnd.ms-excel"))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
}
}
?>
<form action="" method="POST">
<input type="submit" value"YES please save">
<form>
<?php
if (isset($_POST['submit']))
{
//Code for saving file
echo 'File saved!';
}
?>
Is it possible to go about it this way? My last echo statement does not work, so I'm doubtful the file save would be as well.
Hopefully the following comments can help you with the part you are stuck on.
In case you hadn't realized it already, any files uploaded with PHP are deleted once the PHP request that handled the uploaded file terminates. This means, if you don't do anything with the temp file from the upload, it will be deleted when the PHP script terminates.
One function of interest to you will be move_uploaded_file() which will move the temporary file from the upload to a permanent location of your choice.
Since the file will be uploaded and then you have to display the size and ask the user to confirm the upload, you will have to move the temp file to a permanent temporary location where it is kept when the user hasn't confirmed they want to keep the upload.
I'm not sure if you have been introduced to sessions yet, but if not, you will probably need some hidden form element that will keep track of what file they uploaded, otherwise you can keep this info in the session.
Then when the person submits the form saying they want to keep the file, you can move it again to a permanent location, or if they say no, then delete the file. The problem is, if they never say yes or no, then the file remains on the system.
Hope that helps.
Yep, this should work. Your if statements will catch the form submission and then echo your string there. A few little errors in your markup:
<input type="submit" value"YES please save">
Should be
<input type="submit" value="YES please save" name="submit">
Your final if statement in PHP is looking for a post variable named 'submit' but your <input type="submit"> tag has no name.
The file is saved to a temporary location when the upload completes. You can access this temporary file with $_FILES['file]['tmp_name'] BUT the file will be removed at the end of the request if you do nothing about it. This means that when the user clicks YES please save button, the file will not be available any more.
This means that you have to save the file to a disk in the first place, when you first call the upload.php file. There is no way to keep the file "in memory" while the user decides whether or not to save the file permanently.
I have had problems with a simple php script in which I can upload a file to a certain folder. I have tried multiple ways in doing this and I still have not had success.
Any errors in my code or advice on how to correct the issue will be taken gracefully.
Main Php Code:
<p>Browse For a File on your computer to upload it!</p>
<form enctype="multipart/form-data" action="upload_photos.php" method="POST">
Choose Photo:
<input name="userfile" type="file" /><br />
<input type="submit" value="Upload Photo" />
<?PHP
if ($userfile_size>250000)
{$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$file_upload="false";}
else{
if (!($userfile_type<>"image/jpeg" OR $userfile_type<>"image/tiff" OR $userfile_type<>"image/png"))
{$msg=$msg."Your uploaded file must be of JPG, PNG, or tiff. Other file types are not allowed<BR>";
$file_upload="false";}
}
?>
</form>
</label>
</form>
Php code that is called upon on click (upload_photos.php)
<?php
$target_path="uploads/";
chmod("uploads/", 0755);
$target_path=$target_path . basename( $_FILES['uploadedfile']['name']);
$test=move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
if($test) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
var_dump($test);
}
?>
I do not understand why my end results [upon clicking "Upload Files" Button] include only the following results:
"There was an error uploading the file, please try again!bool(false)"
One more thing: I have also tried using the full computer folder path for $target_path and chmod.
Does anybody see what I am doing wrong?
You have <input name="userfile" but then use $_FILES['uploadedfile'] in your script - use one or the other.
Other than that, make sure the chmod worked and the folder is writable.
bool(false) is the output of var_dump($test);, indicating that move_uploaded_file is returning false.
As a basic debugging step, you should try var_dump($_FILES) to make sure you're accessing the right element of that array (I can tell from your code that you aren't, the index will be the name attribute of your <input type="file"/> element).
You have at least one other serious flaw in your logic... The PHP code in your upload form doesn't make any sense. That block of PHP code will execute server-side before the user has ever uploaded a file. It can't possibly work. The two variables you're checking, $userfile_size and $userfile_type, are not defined anywhere.
In my case, I forgot to create a folder where I want to upload. So check once the specified upload path is available or not.
I am practicing with PHP and AJAX but I have some problems!
I'm trying to get the filename, type, size from a jQuery alert after select an image to upload, but I keep getting an empty string.
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="my_file" />
<input type="submit" name="submit" value="Submit" />
</form>
This form includes a JS file that has an ajax script that asks to a php page the filename of the posted file, but it doesn't work. Do I need to upload the file before I try to get this data?
The JS file:
$("input").change (function () {
$.post("preview_uploader.php", { action:"get_size" }, function (data) {
alert (data);
});
});
The PHP file preview_uploader.php:
<?php
if ($_POST["action"] == "get_test") print "text string test works!";
if ($_POST["action"] == "get_name") print $_FILES["my_file"]["name"];
if ($_POST["action"] == "get_size") print $_FILES["my_file"]["size"];
if ($_POST["action"] == "get_type") print $_FILES["my_file"]["type"];
?>
It works if i make a test with action:"get_test" with php page but it doesn't work with $_FILES["my_file"]["name"] or $_FILES["my_file"]["type"] etc...
Can someone help me find where I am wrong?
Thanks!
Your JS script is sending a separate request to the server and so your PHP is unaware of the file, and $_FILES["my_file"] is not a valid index.
You do not need to go to the server to get the file name, simply use this to get the file name:
$("input[type=file]").val();
I believe it brings back the path as well, so you will need to strip the path off to get the filename.
If you are trying to get all the additional details (filesize, etc) you will either need to upload the file first (which defeats what you are trying to do) or use a Flash + JavaScript combination like these solutions:
Uploadify for jQuery
SWF Upload
You can actually get the size with jQuery. See the answer to this questions:
How to check file input size with jQuery?
You can use the method given to get the name, size, and type. General belief is that its not possible. You can't always believe everything you hear...