oci_excute error when try to upload file php - php

This code should upload a blob file image to oracle database. While I try to use the following code, the variable $objExecute produces an error!
Please help to fix this.
$error= $_FILES['Image_assigned']['error'];
$objConnect = oci_connect("jab","jabee","j-windows7/XE");
$lob = oci_new_descriptor($objConnect, OCI_D_LOB);
$strSQL ="insert into SS_USERS_PIC (SYSUID,PICTURE) values (F_SS_GET_AUTO_ID('SYSUID','PICTURE') , EMPTY_BLOB()) RETURNING ImageFile INTO :BLOBDATA " .")";
// $strSQL='insert into mybtab (blobid, blobdata) values (:myblobid, EMPTY_BLOB()) returning blobdata into :blobdata';
$objParse = oci_parse($objConnect, $strSQL);
oci_bind_by_name($objParse, ':BLOBDATA', $lob, -1, OCI_B_BLOB);
$objExecute = oci_execute($objParse, OCI_DEFAULT);
$lob->savefile($_FILES['Image_assigned']['tmp_name']);
$errorCode= $_FILES['Image_assigned']['error'];
if ($objExecute)
{
oci_commit($objConnect);
echo "Copy/Upload Complete<br>";
}
else
{
oci_rollback($objConnect);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
echo "Copy/Upload is not Complete";
}

function upload($operation){
if(!empty($_FILES['Image_assigned']['name']) && !($_FILES['Image_assigned']['error']))
{
$uploadedFile = '';
if(!empty($_FILES["Image_assigned"]["type"]))
{
$fileName = time().'_'.$_FILES['Image_assigned']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["Image_assigned"]["name"]);
$file_extension = end($temporary);
$blobdata = file_get_contents($_FILES['Image_assigned']['tmp_name']);
if((($_FILES["hard_file"]["type"] == "image/png") || ($_FILES["Image_assigned"]["type"] == "image/jpg") || ($_FILES["Image_assigned"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions))
{
$sourcePath = $_FILES['Image_assigned']['tmp_name'];
$targetPath = "uploads/".$fileName;
}
}
$objConnect = oci_connect("[username]","[password]","[hostname]/[instnce_name]");
$lob = oci_new_descriptor($objConnect, OCI_D_LOB);
if ($operation=='ADD'){
$strSQL ="insert into [TableName] (PICTURE) values ( EMPTY_BLOB()) RETURNING PICTURE INTO :BLOBDATA ";
$objParse = oci_parse($objConnect, $strSQL);
}
// *************************************
oci_bind_by_name($objParse, ':BLOBDATA', $lob, -1, OCI_B_BLOB);
try
{
$objExecute = oci_execute($objParse, OCI_DEFAULT);
$lob->savefile($_FILES['Image_assigned']['tmp_name']);
}
catch (Exception $e) {
$err = $e->getMessage();
}
if($objExecute)
{
oci_commit($objConnect);
echo "Copy/Upload Complete<br>";
}
else
{
oci_rollback($objConnect);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
echo "Copy/Upload is not Complete";
}
oci_free_descriptor($lob);
oci_free_statement($objParse);
oci_close($objConnect);
}
}

Related

How to update mysqli field if the value is not empty

I am trying to update a specific value from my table getting them as row from a table let's say the name but the problem is the image, cause i can't pass a value to an input field type = file
I need to update the value in the database only if there is a value to change if not don't change the value that already is there.
My query looks like this and i would like to know what i can change to update image value only if there is a value
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}else{
$conn = get_connection();
$sql = "INSERT INTO `accommodation` (`name`, `image`, `description`, `adress`, `link`) VALUES ('{$_POST['name']}', '$new_file_name', '{$_POST['description']}', '{$_POST['adress']}', '{$_POST['link']}')";
mysqli_query($conn, $sql);
$accommodation_id = mysqli_insert_id($conn);
header("Location: admin.php?page=room_add_edit");
}//end if else
This is the query that i need to change but i don't know how....
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
I am aware of SQL injection but first i need this query to work then i will work on SQL injection, and i typed address as adress and i have to change that too.
I have changed the code to this but i don't know if it's a good way to do it
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$text1 = "`image` = '$new_file_name',";
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}else {
$text1 = "";
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', $text1 `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}
you can simply check the file uploaded or not using a third variable. If file uploaded than save new file name otherwise save the old file name. So you will not lose your file on update. I am assuming you are getting whole row data in $row so check below code
$is_file_uploaded = 0;
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$is_file_uploaded = 1;
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
if(is_array($row)) {
$new_file_name = ($is_file_uploaded == 1) ? $new_file_name : $row['image'];
//your code
}
}
You can try this:
$new_file_name = "";
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
if($new_file_name != ""){
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}else{
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}

PHP- file uploading working on localhost but not in server (linux)

