My teacher,he was uploading and retrieving images from folder with ID recognition. It works with database.
So, when we upload an image, it will be stored in a folder with it's name changing automatically with ID.
Example: The upload form must be on "yourwebsite.com/yourpages/3144242" so the image will be stored as "3144242" and blablabla the same for other pages with ID
This is how he upload and retrieve it
<?php
$ff = './assets/images/kegiatan/'.$_SESSION['idkeg'].'.jpg';
if( file_exists( $ff ) ) {
<img src="<?= base_url()?>assets/images/kegiatan/<?=$_SESSION['idkeg']?>.jpg" />
<?php
}
?>
Retrieve images part:
if( file_exists( $ff ) ) {
<img src="<?= base_url()?>assets/images/kegiatan/<?=$_SESSION['idkeg']?>.jpg" />
<?php
}
?>
However, I change it a bit so I don't have to use a database and $_SESSION things. With this:
<?php
$ff = './assets/images/kegiatan/'.$this->input->post('img_name').'.jpg';
?>
<form id="form" class="kart" action="<?= base_url()?>gallery/upload2" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="img_name" required="required">
</div>
<div class="form-group">
<input type="file" class="form-control" name="foto">
</div>
<div class="form-group">
<button type="submit" class="btn btn-common" value="Update"><i class="fa fa-upload fa-2x"> Upload</i></button>
</div>
</form>
It works uploading images into folder "kegiatan" (means activity) with simply write the names of images in a form. The img_name that you have input, now become the name of that image.
Now I have a little problem to retrieve that images. How?
mistake in your form I realized is asking user to enter image name and get image from folder by using that input value.
First of all, I haven't tried upload an image with codeigniter but I will answer reference to php itself.
When we get an image as input from user by form, then we use "move_uploaded_file" function in php and we send temp_file, path with file name arguments to this function to save the file user selected in the form we prepared.
move_uploaded_file(string $filename , string $target);
// $filename: I use $_FILES['getFileUpload']['tmp_name'] for this argument
// $target: I define path with file name, eg: uploads/files/new_file_25.jpg for jpg image
So, you souldn't ask user to enter file name, because you will deifne it. Or, you must use "img_name" that you asked user to enter as file name which is most probably won't satisfy your ID prediction.
I hope this will help you.
Related
i'm asking user to input the image as;
Fotoğraf <input type="file" id="foto" name="foto" accept="image/*">
<br> <br> <br>
Then i am storing that data into my database with the following;
$j=$_POST['foto'];
$sql = "INSERT INTO customer_list (ad_soyad,telefon,e_posta,cari_kart_kodu,olusturma_tarihi,guncelleme_tarihi,sifre,foto2) VALUES('$a','$b','$c','$d','$e','$f','$h','$j')";
And then i am listing the files and the image i get from the user in the function below;
$sql = "SELECT ad_soyad,id,telefon,e_posta,cari_kart_kodu,olusturma_tarihi,guncelleme_tarihi,foto2 FROM customer_list";
$tdStyle='background-color:grey;';
echo "<td style=\"$tdStyle\"> <img src = ".$row['foto2']." width=200 height=200 ></td>";
However when user uploads the image,i want it to upload the image into my C:\xampp\htdocs\ea file.
Tried this Storing images in MySQL couldn't do it properly.Appriciated for the help.
you must set the enctype in form like this to upload the file
<form action="post" enctype="multipart/form-data">
<input type="file" id="foto" name="foto" accept="image/*">
</form>
to access the uploaded file in the action page you need to do this instead of your code
$j=$_POST['foto']; // you can't access file in $_POST
Use $_FILES to get file data
$j=$_FILES["foto"]["name"]; // get the name of image
echo $j; // print the image name just to check
upload the file to your destination if you want to upload the file in C:\xampp\htdocs\ea folder. If your form file exists in this format then use below code htdocs-
ea (your image path)
yourfoldername -
-form.php (your form)
if(is_uploaded_file($_FILES["foto"]["tmp_name"])){
move_uploaded_file($_FILES["foto"]["tmp_name"], $path1="../ea/".$_FILES["foto"]["name"])or die("couldn't copy.");
}
after file upload save the data to database
$sql = "INSERT INTO customer_list (ad_soyad,telefon,e_posta,cari_kart_kodu,olusturma_tarihi,guncelleme_tarihi,sifre,foto2) VALUES('$a','$b','$c','$d','$e','$f','$h','$j')";
Maybe try this solution for file upload with php.
I am developing a Laravel application.Its have a form which have image upload field and its also not a required field. Now i want to do if anyone submitting form without uploading image then a default random image will be inserted into database from public/images/default directory. How can i do that with Laravel? I have 10 images of that directory (ex: 1b.png, 2b.png, 3b.png....)
<form method="POST" action="{{ route($base_route.'.eventEdit', ['event_id' => $event->event_code]) }}" accept-charset="UTF-8" id="general_form" novalidate="novalidate">
<input name="name" type="text" value="something" class="name">
<input name="name" type="file" value="DefaultImageName" class="image">
<button class="btn btn-default"> Submit </button>
</form>
Add this code to your controller action
$images = scandir(public_path('images/default'));
$image = $request->file('DefaultImageName', $images[mt_rand(0, count($images -1))]);
I would't advise storing images in the database. The approach I take is usually, I store in the database a name, alias and path to the file.
You can do this depending on the pattern you're using on the application, but for your situation, what I'd do is create a mutator that validates whenever you're going to insert a record, if certain field is empty, it does something (if you're using eloquent I assume).
https://laravel.com/docs/5.2/eloquent-mutators
public function setImageAttribute($value)
{
if (empty($value)) {
$this->attributes['image'] = //fetch your image and apply your logic
} else {
$this->attributes['image'] = value;
}
}
Otherwise, I'd create a formrequest that validates if a certain field is empty, I place some content in it (and this way, when it reaches the insertion code it already contains an image)
https://laravel.com/docs/5.2/validation
I have this code where I can upload images. Previously, I'm having trouble changing the path/directory of the folder. And its working fine now. I have the correct path inside my database and also the image is being saved into the correct folder.
My coding :
<table id="details" height="100">
<tr>
<td>Select Image </td>
<td> : </td>
<td><input type="file" name="image" class="ed"></td>
</tr>
</table>
if (!isset($_FILES['image']['tmp_name']))
{
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$location= $_SERVER['DOCUMENT_ROOT'] . '/ehars/photo/';
move_uploaded_file($_FILES["image"]["tmp_name"], $location . $_FILES["image"]["name"]);
$save=mysql_query("INSERT INTO photo (location,emp_id) VALUES ('$location','$emp_id')");
}
Path in my db :
Image saved in the folder :
However, when I try to view the picture inside the folder, I cannot view it. It says like in the photo below. Is there something wrong with my code? Or do I need to enable something so that I can view my photo? Thank you.
Try uploading a .jpg file instead of a .png. Or using another photo viewer program.
There is/was a problem with Photo Viewer not loading .png files
See this for a possible solution
Based on the discussion in the comments. I am sharing the code what I use to upload an image(save to a dir).I also didn't understood why you are using addslashes(). Sorry about this!
Basically what I do is -
created dir in my project folder
Created an unique name for the file to store so that conflict does not happen
This is my html form where I get the file from the User.
<form role="form" method="post" action="save_blog.php" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Image</label>
<div class="col-sm-2">
<input type="file" class="filestyle" name="image_upload" data-input="false" id="file_name"><label id="name_of_image_file"></label>
</div>
</div>
</form>
And my save_blog.php looks like this.
$temp = explode(".",$_FILES["image_upload"]["name"]);
$unique_name_of_image = date('y-m-d') . "_".$user_id ."_".rand(1,9999)."." .end($temp);
$file_location = "$target_dir".$unique_name_of_image;
if (move_uploaded_file($_FILES["image_upload"]["tmp_name"], $file_location)) {
//this prints the location of the file stored
#echo "$target_dir".$unique_name_of_image; echo "<br>";
#$insert_blogs_with_image --> this is my insert string
save_to_database($insert_blogs_with_image);
} else {
#echo "Sorry, there was an error uploading your file.";
}
Hope this will help to solve the problem. If this didn't help then use the sample tutorial shown by the W3schools
I want to show the user a image before the user uploads it to the server to make sure that this image is what the user wanted to upload.
I have tryed to do this with $_FILES['name']['tmp_name'] and put this in a tag but nothing happens.
<form action='' method='POST' enctype="multipart/form-data">
<header class='pageHeading'>Kop afbeedling toevoegen</header>
<section class='body'>
<div class='inputFrame'>
<img src="<?php if(isset($_FILES['image']['tmp_name'])){echo $_FILES['image']['name'];}?>"/>
<div class='input'>
<div class="cellFrame">
<div class="inputHeading">Afbeelding uploaden</div>
<div class="frame">
<div class="frameAlign">
<div class="displayFlie">
<input type='file' name='image'/>
</div>
<button name='upload' class='btnUpload btn'>Upload</button>
<div class="clr"></div>
</div>
</div>
</div>
</div>
<div class="clr"></div>
</div>
</form>
simple solution - grab your image data convert to base64 and output in your current view, so you don't need to copy the current tmp image into an public loction- like
$imageData = file_get_contents($_FILES['image']['tmp_name']); // path to file like /var/tmp/...
// display in view
echo sprintf('<img src="data:image/png;base64,%s" />', base64_encode($imageData));
After the image is submitted, it's already uploaded to the server in a temporary file. If you need to show the contents of the image from that temporary file, then you need to do a script that reads that file and outputs it with the right headers. Here's an example:
header('Content-Type: image/x-png');
readfile($_FILES['name']['tmp_name']);
exit();
any files uploaded to the server if not moved will be deleted automatically.
but do not worry. before uploading, you can display it using javascript or jQuery.
<form>
<input type="file" accept="image/*" name="" onchange="previewImage()">
<img id="preview">
</form>
<script>
function previewImage(){
var previewBox = document.getElementById("preview");
previewBox.src = URL.createObjectURL(event.target.files[0]);
}
</script>
Have you tried reading the file directly from the /tmp folder? Of course this can only happen after the upload, not before. So you have to do this before moving the file to its destinated folder, but right after the upload.
readfile($_FILES["name"]["tmp_name"]);
You have two ways of doing this.
The first is using a javascript code to show the preview before uploading to server, you can check this answer: Image Upload with Preview and Delete
The second one is to upload the image and retrieve a thumbnail from server to show in clientside, you can check this post: http://www.sitepoint.com/image-upload-example/
Yes, it is possible to show the image in the tmp folder. Add an onchange event for input type = file; which triggers a function and it loads the image.
!!! Don't forget to set width for img tag
function preview() {
$('#frame').attr('src',URL.createObjectURL(event.target.files[0]));
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="file" onchange="preview()">
<img src="" width="100px" height="100px" id="frame">
</form>
</body>
I'm using this form to add the title,link of the image and the text of the article to the database.
I'm using type="text" for the image link,now,it's getting borring to upload an image on a external image upload service and copy the link.
I want to upload the image with this for and store THE LINK of the image in the database.
The form:
<?php if (!$_POST["go"]){ ?>
<form method="post" action="">
<input name="article_title" type="text">
<input name="article_image_url" type="text"> <!-- i want here type="file" -->
<textarea name="article_text"></textarea>
<input type="submit" name="go" value="Submit">
</form>
<?php
} else {
$date=date("Y.m.d");
$title = $_POST["article_title"];
$image_url = $_POST["article_image_url"];
$text = $_POST["text"];
$sql="INSERT INTO articles (title,image_url,text,date) VALUES ('$title', '$image_url', '$text', '$date')";
if (mysql_query($sql)){
echo "done";}
else {echo "error<br>" . mysql_error();}}
?>
Please help me with this :)
ps:sorry for my English :$
The first thing you should do, and it seems you are clueless about SQL escaping, is add following before you access the first $_POST var:
$_POST = array_map("mysql_real_escape_string", $_POST);
Then you seemingly want to use a file upload for the image. If so change the url field to:
<input type=file name=image>
This uploaded file will show up in $_FILES. Use it like this, preferrably after you've read the other fields from $_POST:
if ($img = $_FILES["image"]["tmp_name"]) {
$image_url = md5_file($img) . ".jpeg";
move_uploaded_file($img, "./upload/$image_url");
$image_url = "http://www.example.org/where/$image_url";
}
There are lot's of security concerns with that. But that's out of scope here, so I hardwired it to .jpeg. There's lots of information in the manual and its comments: http://de2.php.net/manual/en/features.file-upload.php