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.
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'].'">';
}
?>
I'm trying to update an existing image in my database using mysql query.
This is my edit.php where i edit user info
<?php
require_once "config.php";
if(isset($_GET['edit']))
{
$id = $_GET['edit'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
}
if(isset($_GET['id']))
{
$newText = $_GET['voornaam'];
$newText2 = $_GET['tussenvoegsel'];
$newText3 = $_GET['achternaam'];
$newText4 = $_GET['stemsoort'];
$newText5 = $_GET['adres'];
$newText6 = $_GET['postcode'];
$newText7 = $_GET['plaats'];
$newText8 = $_GET['telefoon'];
$newText9 = $_GET['mobiel'];
$newText10 = $_GET['email'];
$newText11 = $_GET['status'];
$newText12 = $_GET['lid_sinds'];
$newText13 = $_GET['lid_tot'];
$id = $_GET['id'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
$sql = "UPDATE user_data SET voornaam='$newText', tussenvoegsel='$newText2', achternaam='$newText3', stemsoort='$newText4', adres='$newText5', postcode='$newText6', plaats='$newText7', telefoon='$newText8', mobiel='$newText9', email='$newText10', status='$newText11',lid_sinds='$newText12',lid_tot='$newText13' WHERE id=$id";
$res = mysqli_query($link,$sql)
or die("Could not update".mysqli_error($link));
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
And this is how I upload images to a folder and then into mysql database
<?php
$msg = "";
$css_class = "";
$conn = mysqli_connect('localhost','root','','test');
if (isset($_POST['save-user'])) {
echo "<pre>", print_r($_FILES['profileImage']['name']),"</pre>";
$bio = $_POST['bio'];
$profileImageName = time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target)) {
$sql = "INSERT INTO users (profile_image, bio) VALUES ('$profileImageName','$bio')";
if (mysqli_query($conn,$sql)) {
$msg = "image uploaded";
$css_class = "alert alert-success";
}else {
$msg = "Database Error: Failed to save user";
$css_class = "alert alert-danger";
}
} else {
$msg = "Failed to upload image";
$css_class = "alert alert-danger";
}
}
?>
How can I combine the two and let a user edit his uploaded profile image? Thanks for helping out
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')";
} ?>
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
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">