Upload file not working on server but it is working on localhost. File upload permission is ON, but even getting error. I tried all the solution over internet.
Here is my code.
if($submit == "UPLOAD PROFILE PICTURE") {
$user = $_COOKIE['userId'];
$file_name = $_FILES['userPic']['name'];
$file_size =$_FILES['userPic']['size'];
$file_tmp =$_FILES['userPic']['tmp_name'];
$file_type=$_FILES['userPic']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png");
$nameToStore = $user.".".$file_ext;
chmod("images/users-dp/$nameToStore",0777);
if(in_array($file_ext,$expensions)=== true){
if($file_size < 2097152){
if(move_uploaded_file($file_tmp,"images/users-dp/".$nameToStore)) {
$queryFoCheck = "SELECT * FROM profilepic WHERE user = '$user'";
$resultFoCheck = $connection -> query($queryFoCheck);
$countFoCheck = mysqli_num_rows($resultFoCheck);
if($countFoCheck>=1) {
$query = "UPDATE profilepic SET piclink = '$nameToStore' WHERE user = '$user'";
$result = $connection -> query($query);
} else {
$query = "INSERT INTO profilepic VALUES ('$user', '$nameToStore') ";
$result = $connection -> query($query);
}
header('Location: profile.php?s'); //successsfully updated
} else {
header('Location: profile.php?e=1'); //Cant update
}
} else {
header('Location: profile.php?e=2'); //Cant update
}
} else {
header('Location: profile.php?e=3'); //Cant update
}
}

Unable to store pic link into database

I am trying to upload my pic into folder and file link store into database although file store in folder but unfortunately doesn't store link in database. Please see where I am doing mistake.
<?php
include('dbconnection.php');
if(count($_FILES["file"]["name"]) > 0)
{
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $connect))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $file_name);
$stmt->execute();
}
}
}
function file_already_uploaded($file_name, $connect)
{
$statement = $connect->prepare("SELECT image_name FROM tbl_image WHERE image_name = '".$file_name."'");
$statement->execute();
$number_of_rows = $statement->rowCount();
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
store the image name as location with file name:
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $location.'/'.$file_name);
$stmt->execute();
}

PHP No such file or directory error

