This is my php code for image upload.with some text.This script is used in an android app code.
Image id ,Image url and text save in database correctly but image not saved in server folder. Why is happen?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_FILES['image'];
$fullname = $_POST['fullname'];
require_once('dbConnect.php');
$sql ="SELECT id FROM uploadfinding ORDER BY id ASC";
$res = mysqli_query($conn,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$actualpath = "My_url/$path";
// query for db
$sql = "INSERT INTO uploadfinding (image,fullname) VALUES ('$actualpath','$fullname')";
if(mysqli_query($conn,$sql)){
file_put_contents($actualpath,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($conn);
}else{
echo "Error";
}
?>
This one is the working code for this question
<?php
header("content-type:application/json");
require_once('dbConnect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_FILES['image'])){
$errors= array();
$fullname = $_POST['fullname'];
$location = $_POST['location'];
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$date=date('Y-m-dH:i:s');
$path="folder_name/".$date.$file_name;
$actualpath = "http:myUrl/uploadfinding/$path";
if(empty($errors)==true){
move_uploaded_file($file_tmp,$path);
$sql = "INSERT INTO uploadfinding (image,fullname,location,) VALUES ('$actualpath','$fullname','$location',)";
if(mysqli_query($conn,$sql)){
echo "message";
}
}else{
print_r($errors);
}
}
}
?>
Make sure you have added 'enctype' => 'multipart/form-data', for example:
<form method="post" name="abc" enctype="multipart/form-data">
Related
I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.
Here is my code that has to display the images.
<main>
<section align='center'>
<h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
<br><br>
<div class="wrapper">
<!--h2 align='left'>Photos</h2-->
<div class="photo-container">
<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Error updating photo library!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
<h3>'.$row["filetitle"].'</h3>
<p>'.$row["filedescription"].'</p>
</a>';
}
}
?>
</div>
</div>
</section>
</main>
Connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>
And here is the database connection from the html form.
<?php
if(isset($_POST['upload'])) {
$newFileName = $_POST['filename'];
if(empty($newFileName)){
$newFileName = "photo";
}else{
//Replacing spaces in filename with underscores
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$filetitle = $_POST['filetitle'];
$filedescription = $_POST['filedescription'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
//Error handling for allowed file types
if(in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 10000000) {
//Make file unique through naming
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../libraries/photos/" . $imageFullName;
include_once "dbh.php";
//Checking for error handling when fields have been left empty
if(empty($filetitle) || empty($filedescription)) {
header("location:photos_edit.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM photos;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setPhotoOrder = $rowCount + 1;
$sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("location: photos_edit.php?upload=success");
}
}
}
}else{
echo "Photo is too big!";
exit();
}
}else{
echo "An error ocurred while uploading your image!";
exit();
}
}else{
echo "File type not supported";
exit();
}
}
?>
For example, if you use this code, you can load an image from DB (MySQL) :)
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>
While updating the record if I do not upload the image and click on update button the current image will be removed.
Here is the code
<?php
if (isset($_POST['update_record'])){
$edit_id = $_GET['edit'];
$username = $_POST['name'];
$email = $_POST['email'];
$city = $_POST['city'];
$file_name = $_FILES['file']['name'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$allowed = ['png' , 'jpg' , 'jpeg'];
$pathinfo = pathinfo($file_name , PATHINFO_EXTENSION);
$destination = "uploads/" . $file_name ;
if (in_array($pathinfo , $allowed)){
if ($file_size < 100000){
if ($file_error === 0){
move_uploaded_file($file_tmp_name, $destination) ;
} //error close here
else{
echo "Some kind of error";
}
} //size close here
else{
echo "File Size is too big!";
}
} //type close here
else{
echo "File type is wronng";
}
$update_query = "UPDATE crud
SET `name`='$username' , `email`='$email' ,
`city`='$city', `image`='$destination'
WHERE id=$edit_id";
$run = mysqli_query($connect, $update_query) ;
if ($run){
header("Location: show_record.php") ;
} else{
echo "Error in Updating the data";
}
} //main if isset close here
?>
verify that a file exists before proceeding. if no file exist, then DO NOT update the $destination in your update query
//use a flag
$fileExists = false;
if(!empty($_FILES['file'])) { //check here
$fileExists = true;
//rest of the file upload code
}
if($fileExists === true){
// a file was uploaded. now update $destination variable in update query as well
}
So I'm trying to upload the file name of the image in the database and the image itself will be save in the folder inside a root folder.
In my codes, the image name is able to be saved in the database but the image itself did not save in the folder. Why is that?
Here's my code:
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
What seems to be the problem of my codes?
You just get the contain of file. forget to put in target folder use file_put_contents
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
// Write the contents back to the file
file_put_contents($target_file, $imageData);
You can also use move_uploaded_file to uploaded file to a new location
Here try this, I edited your codes.
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "../updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
file_put_contents($target_file, $imageData);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
just copy and paste it. tell if it worked.
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
$id = $_POST['id'];
//remove
if (file_exists($target_file))
{
$result = unlink($target_file);
if (!$result)
{
//error, display error,
return false;
}
}
//upload
$result = move_uploaded_file($_FILES['image']['tmp_name'], $img_dir);
if(!$result)
{
//error upload
}
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
try
So i have an Android app that uploads a selected video to my server. The video right now gets uploaded fine but it doesnt get placed to the new directory that is created when i upload the video. Even though i think the location is wrong right now in the move_uploaded_file it still uploads to the ProductVideos.
I want it to create a new directory and then store the video there. (new directory has 777 permissions even though its bad i know and new directory is created in /var/www/html/ProductVideos/)
PHP code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$file_name = $_FILES['myFile']['name'];
$file_size = $_FILES['myFile']['size'];
$file_type = $_FILES['myFile']['type'];
$temp_name = $_FILES['myFile']['tmp_name'];
$ProductAccountName = $_POST['ProductAccountName'];
$ProductName = $_POST['ProductName'];
$NewDirectory = "/var/www/html/ProductVideos/" . $ProductAccountName;
mkdir($NewDirectory, 0777, true);
$conn = mysqli_connect("XXXXXX", "XXXXXX", "XXXXXX", "Products");
$sql_query = "select Product_Name from Product_Details where Product_Name like '$ProductName';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$statement = mysqli_prepare($conn, "UPDATE Product_Details SET 7sec_File_Path = ? WHERE Product_Name = '$ProductName'");
$FileLocation = $NewDirectory."/".$ProductName;
mysqli_stmt_bind_param($statement, "s", $FileLocation);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}
mysqli_close($conn);
$location = "/var/www/html/ProductVideos/".$ProductAccountName."/";
move_uploaded_file($temp_name, $location.$file_name);
//move_uploaded_file($location.$file_name, "/var/www/html/ProductVideos/".$ProductAccountName."/");
echo "Uploaded!";
}else{
echo "Error";
}
?>
Try this...
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_FILES['myFile']))
{
$file_name = $_FILES['myFile']['name'];
$file_size = $_FILES['myFile']['size'];
$file_type = $_FILES['myFile']['type'];
$temp_name = $_FILES['myFile']['tmp_name'];
}
$ProductAccountName = isset($_POST['ProductAccountName'])?$_POST['ProductAccountName']:rand();
$ProductName = isset($_POST['ProductName']):$_POST['ProductName']:rand();
$NewDirectory = "/var/www/html/ProductVideos/" . $ProductAccountName;
if (!file_exists($NewDirectory))
{
mkdir($NewDirectory, 0777, true);
}
$conn = mysqli_connect("XXXXXX", "XXXXXX", "XXXXXX", "Products");
$sql_query = "select Product_Name from Product_Details where Product_Name like '$ProductName';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 )
{
$statement = mysqli_prepare($conn, "UPDATE Product_Details SET 7sec_File_Path = ? WHERE Product_Name = ?");
$FileLocation = $NewDirectory."/".$ProductName;
mysqli_stmt_bind_param($statement, "s", $FileLocation,$ProductName);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}
mysqli_close($conn);
move_uploaded_file($temp_name, $NewDirectory.$file_name);
//move_uploaded_file($location.$file_name, "/var/www/html/ProductVideos/".$ProductAccountName."/");
echo "Uploaded!";
}
else
{
echo "Error";
}
?>
Hope it will work for you.
I've looked around and haven't found particularly what I'm after.
I have quite a few forms with text input and file uploads.
I've figured how to upload a file, give it a unique ID and get it into my web server folder. Pretty smooth sailing. However, I would like to also get that fancy new ID into my MySQL database.
I've separated my upload.php page with text forms going to the database
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (location, price, thick, width, height, model, brand, email,category)
VALUES ('$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
and then my bit to get the file to its new location in my web server.
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . uniqid();
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
}
else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Basically, I need to get that new unique ID to go to where the text information is going, because they're all being submitted at once. And I'd like to be able to figure out who uploaded what if need be. If it didn't have a unique ID I can get it to work, but for some reason having that uniqid trips me up. Thoughts? Much obliged.
Save the uniqid() to a PHP variable and then you can use it in more than one place:
First, create an ID:
<?php
$ID = uniqid();
?>
Then, save your file, using your new $ID variable:
<?php
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . $ID;
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
} else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Then, save your data to the db, including $ID
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (ID, location, price, thick, width, height, model, brand, email,category)
VALUES ('$ID', '$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
?>