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')";
} ?>
Related
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
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);
?>
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