Warning: move_uploaded_file(C:\mpp\htdocs\ch09\data2018_03_22_11_38_23_0.gif): failed to open stream: No such file or directory in C:\xampp\htdocs\ch09\concert\insert.php on line 101
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpE1D0.tmp' to 'C:\mpp\htdocs\ch09\data2018_03_22_11_38_23_0.gif' in C:\xampp\htdocs\ch09\concert\insert.php on line 101
$upload_dir = "C:\xampp\htdocs\ch09\data";
I think file_name is set correctly, but uploaded_dir isn't.
\xa is missed, despite being typed correctly. Why?
<?php session_start(); ?>
<meta charset="utf-8">
<?php
$userid = $_SESSION["userid"];
if(isset($_REQUEST["page"]))
{
$page = $_REQUEST["page"];
}else{
$page = 1;
}
if(!$userid) {
echo("
<script>
window.alert('로그인 후 이용해 주세요.')
history.go(-1)
</script>
");
exit;
}
if(isset($_REQUEST["mode"])){
$mode = $_REQUEST["mode"];
}else{
$mode ="";
}
if(isset($_REQUEST["num"])){
$num = $_REQUEST["num"];
}else{
$num = "";
}
if(isset($_REQUEST["html_ok"])) //checkbox는 체크해야 변수명 전달됨
$html_ok = $_REQUEST["html_ok"];
else
$html_ok = "";
$subject = $_REQUEST["subject"];
$content = $_REQUEST["content"];
// 다중 파일 업로드
$files = $_FILES["upfile"];
$count = count($files["name"]);
$upload_dir = "C:\xampp\htdocs\ch09\data\\";
$regist_day = date("Y-m-d (H:i)"); // 현재의 '년-월-일-시-분'을 저장
/* 단일 파일 업로드
$upfile_name = $_FILES["upfile"]["name"];
$upfile_tmp_name = $_FILES["upfile"]["tmp_name"];
$upfile_type = $_FILES["upfile"]["type"];
$upfile_size = $_FILES["upfile"]["size"];
$upfile_error = $_FILES["upfile"]["error"];
*/
for ($i=0; $i<$count; $i++)
{
$upfile_name[$i] = $files["name"][$i];
$upfile_tmp_name[$i] = $files["tmp_name"][$i];
$upfile_type[$i] = $files["type"][$i];
$upfile_size[$i] = $files["size"][$i];
$upfile_error[$i] = $files["error"][$i];
$file = explode(".", $upfile_name[$i]);
$file_name = $file[0];
$file_ext = $file[1];
if (!$upfile_error[$i])
{
$new_file_name = date("Y_m_d_H_i_s");
$new_file_name = $new_file_name."_".$i;
$copied_file_name[$i] = $new_file_name.".".$file_ext;
$uploaded_file[$i] = $upload_dir.$copied_file_name[$i];
if( $upfile_size[$i] > 500000 ) {
echo("
<script>
alert('업로드 파일 크기가 지정된 용량(500KB)을 초과합니다!<br>파일 크기를 체크해주세요! ');
history.go(-1)
</script>
");
exit;
}
if ( ($upfile_type[$i] != "image/gif") &&
($upfile_type[$i] != "image/jpeg")
)
{
echo("
<script>
alert('JPG와 GIF 이미지 파일만 업로드 가능합니다!');
history.go(-1)
</script>
");
exit;
}
if (!move_uploaded_file($upfile_tmp_name[$i], $uploaded_file[$i]))
{
print $upfile_tmp_name[$i];
print $uploaded_file[$i];
echo("
<script>
alert('파일을 지정한 디렉토리에 복사하는데 실패했습니다.$upfile_tmp_name[$i] AANNDD $uploaded_file[$i]');
history.go(-1)
</script>
");
exit;
}
}
}
include_once ''; "../lib/dbconn.php"; // dconn.php 파일을 불러옴
$pdo = db_connect();
if ($mode=="modify")
{
$num_checked = count($_POST['del_file']);
$position = $_POST['del_file'];
for($i=0; $i<$num_checked; $i++) // delete checked item
{
$index = $position[$i];
$del_ok[$index] = "y";
}
try{
$sql = "select * from phptest.concert where num=?"; // get target record
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->execute();
$row = $stmh->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $ex) {
print "오류: ".$ex->getMessage();
}
for ($i=0; $i<$count; $i++) // update DB with the value of file input box
{
$field_org_name = "file_name_".$i;
$field_real_name = "file_copied_".$i;
$org_name_value = $upfile_name[$i];
$org_real_value = $copied_file_name[$i];
if ($del_ok[$i] == "y")
{
$delete_field = "file_copied_".$i;
$delete_name = $row[$delete_field];
$delete_path = "./data/".$delete_name;
unlink($delete_path);
try{
$sql = "update phptest.concert set $field_org_name = ?, $field_real_name = ? where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $org_name_value, PDO::PARAM_STR);
$stmh->bindValue(2, $org_real_value, PDO::PARAM_STR);
$stmh->bindValue(3, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
}
else
{
if (!$upfile_error[$i])
{
try{
$pdo->beginTransaction();
$sql = "update phptest.concert set $field_org_name = ?, $field_real_name = ?, where num = ?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $org_name_value, PDO::PARAM_STR);
$stmh->bindValue(2, $org_real_value, PDO::PARAM_STR);
$stmh->bindValue(3, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
print "오류: ".$ex->getMessage();
}
}
}
}
try{
$pdo->beginTransaction();
$sql = "update phptest.concert set subject=?, content=?, is_html=? where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $subject, PDO::PARAM_STR);
$stmh->bindValue(2, $content, PDO::PARAM_STR);
$stmh->bindValue(3, $html_ok, PDO::PARAM_STR);
$stmh->bindValue(4, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
} //기존내용을 수정하는 경우..
else //신규 추가하는 경우.
{
if ($html_ok=="y")
{
$is_html = "y";
}
else
{
$is_html = "";
$content = htmlspecialchars($content);
}
try{
$pdo->beginTransaction();
$sql = "insert into phptest.concert(id, name, nick, subject, content, regist_day, hit, is_html, ";
$sql .= " file_name_0, file_name_1, file_name_2, file_copied_0, file_copied_1, file_copied_2) ";
$sql .= "values(?,?,?,?,?,now(),0,?,?,?,?,?,?,?)";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $_SESSION["userid"],PDO::PARAM_STR);
$stmh->bindValue(2, $_SESSION["name"],PDO::PARAM_STR);
$stmh->bindValue(3, $_SESSION["nick"],PDO::PARAM_STR);
$stmh->bindValue(4, $subject, PDO::PARAM_STR);
$stmh->bindValue(5, $content,PDO::PARAM_STR);
$stmh->bindValue(6, $is_html,PDO::PARAM_STR);
$stmh->bindValue(7, $upfile_name[0],PDO::PARAM_STR);
$stmh->bindValue(8, $upfile_name[1],PDO::PARAM_STR);
$stmh->bindValue(9, $upfile_name[2],PDO::PARAM_STR);
$stmh->bindValue(10, $copied_file_name[0],PDO::PARAM_STR);
$stmh->bindValue(11, $copied_file_name[1],PDO::PARAM_STR);
$stmh->bindValue(12, $copied_file_name[2],PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
}
echo "
<script>
location.href = 'list.php?page=$page';
</script>
";
?>
$upload_dir = "C:\xampp\htdocs\ch09\data\";
you missed a backslash.

Unexpected result after file upload

This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.

Categories