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";
}
Related
i try to upload image to phpmyadmin server but in every time i get same error first error : Notice: Undefined index: image_path in /storage/ssd2/750/2564750/public_html/hi.php on line 12
Your Image Has Been Uploaded.
image is uploaded to server but its size =0 "zero"
php code
<?php
include 'DatabaseConfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_path'];
$ImageName = $_POST['image_name'];
$GetOldIdSQL ="SELECT id FROM UploadImageToServer ORDER BY id ASC";
$Query = mysqli_query($conn,$GetOldIdSQL);
while($row = mysqli_fetch_array($Query)){
$DefaultId = $row['id'];
}
$ImagePath = "images/$DefaultId.png";
$ServerURL = "https://xxxxx.000webhostapp.com/$ImagePath";
$InsertSQL = "insert into UploadImageToServer (image_path,image_name) values ('$ServerURL','$ImageName')";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "Your Image Has Been Uploaded.";
}
mysqli_close($conn);
}else{
echo "Not Uploaded";
}
?>
my database (id, image_path,image_name) both path and name datatype is text
i use postman to test my test like the following
https://i.imgur.com/VrIXOsN.png
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 am trying to upload an image to my server but can't seem to get it to work. I am using android and volley to get the image and then sending it to the php to upload.
I am using wamp as well.
Says "successfully uploaded" but is not in the directory?
PHP CODE:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$username = $_POST['username'];
require_once('dbConnect.php');
$sql ="SELECT profilepictureID FROM tbl_userprofilepictures ORDER BY profilepictureID ASC";
$res = mysqli_query($con,$sql);
$profilepictureID = 0;
while($row = mysqli_fetch_array($res)){
$profilepictureID = $row['profilepictureID'];
}
$path = "000001/$profilepictureID.JPG";
$actualpath = "http://*wamp server ip*/Users/Images/$path";
$sql = "INSERT INTO tbl_userprofilepictures(username,profilepicturepath) VALUES ('$username','$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
} else{
echo "Error";
}
?>
So I think I'll never get an answer lol ...
Old Question, please read the EDIT
I am trying to display a picture after uploading it to a mysql database.
But by trying to open the picture firefox shows the following warning:
the image cannot be displayed because it contains errors
I already had been searching google because of it for hours now but I really can't find a fix for this issue. So now you guys are my very last hope :)
Here is the php:
<?php
session_start();
$con = mysql_connect("localhost", "...", "...");
mysql_select_db('...',$con);
$id = $_GET['id'];
$result = mysql_query("SELECT image, mime FROM artikel WHERE id='$id'");
$row = mysql_fetch_object($result);
header("Content-type: $row->mime");
echo $row->image;
?>
EDIT
I think the mistake is in the insert.php..
Could someone please have a look at it and tell mewhat might be wrong? Thank you :) (I think the image is not uploaded correct)
<?php
session_start();
header('content-type: text/html; charset=utf-8');
$uname = $_POST['username'];
$typ = $_POST['typ'];
$titel = $_POST['titel'];
$content = $_POST['content'];
$timestamp = time();
$db = new mysqli("localhost", "...", "...", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
// Verweis auf Bild
$image = $_FILES['image']['tmp_name'];
// Vorbereiten für den Upload in DB
$data = addslashes(file_get_contents($image));
// Metadaten auslesen
$meta = getimagesize($image);
$mime = $meta['mime'];
}
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mime`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//bind the username and message
$stmt->bind_param('sssssss', $uname, $typ, $titel, $content, $data, $mime, $timestamp);
//run the query to insert the row
$stmt->execute();
header("Location: erfolg.php");
?>
I followed the instruction from here. I inserted the image with additional mime field and checked the code is working.
Confirm whether you have your mime types correct. If yes, then possibly the image might be corrupted.
having simply
header("Content-type: ");
also worked for me.
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_object($result);
/*Only for testing purpose.*/
// echo $row->mime; //This line should output image/jpeg
/*Only for testing purpose*/
/*Only to check output*/
header("Content-type: $row->mime");
echo $row->image;
/*Only to check output*/
Try this. Check whether you are getting values inserted. If inserted and still getting error, post pics of database compared to my earlier post.
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mime`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//run the query to insert the row
$stmt->execute(array($uname, $typ, $titel, $content, $data, $mime, $timestamp));
header("Location: erfolg.php");
I have an image submission form that just uses a simple action="" to get to a PHP page that adds the submission details to the DB and creates a unique page for the submission. That works fine. However, I want it to redirect to their submission page (created with fwrite()) How would I do this? Code below.
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_GET['right_form_title'];
$filename = $_GET['right_form_url'];
$submitter = $username;
$type = exif_imagetype($_GET['right_form_url']);
list($width, $height) = getimagesize($filename);
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
$php_file_name = $name.".php";
$path_for_link = $submissions_path.$php_file_name;
$tpl = file_get_contents($tpl_path.$tpl_file);
$tpl_and_values = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl_and_values);
fclose($fh);
?>
Adding this after you close the file would work just fine.
header('location: '.$submissions_path.$php_file_name);
I believe all you need to do is stick a header at the bottom of that file which will redirect to the newly created file. Try adding this at the bottom of your file.
header('Location: '.$submissions_path.$php_file_name);