How to debug if image is not uploading to the server - php

I want to upload image to the server and save the file name in MySql. I am uploading from image from Android Application , i am sending all the required params from android app but still something is wrong in copy image in server. It is echoing "Upload Failed".
<?php
$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];
include('../Config.php');
$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
$filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
if($type == "Address"){
$sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
}else if($type == "ID"){
$sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
}else if($type == "GramPanchayat"){
$sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
}
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
}
?>

Let's start here. I would change the copy() function to the move_uploaded_file() function.
Secondly, You need to check to make sure the path for the download destination exist. If it does not then we need to create it.
We also need to make sure the folder/file has permissions to be able to write. If it does not then change the folder/files permission.
Then when done, change your folder/files permissions back to what they were originally.
Like so:
$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];
include('../Config.php');
$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
//Check to see if the folder exist.
if(!file_exists($uploaddir)) {
mkdir($uploaddir, 0777, true); //If it does not exist then create it and set permissions to be able to write.
}
//The folder does exist at this point. Check to see if it's writable.
if(!is_writable($uploaddir)){
chmod($uploaddir, 0777); //The folder is not writeable. Set the folder to be able to write.
}
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
$filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
if($type == "Address"){
$sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
}else if($type == "ID"){
$sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
}else if($type == "GramPanchayat"){
$sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
}
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//Reset the permissions back to what you need them to be.
//You probably want 0755
chmod($uploaddir, 0755);
chmod($uploadfile, 0644); //Sets your new file to read only.
//Add this code below to test.
if(file_exists($uploadfile)) {
echo 'Your file exist.';
}else{
echo 'You file does not exist.';
}
}
else
{
echo "Upload failed";
}
}
Some resources for you to read.
move_uploaded_file()
is_writeable()
chmod()
You will also want to read up on file permissions an how to properly set them. Not doing this correctly can leave you open to unwanted security issues.
Hope this helps.

Related

PHP file upload from imput with rename not move the file into the destination folder

I am trying to make a script in PHP which is a basic file upload function. Everything is done and everything works except the move_uploaded_file command. So what my program does in brief: You can upload an image from your PC and it renames it and uploads it to my localhost /uploads/ folder with a new name which is the current time. The problem is that, the program is not moves the file into the /uploads/ folder, but rename it, you can see it in the MYSQL Database, because the new path and name are correct. I am struggling with this one bug or error or I don't really know what it is. (Before the renaming function everything was working fine, you could upload your file into the /uploads/ folder). Any idea what should I do?
Code:
<?php
$con = mysqli_connect("localhost", "root", "", "dotech");
$target_dir = '/uploads/';
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
$target_type = basename($_FILES['fileToUpload']['type']);
$target_ext = strtolower(end(explode('.',$_FILES['fileToUpload']['name'])));
$target_tmp = $_FILES['fileToUpload']['tmp_name'];
$target_size = $_FILES["fileToUpload"]["size"];
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$user_id = mysqli_real_escape_string($con, $_POST['cpmsbtndbldsrd']);
$post_text = mysqli_real_escape_string($con, $_POST['user_post_textarea']);
$post_tag = mysqli_real_escape_string($con, $_POST['tag_select']);
if(isset($_POST["create_post"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
header("Location: /p/index.php?id=$user_id&fileupload=invalid_file_type");
exit();
}
if ($uploadOk = 1) {
$target_file = $target_dir.''.date('YmdHis').'.'.$target_ext;
$post_file = $target_file;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
if ($stmt = $con->prepare('INSERT INTO user_posts (user_id, post_desc, post_file, post_file_type, post_file_size, post_tags) VALUES (?, ?, ?, ?, ?, ?)')) {
$stmt->bind_param('isssis', $user_id, $post_text, $post_file, $target_type, $target_size, $post_tag);
$stmt->execute();
header("Location: /p/index.php?id=$user_id&fileupload=success");
exit();
} else {
echo 'Could not prepare statement!';
}
$stmt->close();
}
}
?>
EDIT:
So I made changes on my code and I have a new error or I don't even know what to call this. By the way, it finally move the renamed file into the /uploads/ folder, but not insert into the database.
CHANGES:
$tmp = explode('.', $target_name); // New exploding method
$target_ext = #end($tmp);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
$stmt = $con->prepare('INSERT INTO user_posts (user_id, post_desc, post_file, post_file_type, post_file_size, post_tags) VALUES (?, ?, ?, ?, ?, ?)');
$stmt->bind_param('isssis', $user_id, $post_text, $post_file, $target_type, $target_size, $post_tag);
$stmt->execute();
header("Location: /p/index.php?id=$user_id&fileupload=success");
exit();
} else {
var_dump($_FILES["fileToUpload"]);
}
Error:
The move_uploaded_file() function will return the result of the operation, so you should check it before insert it to the database:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
// success
} else {
// try to debug it, var_dump($_FILES["fileToUpload"]);
// The destination directory must exist, so check if $target_file path is available
}

I would like to create separate image folder based on registration id during register in php

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.

File upload working on localhost but not working after publishing on server

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

upload an image using PHP to MySQL

I'm trying to upload an image using PHP to MySQL. In the query i'm trying to save the image and the directory of the image in the DB, but I get empty directory in the DB, plus no image in the folder. Any help would be greatly appreciated!
<?php
// include db connect class
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/android_connect/db_connect.php');
$db = new DB_CONNECT();
//Setting up images directory
$target = "./images";
$target = $target . basename( $_FILES['photo']['name']);
$photo=($_FILES['photo']['name']);
//inserting data order
$order = "INSERT INTO scb
(photo, directory)
VALUES
( '$_POST[$target]',
'({$_FILES['photo']['name']})')";
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo "Thank you for submitting!";
} else{
echo "Sorry, something went wrong! Please try again!";
}
?>
Well first mysql_query is outdated use PDO instead (you'll have to check if this feature is enabled on your server by using phpinfo());
Try this
<?php
//Connect to sql db
try {
$user = "username";
$pass = "password";
$db = new PDO('mysql:host=yourhost;dbname=yourdb', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//Setting up images directory
$target = "./images/"; //you forgot the last slash
$target = $target . basename($_FILES['photo']['name']);
$photo = $_FILES['photo']['name'];
//inserting data order
$stmt = $db->prepare("INSERT INTO scb (photo, directory) VALUES (:photo, :directory)");
$stmt->bindParam(':photo', $_POST[$target]);
$stmt->bindParam(':directory', $_FILES['photo']['name']);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//declare in the order variable
if($stmt->execute()){
echo "Thank you for submitting!";
} else{
echo "Sorry, something went wrong! Please try again!";
}
?>
Have you checked for any errors or warnings in the web server log files? Do you get any sensible output if you write:
print_r($_FILES);

How can I have a upload auto linked in a mysql table

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.

Categories