I have a problem with refreshing upload file form. First time when I clik Upload File it uploads file on server (folder uploads/), and path name uploads in mysql base (table 'files'). When I refresh that page it duplicates same path name in mysql base, it does not duplicate file in uploads/. I found similar solutions but not my case, where I need to stay on the same page, and list all uploaded files. Here is the form code :
<?php
if(isset($_POST['upload'])){
$targetfolder = "uploads/";
$target_file = $targetfolder . basename( $_FILES['file']['name']) ;
$ok=1;
$file_name = $_FILES['file']['name'];
$file_type=$_FILES['file']['type'];
if ($file_type=="application/pdf" || $file_type=="image/gif" || $file_type=="image/jpeg" || $file_type== "application/msword" || $file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) {
if ($ok == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$sql = "INSERT INTO files (path, profesor, struka) VALUES ('" .$file_name. "', '". $_SESSION['username']. "','')";
if (mysqli_query($link, $sql)){
}else {echo "ERROR connecting database $sql".mysqli_error($link);
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}}
else {
echo "Sorry only PDF, DOCX, JPEG, GIF.<br>";
}}
?>
<div class = "upload">
<form method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Select file for upload:</br>
<input type="file" name="file" >
<input type="submit" id = "button_upload" value="Upload File" name="upload">
</form>
</div>
first, i don't see a place in your code, where you actually show the list of uploaded files.
second - if you refresh your page, the form is submited one more time, so another insert is done with the same data. you don't see the duplicate file, because it is just overwritten.
so, after you successfully inserted and uploaded, you should do a redirect to the same page, for example with header('Location: yourscript.php'). in this case POST will not be set.
Related
I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference
I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/
I want to restrict some file types from my html forms that are not necessary in it.
I want the code for my form submission panel.
Here is my code
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="submit" name="upload" value="Upload"/>
</form>
In HTML5 you can use "accept" attribute in the input[type=file] tag. For example:
<form action="" method="POST" " enctype="multipart/form-data">
<input type="file" name="files" accept="image/jpeg,image/png,image/gif/>
<input type="submit" name="upload" value="Upload" placeholder="Only .jpg/.jpeg files support."/>
</form>
From http://www.w3schools.com/php/php_file_upload.asp
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Complete Upload Example
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div id="upload_box" style="width : 200px; height : 200px; position : fixed; top : 300px; left : 400px; display : none;">
Select File :- Only jpg and jpeg supported !
<input type="file" id="fl" name="files" accept="image/jpg, image/jpeg" />
</div>
<button id="show_dialog"> Select File </button>
<input type="submit">
</form>
<script type="text/javascript">
$(document).on('click', '#show_dialog', function(){
$('#upload_box').css({'display' : 'block'}); // show box when click on
});
$(document).on('change', '#fl', function(){
$('#upload_box').css({'display' : 'none'}); // hide box when file selected
});
:) Thanks
To restrict to jpg and jpeg by MIME Type
if (is_uploaded_file($_FILES['files']['tmp_name'])
AND $_FILES['files']['error'] ==UPLOAD_ERR_OK) {
if (strtolower($_FILES['files']['type']) != 'image/jpeg'){
//not jpg code
}
Additional Check if uploaded file is not a jpg but has jpg extension and or MIME Type.
Requires GD Image Processing Extension
This is the most rigorous test. The file is completely analyzed. $image can also be converted to other image types, resized, text annotations added, and a lot more. See: http://php.net/manual/en/ref.image.php
$image = #imagecreatefromjpeg($_FILES['files']['tmp_name']);
if ($image == false){
//not jpg code
}
Or if not going to resize etc..
You can restrict by MIME Type, dimensions, attributes
Requires GD Image Processing Extension
list($width, $height, $type, $attr) = getimagesize($_FILES['files']['tmp_name']);
I have a website for school where every teacher is going to have a page. Each teacher's page will have a spot for them to upload a PDF. I want this to then show in a viewer on the page so students see the Viewer when they access it.
How would I code into the website allowing the user to upload a PDF and not have it replaced until somebody else uploads a PDF?
so far I have the code to upload a document.
<form method="POST" enctype="multipart/form-data" action="fup.cgi">
File to upload: <input type="file" name="upfile"><br/>
Notes about the file: <input type="text" name="note"><br/>
<br/>
<input type="submit" value="Press"> to upload the file!
</form>
How can I get it to go into a viewer below? and that it saves until replaced.
1 - First thing you are not able to upload file to server but your form action is claiming to use CGI,
2 - Second i cant really get what you want but the following code can upload files to server its in PHP and otherthing are you using SQL or what Database are you using it seems you also need database
<?php
set_time_limit(0);
if(!is_dir("uploads")){
$uploadDir = mkdir("uploads");
}
$allowedExts = array("pdf", "docx", "doc");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 200000000000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("/uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "/uploads/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Do you want to display pdf thumb, icon, or read the pdf
Can someone please provide me with some links (or source code) for me to research about how to upload images to a website (by the community) and for these images to be viewed online by the community.
I have searched via google, but have had no luck.
Thank you.
EDIT
Sorry, I have actually seen many examples to upload files. I am wanting (if possible) to be able to upload images, and then have them arranged in some kind of gallery so that the community can see/view them.
I am after a range of different technologies that are available on the WWW if possible.
Copy the below codes and save it as upload.php or anything.php (note it should be saved as php extension and should be run on apache server or any server supporting php).
<?php
if(isset($_REQUEST['submit']))
{
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 200000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"uploads/$filename");
echo "Upload Successful . <a href='uploads/$filename'>Click here</a> to view the uploaded image";
}
}
else
{
echo "invalid file.";
}
}
else
{
?>
<form method="post" enctype="multipart/form-data">
File name:<input type="file" name="imgfile"><br>
<input type="submit" name="submit" value="upload">
</form>
<?php
}
?>
And you should create two folders("uploads" and "tmp") in the parent directory (Where the script executes).
Now your upload script is ready. It's simply an upload script with which you can upload one image at a time.
Here's a good, basic start using PHP: http://www.w3schools.com/php/php_file_upload.asp
In order to get a list of files in a directory (assumes the file path is known ahead of time) you can do something like this:
$filePath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'uploads';
$files = scandir($filePath);
If you wanted to filter this down to look for image files you could use something like this:
$filePath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'uploads';
$files = scandir($filePath);
$imageFiles = array_values(preg_grep('/^.*?\.((gif)|(png)|(jpe?g))$/', $files));
And for a good guide on uploading the files you can check out http://www.exchangecore.com/blog/how-upload-files-html-php/