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);
Related
I want to make an application in android where user uploads photo and that uploads will be inserted in my MySQL database using PHP
but my PHP script generates an error that
Undefined index image in PHP
following is my PHP files-
"Constants.php"
<?php
$db_name="mydb";
$local_username="root";
$local_password="";
$server_name="localhost";
$conn=
mysqli_connect($server_name,$local_username,$local_password,$db_name);
if($conn)
{
echo "Connection successful";
}
else
{
echo "Connectionj failed";
}
?>
"imageUploadScript.php"
<?php
require "Constants.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$image = $_POST['image'];
$mobile = $_POST['mobile'];
// if(isset($_POST['image']))
//{
$ImagePath = "imageUploads/$mobile.jpg";
$ServerURL = "yourPath/$ImagePath";
$InsertSQL = "INSERT INTO info (img) values('$ServerURL') where
mobile=$mobile";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "Your Image Has Been Uploaded.";
mysqli_close($conn);
}
else{
echo "Please Try Again";
}
//}
}
?>
any help from your side will be appreciated
For uploading an image, you need to use
$_FILES['image']
instead of
$_POST['image']
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
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.