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
Related
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);
I have a problem, because the picture isnt sent to my database. I used different PHP file which doesnt decode picture again and everything works fine, all results appear in my database, but when I try to connect to that file it doesnt work. This is the php that doesnt work properly:
<?php
header('Content-type : bitmap; charset=utf-8');
if(isset($_POST["encoded_string"])){
$username = $_POST["username"];
$description = $_POST["description"];
$encoded_string = $_POST["encoded_string"];
$decoded_string = base64_decode($encoded_string);
$path = 'place on server where I want pictures to be sent' ;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if($is_written > 0){
$con = mysqli_connect("localhost", "xx", "xx", "xx");
$query = "INSERT INTO meals(username, description, image) values('$username', '$description' , '$path');";
$result = mysqli_query($con, $query);
if($result){
echo "success";
}else{
echo "failed";
}
mysqli_close($con);
}
}
?>
And that one send details properly but not in the way I would like to:
<?php
$con = mysqli_connect("localhost", "xx", "xx", "xx");
$username = $_POST["username"];
$description = $_POST["description"];
$encoded_string = $_POST["encoded_string"];
$statement = mysqli_prepare($con, "INSERT INTO images (username, description, image)
VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $username, $description, $encoded_string);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Is it casued beacause I have to change FTP settings?
the second code passes all data to database but image is in base64 format so there are plenty characters and it runs slowly. What I want to do is to be able to use the first code, but it doesn't decodes base64 to actual image I am sending and it shows no result in database nor folder in server.
Try this:
$encoded_string = $_POST["encoded_string"];
$path="uploads"."/".rand()."_".time().".jpeg"; //uploads is folder, file name is composed of random number+underscore+time.jpeg
$upload_url="http://xxx.xx.xx.xx/".$path;
if(file_put_contents($path,base64_decode($encoded_string))){
//file uploaded, insert $upload_url into database(Type varchar)
}else{
//echo "file could not uploaded";
}
I am trying to use a PHP file to upload files from an Android app to a web server.
This the PHP file:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = 'usuarios/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://'.$server_ip.'/danyra/administrar/application/admin/'.$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'];
//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
line 45 --> move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO `images` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
//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(id) as id FROM images";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['id']==null)
return 1;
else
return ++$result['id'];
}
This file is taken from a tutorial.
This is the scenario:
The PHP file is at:
http://myserver.com/danyra/android_login_api/upload.php
The folder where I want to store the uploaded images is at:
http://myserver.com/danyra/administrar/application/admin/usuarios
I am using POSTMAN to check the script, and I am always receiving this error:
Warning: move_uploaded_file(usuarios/18.png): failed to open stream: No such file or directory in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
Warning: move_uploaded_file(): Unable to move '/tmp/phpMciKUa' to 'usuarios/18.png' in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
{"error":false,"url":"http:\/\/XXX.XXX.246.130\/danyra\/administrar\/application\/admin\/usuarios\/18.png","name":"fsd"}
I have tried a lot of options changing paths, but with no success.
Any help is welcome.
I think your current path is incorrect. You should be using a relative path.
Try this path
$upload_path = $_SERVER['DOCUMENT_ROOT'].'/danyra/administrar/application/admin/usuarios/';
I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.
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.