Upload images as BLOBs in Oracle using PHP - php

Can anyone please tell me how to store images in an oracle database as BLOBs using PHP?
A working example would be nice. Thankyou.

You first need to get the image that is being uploaded from the $_FILES #global array:
$image = file_get_contents($_FILES['image_field_name']['tmp_name']);
Then to insert the image in the database try this:
$sql = "INSERT INTO table (id, image) VALUES(1, empty_blob()) RETURNING image INTO :image";
$result = oci_parse($connection, $sql);
$blob = oci_new_descriptor($connection, OCI_D_LOB);
oci_bind_by_name($result, ":image", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_DEFAULT) or die ("Unable to execute query");
if(!$blob->save($image)) {
oci_rollback($connection);
}
else {
oci_commit($connection);
}
oci_free_statement($result);
$blob->free();

Thank you DRiFTy, I build my small JSON query on your example.
Let's clarrify that you can save large images with both examples.
<?php
// Database parameters
$oci_user = 'YOUR_DB_USER';
$oci_pw = 'YOUR_DB_PASSWORD';
$oci_db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 000.000.000.000)(PORT = 1521)))(CONNECT_DATA=(SID=XXX)))";
// Get data from JSON imput
$data = json_decode(file_get_contents("php://input"),true);
// Now you can do some checks on date etc.
$img = $data['IMAGE'];
$jfid = $data['OBJECT_ID'];
$jfdate = $data['DATE'];
// Let's beginn with the blob upload
// We have 3 fiels in our table: OBJECT_ID,DATE,BLOBIMAGE
// First you fill your BLOB with an 'Empty' one and assign in PL/SQL style :img
$sql = "INSERT INTO ZAEHLER.METERAPP_BILD (OBJECT_ID,DATE,BLOBIMAGE)
VALUES (".$jfid.",to_date('".$jfdate."','DD/MM/YYYY'),empty_blob())
RETURNING BLOBIMAGE INTO :img";
$result = oci_parse($conn, $sql);
$blob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($result, ":img", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_NO_AUTO_COMMIT);
// Now let's check if we could connect to database or if we have to output something => 500
if(!$result){
$err = oci_error();
header('HTTP/1.0 500 Internal Server Error');
header('Content-Type: application/json');
$out = array('code' => '500', 'response' => '500 Internal Server Error / SQL connection problem', 'error sql' => $err[message]);
echo json_encode($out);
}
// Can we same the image ($img) or not => 406
// This step saves the image to the db
if(!$blob->save($img)) {
oci_rollback($conn);
header('HTTP/1.0 406 Not Acceptable');
header('Content-Type: application/json');
$out = array('code' => '406', 'response' => '406 Not Acceptable / Wrong image type or JSON error');
echo json_encode($out);
}
// If both was ok, we're going to commit and output an OK => 200
else {
oci_commit($conn);
header('HTTP/1.0 200 OK');
header('Content-Type: application/json');
$out = array('code' => '200', 'response' => '200 OK', 'response advanced' => 'Image saved', 'object_id' => $jfid, 'file date' => $jfdate);
echo json_encode($out);
}
// Clean up
oci_free_statement($result);
$blob->free();
?>

You can use PDO too:
<?php
include '../conexao_oracle.php';
$db = $pdo;
$db->beginTransaction(); // Essential!
$mimetype = 'image/jpeg';
$funcionario_id = 10;
$stmt = $db->prepare(
"INSERT INTO foto (mimetype, binario, funcionario_id) ".
"VALUES (:mimetype, EMPTY_BLOB(), :funcionario_id) ".
"RETURNING binario INTO :binario");
$stmt->bindParam(':mimetype', $mimetype);
$stmt->bindParam(':binario', $blob, PDO::PARAM_LOB);
$stmt->bindParam(':funcionario_id', $funcionario_id);
$blob = fopen('fotos/10.jpg', 'rb');
$stmt->execute();
$pdo->commit();

Related

php do not fetch new data from database after adding item

I working on a very simple form project, I send items using ajax and save them on the database using PHP insert query, then by clicking a button I fetch data using ajax from another PHP file using SELECT query, the problem is when I want to get new data the PHP query doesn't update data and it returns old data if I check the file whit out using ajax and I put the URL like mysite.com/getdata.php it still returns old data and I have to refresh this page until it fetches new data, I don't have any error or warning in my javascript code or PHP and I have no idea why it doesn't get new data whit new request and I have to refresh the URL till fetches new data.
It worked correctly local I see this bug when I upload my code to the server
My getdata.php file code:
<?php
$servername = "localhost";
$username = "projectform";
$password = "jtq*o2ZL7qBPt_HS";
$dbname = "projectform";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
$responseData = json_encode(array(
"status" => $status,
"message" => "Connection failed: " . $conn->connect_error,
"data" => null,
));
die($responseData);
}
$sql = "SELECT * FROM form_data";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$data[] = array(
'id' => $row["id"],
'Title' => $row["title"],
'address' => $row["address"],
'photo' => $row["p_date"],
'phone' => $row["phone"],
'detail' => $row["detail"],
'create' => $row["created_at"],
'status' => $row["status"],
);
}
$status = "success";
$message = "";
$response = $data;
} else {
$data = null;
$status = "error";
$message = "NO data found.";
}
$conn->close();
$responseData = json_encode(array(
"status" => $status,
"message" => $message,
"data" => $response,
));
die($responseData);
If you are using pure PHP, you can try to disable browser cache like this:
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: close");

