I need a help to upload and show an image from a database in PHP, I created a database that name is students contains the ID, image size,and image name, is there is a way to do that?
I searched on youtube about this but I found this code, but this code save to a directory.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
So, is there any way to save an image to a database and view it from a database?
You can save it into a MySQL table as a Blob but this isn't a really a good idea. Explanation here: http://www.hockinson.com/programmer-web-designer-denver-co-usa.php?s=47
Do what FDl said in the comments. Give each image a unique name and save it to your server, then save its unique name into your database.
Related
I'm not very experienced in coding PHP and MySQL, and am therefore looking for help. I'd like to do the following:
I have a form where users enter their contact details and at the end of the form there is a multiple file upload button.
Now if they submit the form, the following should happen:
First, I wanna check if all of the uploaded files are valid (file types are ok), if this is true, then the contact details should be entered to table_X of db_Z.
Then, all files should be moved/uploaded to the server and in table_Y of db_Z the file name, the (let's call it) eventID and date and time of the upload should be inserted, whereas the eventID is a foreignkey of the ID of the entry of the contact details.
The code I have until now is close, but the final step is missing. It adds the contact details to the database regardless of the result of the validation of the files.
How can I change it, so that it only adds something to the database if all files are valid? And also that it adds the contact details only once to database regardless of how many files are being uploaded?
Thanks in advance
Here's my code:
<?php
if(isset($_POST['submit'])){
$obs_fname = filter_input(INPUT_POST, 'firstname');
$obs_lname = filter_input(INPUT_POST, 'lastname');
$obs_address = filter_input(INPUT_POST, 'adresse');
// Include the database configuration file
include_once 'dbConfig.php';
$query = "INSERT INTO bear (obs_fname, obs_lname, obs_address)
values ('$obs_fname','$obs_lname','$obs_address')";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR SAVING POST : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
/**
* get the last inster id of the Post
**/
$post_id = $db->insert_id;
echo "Post id=".$post_id ."<br>\n";
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
if(isset($_FILES['files'])) {
foreach($_FILES['files']['name'] as $key => $name) {
$image_tmp = $_FILES['files']['tmp_name'][$key];
move_uploaded_file($image_tmp, './uploads/' . $name);
/**
* now insert the image with the post_id
**/
$query = "INSERT INTO images (eventID, file_name, uploaded_on)
VALUES ('$post_id', '$name', NOW())";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR INSERT IMAGE : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
}
}
header("Location: upload-complete.php");
}
You need to validate the MIME type on the server-side using mime_content_type() or using an image function that will return FALSE if it is not an image such getimagesize()
you gonna need a function like this + you need to validate the size $_FILES['files]['size] and the file extension $file_ext = strtolower(pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION))
function validate_images($image_tmp){
foreach($_FILES['files']['tmp_name'] as $key => $name) { // you need the tmp_name here and not "name" name is the one was when the file was in the client computer, After the form sent, the file will be in `/tmp` on the server and that is where php is accessing it.
$image_tmp = $_FILES['files']['tmp_name'][$key];
if(strpos(mime_content_type($image_tmp),"image")){
return true;
}else{
return false;
}
}
if(validate_images($image_tmp)){
// do the rest
}else{
die("no no no");
}
Also look here w3school image upload
this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
Having big time problems in displaying an image out of my mysql database
I'm storing it in a longblob type
when the image is displayed i get a broken image icon
here is code for storing image
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
//temporary file name
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$imageType = $_FILES['image']['type'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
VALUES
('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";
//For debugging purposes
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Your Image has been Added";
}
}
then printing the image
if(isset($_POST['usersImage'])){
//code to show images
$user = $_POST['usersImage'];
$sql = "SELECT * FROM `photos` WHERE userName = '$user'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
switch ($row['photoType']) {
case 'image/jpeg':
echo "<tr>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";
echo "</tr>";
//echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
//echo '<p id="caption">'.$row['caption'].' </p>';
break;
}
}
}
as you can see my latest attempt was to use base64 encoding to print out the image
my previous try was the commented out code
When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.
<?php
$photo_bin = //binary data from query here;
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $photo_bin;
Quick example^ of a php script that can be requested by the browser from an img tag.
Validation is important. You are opening yourself up to so many security issues.
Never use $_POST / $_GET inside a sql statement. Escape them, better yet, use PDO statements. Validate that the image is actually an image, at this point, you could be entering any type of file into your table.
As you're finding, it's also far more difficult to store images in a database than on the filesystem. Usually, there are far more arguments to store the image on the filesystem than inside a table.
Having a quick look down your insertion code, I'm not quite sure why you're adding slashes to the binary data. remove the call to addslahes, and try that.
having a big trouble trying to make this blob saved to a file and load it as an image.
Using SQLite Manager (Firefox Add-on) I was able to "Save As" a file with the content of my image BLOB. The result is a strange (for me) code.
Since I can´t post the "source of the file", I'm attaching one png with the example.
In my Mac, the saved file has no extention but I can view the image it produces as thumbnail.
So I'm trying to achieve the same result saving one file, but all I get is a 16 bytes document I can't read...
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'w');
fwrite($pic, base64_encode($theFile));
fclose($pic);
* EDIT *
$theFile = shell_exec("sqlite3 AddressBookImages.sqlitedb 'select data from ABThumbnailImage where record_id = ".$id."'");
if($theFile != '') {
file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $theFile);
}
Try to use (b for binary)
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'wb');
I find a solution to this, but its very slow, I'm posting a new question to ask help for improve this.
$sql2 = shell_exec("sqlite3 ".$endereco_iphone."".$db_pics." 'select hex(data) from ABThumbnailImage where record_id = ".$id."'");
//
if($sql2 !='' && $sql2 != 'NULL') {
$img = '';
foreach(explode("\n",trim(chunk_split($sql2,2))) as $h) {
$img .= chr(hexdec($h));
}
if(file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $img)) {
$cnt .= "<img class='pics' src='pics/thumbnails/pic_".$id.".jpg' width='30px' height='30px'></img>";
}
} else {
$cnt .= "<div class='pics'></div>";
}