i can't move an uploaded image to a spesific directory - php

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

Related

PHP / MySQL: Rename $_FILES['image']['name'] base on id

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);

Unable to post image and text to database. Receiving no errors

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

PHP, MySQL(i) and Dropzone

I am just wondering if someone can tell me what I'm doing wrong. My goal is pretty simple. Using dropzone or php to upload a file and insert a record into a database. I am able to post the record except for one field which is always showing "array" as the entry. I've tried changing variable names, inserting and removing quotes, etc to no avail. Any suggestions would be greatly appreciated.
Here is my code.
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
move_uploaded_file($tempFile,$targetFile); //6
}
$servername = "localhost";
$username = "root";
$password = "***************";
$dbname = "drop";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO uploads (id, file_name)
VALUES (NULL, 'file_name')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Figured out my own question. The answer is replacing file_name with $targetfile. Now it works as expected. Thanks.

php session and mysql update

am building a social network, i use php session to allow info to stay on the pages when the user goes to another page, however when the mysql script to update a value. it does reflect the change made unless the user log out and log back in. any ideas?
thanks . . .
<?php
session_start();
$login_email = $_SESSION['email'] ;
$login_pass = $_SESSION['pass'] ;
$target_path = "pictures/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path) and
$con = mysql_connect("localhost","root","naruto") and
mysql_select_db("users", $con) and
mysql_query (" UPDATE user_info SET profile_pic = ' $target_path ' WHERE email = '$login_email' AND password1 = '$login_pass' " ) ) {
session_destroy ();
include 'login.php';
session_start ();
if ( $login_email == $_SESSION['page_email'] && $login_pass == $_SESSION['page_pass ']){
header ('location:home.php');
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
$_SESSION['page_email']
$_SESSION['page_pass ']
It would depend on how you show the profile pic on a user's page. If it's through stored session, I would suggest you create a function to return a user information to store in $_SESSION, and call that on every user profile update
mysql_query (" UPDATE user_info SET profile_pic = ' $target_path ' WHERE email = '$login_email' AND password1 = '$login_pass' " ) ) {
session_destroy();
include 'login.php';
session_start ();
$_SESSION['user'] = get_user_info(); // your new function to return user info

Preventing overwrite of file upload and MySQL record through form?

I have a submission system set up and I'd like to have it so no duplicate entries can be submitted. If one is submitted, the ORIGINAL record and file upload is kept (not overwritten). Also, if it exists I'd like the form to display an error to the user. Here's my upload.php (referred to in the HTML form).
upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
// Connects to your Database
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `Table` VALUES ('$fname', '$lname', '$snumber', '$grade', '$email', '$target')") ;
//Writes the upload to the server
if(move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
//Tells you if its all ok
echo "Your submission ". basename( $_FILES['uploadedfile']['name']). " was successful and we have received your submission. Your result will be sent to $email ";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
How would I go about doing this?
EDIT: Combined suggestions from below, here's updated code however now I'm getting a Parse error: syntax error, unexpected T_ECHO in /path/to/upload.php on line 32
New upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
//Checks if submission already exists
if(file_exists($target))
{
echo "This submission already exists. Please check that you have entered all values correctly. If this is an error please contact support";
}
else
{
//Now that file doesn't exist, move it.
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
//MYSQL CONNECTION
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//MYSQL Entry
mysql_query("INSERT INTO Table (fname, lname, snumber, grade, email, target) VALUES ('".mysql_real_escape_string($fname)."', '".mysql_real_escape_string($lname)."', '".mysql_real_escape_string($snumber)."', '".mysql_real_escape_string($grade)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($target)."')")
echo "Your submission was successful and we have received your portfolio. Your marks will be sent out to $email.";
}
?>
Looks like you're storing the target in your database, so you can either check the database to see if that file already exists or you can use php's file_exists() function.
DB you obviously run the query before that insert statement and make your conditional based off the results.
Otherwise,
if(file_exists($target))
{
echo 'error';
}
else
{
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
// do success things here
}
file exists may require the full path. If it doesn't work right away see if prepending $_SERVER['DOCUMENT_ROOT'] helps.
I have solved this issue by applying an ajax query before submitting the form and the file
var param = "action=testfile&dirpath=" + dirpath + "&file=" + filename;
$.ajax({
type: "GET",
url: 'combi/testfile.php',
data: param,
success: function(data) {
test data .... if OK submit.
}
In testfile.php you test for the file and echo out the data
if($_GET['action'] == 'testfile'){
$msg = '';
$basedirpath = $_GET['dirpath'] . "/";
if(file_exists($basedirpath . $_GET['file'])) {
$msg = 'exists';
}
echo $msg;
}
$msg is returned in the data in the ajax call.

Categories