Ckeditor Image Upload - Incorrect Server Repsonse

I'm having a problem uploading images. CKEditor keeps throwing an "Incorrect server response" error when using the drag and drop Upload Image addon.
I've added the following lines to my ckeditor config.js file:
config.extraPlugins = 'uploadimage';
config.imageUploadUrl = './scripts/ckImageUpload.php';
config.extraPlugins = 'image2';
And my ckImageUpload.php script is:
con = dbConnect();
$id = $_GET['edit'];
$time = new DateTime;
$fileName = $time->format(DateTime::ATOM).pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
$url = './images/uploaded/'.$fileName;
if(move_uploaded_file($_FILES['upload']['tmp_name'], $url)) {
$data = ['uploaded' => 1, 'fileName' => $filename, 'url' => $url];
$query = 'INSERT INTO postImages (
parentID,url
) VALUES (
"'.$id.'",
"'.$url.'"
)';
if(!mysqli_query($con, $query)){
$error = 'Insert query failed';
$data = array('uploaded' => 0, 'error' => array('message' => $error));
}
} else {
$error = 'There was an error uploading the file';
$data = array('uploaded' => 0, 'error' => array('message' => $error));
}
echo json_encode($data);
If I fake it and remove everything except the following lines, and place an image called image.jpg in the correct location the error goes away and the image appears within the editor as it should:
$data = ['uploaded' => 1, 'fileName' => 'image.jpg', 'url' => './images/uploaded/image.jpg'];
echo json_encode($data);
Instead of trusting the std. json_encode, sending an actual JSON response works.
Changing that simple
echo json_encode($data);
into:
return new Symfony\Component\HttpFoundation\JsonResponse($data);
will get this working.

How to recieve a Multipart request in PHP

