PHP upload in database and folder in my root folder - php

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

Related

Displaying images from Database not working

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'].'">';
}
?>

alternate to upload image or not

I am new in stackoverflow and in PHP too, so I want to describe my problem first. Sorry if I have bad grammar, I am not native though.
I make a form that let user post (to database) with or without an image, this the code
$link = mysqli_connect('localhost', 'root', '12345!##', 'pklapps') or die("Couldnt connect to the server");
//public info dari admin
if (isset($_POST["title"]) && isset($_POST["content"]) && isset($_POST["category"])) {
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if (!isset($_FILES['userfile'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
} else {
header('Location: post.php?error');
}
} else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if ($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
} else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
}
and the form goes normal when i attach the image or file but it goes to header('Location: post.php?errimg'); when i not attach the image. Please help me with this, thank you.
Replace your if condition from !isset($_FILES['userfile']) to empty($_FILES['userfile']['name'])
//if (!isset($_POST[]))
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if(empty($_FILES['userfile']['name'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
}
else {
header('Location: post.php?error');
}
}
else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
}
else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
// $query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
} ?>

how to Save image in sever folder

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">

upload video to specific folder in PHP

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.

How to Declare timestamp as variable and convert to ddmmyy format

I have a date issue here. I have a timestamp field in mysql table called filedate. However I have tried several times to declare it and also convert it to a dd-mm-yy format. Unfortunately when I load it the date is still in timestamp format and when I then upload it claims I haven't declared the variable filedate.
Any assistance pointing me in the right direction would be gratefully accepted.
All the code is below. I also have a HTML file to show upload and description.
if (isset($_POST['action']) and $_POST['action'] == 'upload')
{
// Bail out if the file isn't really an upload
if (!is_uploaded_file($_FILES['upload']['tmp_name']))
{
$error = 'There was no file uploaded!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$uploadfile = $_FILES['upload']['tmp_name'];
$uploadname = $_FILES['upload']['name'];
$uploadtype = $_FILES['upload']['type'];
$uploaddesc = $_POST['desc'];
$uploaddata = file_get_contents($uploadfile);
$filedate = time();
include 'db.inc.php';
// Prepare user-submitted values for safe database insert
$uploadname = mysqli_real_escape_string($link, $uploadname);
$uploadtype = mysqli_real_escape_string($link, $uploadtype);
$uploaddesc = mysqli_real_escape_string($link, $uploaddesc);
$uploaddata = mysqli_real_escape_string($link, $uploaddata);
$sql = "INSERT INTO filestore SET
filename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
filedata = '$uploaddata'";
if (!mysqli_query($link, $sql))
{
$error = 'Database error storing file!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
if (isset($_GET['action']) and
($_GET['action'] == 'view' or $_GET['action'] == 'download') and
isset($_GET['id']))
{
include 'db.inc.php';
$id = mysqli_real_escape_string($link, $_GET['id']);
$sql = "SELECT filename, mimetype, filedata, DATE_FORMAT(STR_TO_DATE( filedate, '%d-%b-%Y'), '%Y.%m.%d')
FROM filestore
WHERE id = '$id'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Database error fetching requested file.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$file = mysqli_fetch_array($result);
if (!$file)
{
$error = 'File with specified ID not found in the database!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download')
{
$mimetype = 'application/octet-stream';
$disposition = 'attachment';
}
// Content-type must come before Content-disposition
header("Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
header('Content-length: ' . strlen($filedata));
echo $filedata;
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'delete' and
isset($_POST['id']))
{
include 'db.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
$sql = "DELETE FROM filestore
WHERE id = '$id'";
if (!mysqli_query($link, $sql))
{
$error = 'Database error deleting requested file.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
include 'db.inc.php';
$sql = 'SELECT id, filename, mimetype, description, filedate
FROM filestore';
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Database error fetching stored files.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$files = array();
while ($row = mysqli_fetch_array($result))
{
$files[] = array(
'id' => $row['id'],
'filename' => $row['filename'],
'mimetype' => $row['mimetype'],
'description' => $row['description'],
'filedate' => $row['filedate']);
}
include 'files3.html.php';
?>
Use NOW() when inserting. When formatting, I don't think you need to parse the TIMESTAMP typed column, as DATE_FORMAT should be able to work with timestamps directly.
This works:
SELECT DATE_FORMAT( CURRENT_TIMESTAMP( ) , '%Y.%m.%d' )
you have to use UNIX_TIMESTAMP() in your select statement

Categories