can anyone help me to solve my problem? Currently, I created a system that can upload a photo and the function successful. but the name of the photo that saves to the database and also at the server folder is the actual name of the photo.
Now, I want to rename the photo based on id. Below is my code:
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$image = $_FILES['uploadFile']['name'];
// image file directory
$target = "../../../../images/upload/".basename($image);
$ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$image";
// Prepare an insert statement
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Attempt to execute the prepared statement
if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
// Records created successfully. Redirect to landing page
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
?>
Try this code
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$image = $_FILES['uploadFile']['name'];
//set new name for upload image
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $report_id. '.' . end($temp);
$target = "../../../../images/upload/".$newfilename;
$ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$newfilename";
// Prepare an insert statement
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Attempt to execute the prepared statement
if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
// Records created successfully. Redirect to landing page
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
?>
Change one line of your code
$target = "../../../../images/upload/".$report_id . '.'. pathinfo($image, PATHINFO_EXTENSION);
Related
Here I want to create one more folder inside upload folder and that folder will be unique like based on registration id.
In database I want to save path like ../upload/userid/image_name.jpg
Here is my PHP code:-
session_start();
include 'db.php';
$target_dir = "../upload/";
$target_file = $target_dir . basename($_FILES["photo"]["name"]);
$uploadOk = 1;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file);
}
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "SELECT email FROM register where email='$email'";
$qur = $connection->query($sql);
if(mysqli_num_rows($qur)==0)
{
$password = md5($_POST["password"]);
$phone = $_POST["phone"];
$sql = "INSERT INTO register(name,email,password,photo,phone)
VALUES ('$name','$email','$password','$target_file','$phone')";
$success = $connection->query($sql);
if (!$success) {
die("Couldn't enter data: ".$connection->error);
}else{
echo "Thank You For registration <br>";
}
}else{
echo "Email-id already exist";
}
$connection->close();
Try this code.
if($uploadOk == 0){
echo "Sorry, your file was not uploaded.";
}else{
mkdir($target_dir.$id);
//The variable $id is your registration id.
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_dir.$id."/");
}
You can use php function mkdir("/path/to/my/dir"); You would need to move use of function move_uploaded_file after record has been inserted in database [in case of new registration]. After record is inserted you would need to get last inserted id from mysql and use it in mkdir function with full path of the folder where you want to keep the uploaded file.
Actually My problem is when I am registering user profile on localhost is working fine and image is storing in folder but after published is not storing image in folder.
my php code
$target_dir = "../upload/";
$target_file = $target_dir . basename($_FILES["photo"]["name"]);
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file);
}
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "SELECT email FROM register where email='$email'";
$qur = $connection->query($sql);
if(mysqli_num_rows($qur)==0)
{
$password = md5($_POST["password"]);
$birth = $_POST["birth"];
$sql = "INSERT INTO register(name, email,password,photo,birth)
VALUES ('$name','$email','$password','$target_file','$birth')";
$success = $connection->query($sql);
if (!$success) {
die("Couldn't enter data: ".$connection->error);
}else{
echo "Thank You For registration";
}
}else{echo "Email-id already exist";
}
most of the time server need dont allow to upload data.
you need to give permission to your upload folder and it will work
You can check your error: $_FILES['photo']['error']
You can get more detail from here :- http://php.net/manual/en/features.file-upload.errors.php
Hey guys I am having issues with my php file which is supposed to allow a user to post a status along with a picture which is uploaded to a server and its path along with the username of the user is added to the db.
DB Colomns:
postID (A.I)
username
status
imagepostpath
timestamp (added automatically inserting a new entry)
extra info: I have changed the code from one of my already working ones, but when I attempt to test the PHP file with Postman my error is "[]".
I'm not too familiar with PHP so if you see that the mistake that I'm making is simple, please help me understand it :)
Here is my code:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = '000002/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://'.$server_ip.'/Users/Images/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['name']) and isset($_FILES['image']['name'])){
//connecting to the database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//getting name from the request
$name = $_POST['name'];
$status = $_POST['status'];
$timestamp = date('Y-m-d H:i:s');
//getting file info from the request
$fileinfo = pathinfo($_FILES['image']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO `flare`.`tbl_user_feed` (`postID`, `username`, `status`, `imagepostpath`, `timestamp`) VALUES (NULL, '$name', '$status', '$file_url');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['name'] = $name;
$response['imagepostpath'] = $file_url;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
}
/*
We are generating the file name
so this method will return a file name for the image to be upload
*/
function getFileName(){
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
$sql = "SELECT max(postID) as postID FROM tbl_user_feed";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['postID']==null)
return 1;
else
return ++$result['postID'];
}
?>
Change these lines:
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
Your file path is always the same so old files are being overwritten by new...randomize it with md5()
$unix = time();
$file_path = $upload_path . getFileName() . md5($unix) . '.'. $extension;
then alter your query slightly
$sql = "INSERT INTO `flare`.`tbl_user_feed` (`postID`, `username`, `status`, `imagepostpath`, `timestamp`) VALUES (NULL, '$name', '$status', '$file_url', '$unix')";// remove the semicolon before last double quote and add value for 5th column
I'm trying to upload an image to my server using the following form by Sanwebe.
Can be found here.
However when I'm pressing upload, the new thumb loads perfectly fine. However, my image can't be uploaded to the database using the exact same variables from which the image is being viewed. How come?
I tried putting the db information just infront of the query. Like this:
echo '<div align="center">';
echo '<img src="images/profile-pictures/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
echo '</div>';
$profile_pic_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_pic_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
require 'database.php';
$profile_pic_db_upload = $db->prepare("UPDATE login SET profile_picture_temp = :profile_pic_temp, profile_picture_full_temp = :profile_pic_full_temp WHERE user_session = :session_user");
$profile_pic_db_upload->bindParam(':session_user', $session_user, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_temp', $profile_picture_temp, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_full_temp', $profile_picture_full_temp, PDO::PARAM_STR);
$profile_pic_db_upload->execute();
$confirm_upload_db = $profile_pic_db_upload->rowCount();
if($confirm_upload_db != 0){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
EDIT TWO:
The query now runs, however, I get the feedback "Profile picture could not be uploaded.". How come the query does not run properly?
EDIT FOUR:
I have tried changing the user_session = :session_user to id = 1 instead. I then get upload successfull, however, the value is only inserted into profile_picture_temp and is set to 0. Somehow the bindParam changes the value. Why?
EDIT THREE:
I have now tried using mysqli aswell. Same results here. Returning could not be uploaded. However, does not change value in DB.
$sql = "UPDATE login SET profile_picture_temp = ? AND profile_picture_full_temp = ? WHERE user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
if($stmt->fetch()){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
Are you sure this line isn't throwing a PHP error...
$confirm_upload_db = $$profile_pic_db_upload->rowCount();
^^
The $$ (two dollar signs) are how we reference a variable variable; but $profile_pic_db_upload doesn't contain the name of another variable, it's a reference to a PDO statement object.
Another note. The rowCount() function returns the number of rows affected by the UPDATE statement; if the UPDATE statement succeeds, but no actual changes are made to the row (because the values assigned to the columns are the same as what's already stored in the columns), then rowCount() will return 0.
(To change that behavior, to have it return the number of matched rows, you can use PDO::MYSQL_ATTR_FOUND_ROWS).
The problem was fixed using the following query:
$profile_picture_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_picture_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
$sql = "UPDATE login l SET l.profile_picture_temp = ?, l.profile_picture_full_temp = ? WHERE l.user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
$result = $stmt->affected_rows;
if($result == 1){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
I can't identify the problem itself, however, I managed to fix it by adding UPDATE login l. Using alias fixed it somehow.
This is my code :
<?php
session_start();
include "connect.php";
$username=$_SESSION['username'];
if(isset($_SESSION['username'])){
$teks= mysql_real_escape_string($_POST['teks']);
$photo= $_POST['photo'];
$path_file = pathinfo($_FILES['photo']['name']);
$type_file = $_FILES['photo']['type'];
$name_file = $_FILES['photo']['name'];
$directory = "image/$nama_file";
if (!empty($lokasi_file)) {
move_uploaded_file($lokasi_file,$direktori); }
$sql=mysql_query("SELECT username from member where username='$username'");
$result=mysql_fetch_array($sql);
mysql_query("Insert into posting (username, pic_post, text_post, location, datetime) values('$username','$photo','$teks', '$photo', NOW())");
header("Location: member.php");
}
?>
I've got an issue with this code, and can't move the uploaded image into the /image folder.
The code you have written is full of bugs
$photo= $_POST['photo']; This is wrong... $photo= $_FILES['photo'];
Please go through the bellow Link, you will find a good tutorial here.
http://www.w3schools.com/php/php_file_upload.asp
New Edit : ( I have Just edited the your code)
<?php
session_start();
include "connect.php";
$username=$_SESSION['username'];
if(isset($_SESSION['username'])){
$teks= mysql_real_escape_string($_POST['teks']);
$photo= $_FILES['photo']['name'];
$path_file = pathinfo($_FILES['photo']['name']);
$type_file = $_FILES['photo']['type'];
$name_file = $_FILES['photo']['name'];
$directory = "image/$nama_file";
$target_file = $directory . basename($_FILES["photo"]["name"]);
if (!empty($lokasi_file)) {
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file);
}
$sql=mysql_query("SELECT username from member where username='$username'");
$result=mysql_fetch_array($sql);
mysql_query("Insert into posting (username, pic_post, text_post, location, datetime) values('$username','$photo','$teks', '$photo', NOW())");
header("Location: member.php");
}
?>
You have several erros in your code.
Check this block
$photo= $_POST['photo'];
$path_file = pathinfo($_FILES['photo']['name']);
$type_file = $_FILES['photo']['type'];
$name_file = $_FILES['photo']['name'];
$directory = "image/$nama_file";
Files are in $_FILES array, not in $_POST, so your photo will be $photo= $_FILES['photo'];
You never use $path_file, so why is it?
You have a type, with $nama_file, that is $name_file
Where is $lokasi_file and $direktori come from? That should be $_FILES['photo']['tmp_name'] in move upload.
Do not use mysql functions, they are deprecated. Use mysqli or PDO instead.
Escape your variables comes from outside, because of sql injection, or use prepared statements.
You do not use the result of your first $sql.
You can not store $photo in your database, because that is an array
Add exit; or die; after redirection.
Sidenote: Why are you store the location of the file twice?
So your final code will be something like this, but again, change the mysql_ functions!
session_start();
include "connect.php";
$username = $_SESSION['username'];
if (isset($_SESSION['username'])) {
$teks = mysql_real_escape_string($_POST['teks']);
$type_file = $_FILES['photo']['type'];
$name_file = "image/" . basename($_FILES['photo']['name']);
if (move_uploaded_file($_FILES["photo"]['tmp_name'], $name_file)) {
//Why is it here, for what? Never used the $res (what is acually $row)
//$sql = mysql_query("SELECT username from member where username='" . mysql_real_escape_string($username) . "'");
//$res = mysql_query($sql);
mysql_query("Insert into posting (username, pic_post, text_post, location, datetime) "
. "values('" . mysql_real_escape_string($username) . "',"
. " '" . mysql_real_escape_string($name_file) . "',"
. " '" . $teks . "',"
. " '" . mysql_real_escape_string($name_file) . "', NOW())");
header("Location: member.php");
die();
}
}
thanks so much for answer..
and here is my successfully code :
<?php
session_start();
include "connect.php";
$username=$_SESSION['username'];
if(isset($_SESSION['username'])){
$koneksi = mysqli_connect("localhost","root","");
mysqli_select_db($koneksi, "dbjashik");
$teks = $_POST['teks'];
$folder = "image";
$tmp_name = $_FILES["photo"]["tmp_name"];
$name = $folder."/".$_FILES["photo"]["name"];
//to moving the file into /image directory
move_uploaded_file($tmp_name, $name);
//inserting query
$input = mysqli_query($koneksi, "INSERT INTO posting VALUES(null, '$username', '$name' ,'$teks', '$name', NOW() )");
header("Location: member.php");
}
?>