We have API which receives images converted in base64 string. Our mobile application consumes too much RAM during the conversion process (to base64), now we need to upload image as multipart. I developed the mobile part but I'm stuck with the PHP API. We switched from volley to Retrofit because volley did not support multipart upload.
What do I need to change in the script that receives the multipart image upload?
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'images/' . $image_name;
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if ($is_written > 0) {
$connection = mysqli_connect('localhost', 'root', '', 'test');
if ($connection) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
echo json_encode(array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
));
} else {
echo json_encode(array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
));
}
mysqli_close($connection);
} else {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
}
}
} else {
echo json_encode(array(
"response" => "Error! Please insert data!",
"result" => "error"
));
}
?>
Have a look at move_uploaded_file() function of php and the $_FILES array.
Example code plenty on this site.
If you want add multipart upload in backend you should make next changes:
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$connection = mysqli_connect('localhost', 'root', '', 'test');
if (!$connection) {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
die;
}
$responses = array();
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$image_name = $_FILES["pictures"]["name"][$key];
$path = 'images/' . $image_name;
if (move_uploaded_file($tmp_name, path)) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
$responses[] = array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
);
} else {
$responses[] = array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
);
}
}
} else {
$responses[] = array(
"response" => "Error! Please insert data!",
"result" => "error"
);
}
}
mysqli_close($connection);
echo json_encode(array(
'responses' => $responses
));
}
Also, make shore you use post request with multipart format (it should have header Content-Type: multipart/form-data and bi in right format - https://ru.wikipedia.org/wiki/Multipart/form-data). Hope it help you.

web service database connection

I have developed a php web service on a server with mysql database connection. It can not connect to database and does not execute codes after database connection. Also it does not show any error.
If I return something before database connection line, it is returned.
I have tested another php file with database connection and it works properly.
<?php require_once('lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('ivrmci', 'urn:ivrmciwsdl');
$server->register('upload_file', // method
array('username' => 'xsd:string','password' => 'xsd:string','encoded_filepath' => 'xsd:string','filename' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmciwsdl', // namespace
'urn:ivrmciwsdl#upload_file', // soapaction
'rpc', // style
'encoded', // use
'Uploads files to the server' // documentation
);
$server->register('inquiryMsisdnCalls', // method
array('username' => 'xsd:string','password' => 'xsd:string','callerid' => 'xsd:string','advertise_id' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmci', // namespace
'urn:ivrmci#inquiryMsisdnCalls', // soapaction
'rpc',
'encoded', // style // use
'Returns User Log' // documentation
);
function upload_file($username,$password,$encoded,$name) {
if ($username != "abc" OR $password != "123")
{
return "-2";
}
$location = "uploads/".$name; // Mention where to upload the file
//$current = file_get_contents($location); // Get the file content. This will create an empty file if the file does not exist
$current = base64_decode($encoded); // Now decode the content which was sent by the client
file_put_contents($location, $current); // Write the decoded content in the file mentioned at particular location
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$filename = explode(".", $name);
$sql = "INSERT INTO advertise (name) VALUES ($filename[0])";
try{
$db->exec($sql);
return $db->lastInsertid();
}
catch(PDOException $e)
{
return $e->getMessage();
}
if($name!="")
{
return "File Uploaded successfully..."; // Output success message
}
else
{
return "Please upload a file...";
}
}
function inquiryMsisdnCalls($username,$password,$callerid,$contentid)
{
if ($username != "abc" OR $password != "123")
{
return "-2";
}
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$sql = "select status from user_advertise_log where callerId=$callerid and advertise_id=$contentid";
try{
$log = $db->query($sql)->fetch(PDO::FETCH_OBJ);
return $log->status;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

How to solve xml load parsing soap payload using nusoap?

I am new in using web service nusoap. When I try to run my program I got an error like this:
XML error parsing SOAP payload on line 1: Not well-formed (invalid
token)
Here is my client.php :
<?php
require_once('lib/nusoap.php');
$data = json_decode(file_get_contents("php://input"), true);
$doc_type = $data['doc_type'];
$transaction_date = $data['transaction_date'];
$file_name = $data['file_name'];
$file_path = $data['file_path'];
//create client instance
$client = new nusoap_client('http://computer_name:2224/WebService/webservice.php?wsdl' , true);
//to check if the request method is POST or not
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//check for error
$err = $client->getError();
if($err){
//Display error
echo '<h2>Constructor error </h2> <pre>' . $err . '</pre>' ;
}
//declare variables
$datas = array(
'doc_type' => $doc_type,
'transaction_date' => $transaction_date,
'file_name' => $file_name,
'file_path' => $file_path
);
//call the function InsertData and pass the parameters being instantiated
$result = $client->call('InsertData', $datas);
if($client->fault){
echo '<h2> Fault (Expect - The request contains an invalid SOAP body) </h2> <pre>';
print_r($result);
echo '</pre>' ;
}else {
$err = $client->getError();
if($err){
echo '<h2> Error </h2><pre>' . $err . '</pre>' ;
}else {
echo '<h2> Result </h2><pre>' ;
print_r($result);
echo '</pre>';
}
}
} else if ($_SERVER['REQUEST_METHOD'] != 'POST'){
echo "Method is not POST";
}
?>
webservice.php
<?php
// require the nusoap.php
require_once ('lib/nusoap.php');
//create new instance
$server = new soap_server();
//initialize WSDL support
$server->configureWSDL('Database Data Insertion', 'urn:Insert');
//character encoding
$server->soap_defencoding = 'utf-8';
// Registering different functions of your Web service
$server->register ('InsertData',
array(
'doc_type' => 'xsd:doc_type',
'transaction_date' =>'xsd:transaction_date',
'file_name' =>'xsd:file_name',
'file_path' =>'xsd:file_path'), //input values
array('return' =>'xsd:string'),
'urn:Insert', // Namespace
'urn:Insertwsdl#InsertData', //SoapAction
'rpc', //style
'literal' // can be encoded but it doesn't work with silverlight
);
// function for inserting data
function InsertData($doc_type,$transaction_date,$file_name,$file_path) {
//set initial values for connection
$db_host = 'localhost' ;
$db_username = 'root' ;
$db_password = '' ;
$db_name = 'sample' ;
//making connection
$conn = new mysqli($db_host, $db_username ,$db_password , $db_name);
//checking if connection is successful
if($conn->connect_error){
trigger_error('Database connection failed : ' .$conn->connect_error , E_USER_ERROR);
}
//inserting data in the edi_doc_type table
$sql = "INSERT INTO transaction_tbl (`transaction_date`,`edi_doc_type_id`,`file_name`,`file_path`,`creation_date`)
VALUES ('$transaction_date',( SELECT edi_doc_type_id FROM `edi_doc_type` WHERE doc_type = $doc_type ),'$file_name','$file_path',NOW()) " ;
//Checking query if it is successful
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
}
$HTTP_RAW_POST_DATA = isset ($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA: '' ;
$server->service($HTTP_RAW_POST_DATA);
?>
Now , when I try to run this I got the above error. so what could be the possible problem? By the way, I can still insert in my database , but the problem is it returns the above error and not all the data in the script can be inserted . When I check my php error logs I have this :
PHP Fatal error: Wrong SQL: INSERT INTO transaction_tbl
(transaction_date,edi_doc_type_id,file_name,file_path,creation_date)
VALUES ('2015-05-28 22:33:00',( SELECT edi_doc_type_id FROM edi_doc_type
WHERE doc_type = 997),'87749-20150528223345027_54423526_54423945.xfa','/home/sample/test/87749-20150528223345027_54423526_54423945.xfa',NOW())
Error: Subquery returns more than 1 row
C:\xampp\htdocs\WebService\webservice.php on line 65
Any help will be appreciated. Thanks :)

Categories