I am working on a script that uploads a file, calls a php script via ajax that uploads it to a folder on the server. This part is working correctly. The next step is to then take this file and insert it into a database (I know its not best practise but I have to due to exising db/software constraints) but I cant seem to get this to work at all.
I'll leave out the ajax as that is working correctly, here's the PHP:
$upload_dir = "./uploads";
$result["status"] = "200";
$result["message"] = "ERROR!";
if (isset($_FILES['file']))
{
echo "Uploading File...<br />";
if ($_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$filename = $_FILES['file']['name'];
$destination = 'uploads/' . $filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
//THIS IS THE SECTION THAT DOESN'T WORK CORRECTLY. IT JUST DOES NOTHING AT ALL
//upload the image as a blob
$image = file_get_contents ($destination);
//see if there is anything already stored in blob
$sqlcheck = "select id from blobstore where id='$custid'";
$result = sasql_query($connect, "$sqlcheck");
if (!isset($row['id']))
{
$sql = "update blobstore set class='j', id='$custid', blob='".sasql_real_escape_string($connect,$image)."', createdby='$userid', createdat='". date_format($date, 'Y-m-d H:i')."' where id='$custid' ";
$insert = sasql_query($connect, "$sql");
}
else if (isset($row['id']))
{
$sql = "insert into blobstore (class, id, blob, createdby, createdat) VALUES ('j','$custid', '".sasql_real_escape_string($connect,$image)."','$userid', '". date_format($date, 'Y-m-d H:i')."') ";
$insert = sasql_query($connect, "$sql");
}
//WHEN I INCLUDE THE ABOVE SECTION TO UPLOAD THE IMAGE TO THE DB THIS ALSO RETURNS NOTHING, WHEREAS IF I TAKE OUT THAT SECTION IT RETURNS AS EXPECTED
$result["status"] = "100";
$result["message"] = "File was uploaded successfully!";
}
}
elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
{
$result["status"] = "200";
$result["message"] = "The file is too big.";
}
else
{
$result["status"] = "500";
$result["message"] = "Unknown error.";
}
When I run this I am getting the error
Warning: Cannot use a scalar value
This error goes when I remove the following code
$result["status"] = "100";
$result["message"] = "File was uploaded successfully!";
Any help would be much appreciated.
Thanks
Related
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
I followed this link to upload image from android to server. But the upload is failed on PHP part, so I added some echo to keep track on which one triggered the error. And I found that even though I already set an image to upload (I use Postman), the error of 'Please choose a file' is triggered.
<?php
//importing dbDetails file
require_once('dbDetails.php');
//this is our upload folder
$upload_path = 'uploads/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://xxx/xxx/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
echo "method OK";
//checking the required parameters from the request
if(isset($_POST['name']) && isset($_FILES['image']['name'])){
echo "isset ok";
//connecting to the database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//getting name from the request
$name = $_POST['name'];
//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 uploads (id, fileUpload, name) VALUES (NULL, '$file_url', '$name');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
//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{
echo "isset error";
$response['error']=true;
$response['message']='Please choose a file';
}
}
function getFileName(){
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
$sql = "SELECT max(id) as id FROM uploads";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['id']==null)
return 1;
else
return ++$result['id'];
}
?>
Screenshot from Postman
Please guide me what did I missed?
it returns content uploaded successfully but no image is displayed. what can i do to fix this problem or move uploaded file stream not found. how can i do this correctly. please help.thanks
MY code;
<?php include('includes/connect.php'); ?>
<?php include('includes/function.php'); ?>
<?php
if($_POST['add']){
$h1 = trim($_POST['heading']);
$t1 = trim($_POST['text']);
$sql = "INSERT INTO home ( heading,text)VALUES('{$h1}', '{$t1}')" ;
//die(print($sql));
$result = mysql_query($sql);
confirm_query($result);
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
}
if($valid_file)
{
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
}
}
else
{
//set that to be the returned message
$msg = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
header("Location:home_add.php?msg=$msg");
exit;
}
}
//die(printf($sql));
if($result){
$msg="Content uploaded Successfully!";
//$_SESSION['loggein_msg'] = 'Content updated Successfully!';
header("Location:home_add.php?msg=$msg");
exit;
}else{
$msg= "Content upload failed!";
header("Location:home_add.php?msg=$msg");
}
}
?>
?>
it returns content uploaded successfully but no image is displayed
First make sure your form has enctype='multipart/form-data'
<form enctype='multipart/form-data' ..... >
And then
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$_FILES['photo']['name']);
Make sure the form upload field has the same name is photo
move_uploaded_file 2nd parameter should be a proper path to the image, you shouldn't use tmp_name for the same. Hence, replace this line :
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
to :
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$_FILES['photo']['name']);
to keep the original file name in server, else change the file name as per your requirement with same extension.
Change this.
$new_file_name = strtolower($_FILES['photo']['tmp_name']);
To this.
$new_file_name = strtolower($_FILES['photo']['name']);
It's Done.
Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer
I am trying to upload an image to the server (with a path in mysql table) twice through php with different names. One version of the image as "xxxx.png" and the other version of the image as "xxxxt.png".
My php is:
<?php
if ($_FILES['photo']) {
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
} else {
echo "Error uploading new image - please check the format and size";
}
}
?>
The above code inserts the image into the mysql database and uploads the file to the server correctly.
I am however trying to upload the same image twice with a different naming convention on a "thumbnail" version. The slideshow script in my html only recognises the thumbnails if there are named with a "t" at the end of the filenames hence my problem.
I have been advised to look at the php copy() function to achieve this but am incredibly unclear as to how to incorporate such a function into my existing code.
Happy to provide the html or any other info if required.
Any help much appreciated. I did have another thread attempting to find out the same thing but I wasn't very clear!
Thanks
JD
If I correctly understand you, you do not need to upload this file twice. You already have this file on your server. So you should copy it (optionally do some transitions to make it more like a thumbnail) on your server's hard drive and update database.
Your code should like similar to this:
<?php
if($_FILES['photo'])
{
$target_dir = "images/properties/";
$upload_file_name = basename( $_FILES['photo']['name']);
$upload_file_ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . $upload_file_name . '.' . $upload_file_ext;
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.' . $upload_file_ext);
$target_thumb = $target_dir . $upload_file_name . 't.' . $upload_file_ext;
$target_thumb_sql = $target_dir . mysql_real_escape_string($upload_file_name . 't.' . $upload_file_ext);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_file_sql' )");
echo "The new image has been added successfully";
if (copy($target_file, $target_thumb))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_thumb_sql' )");
echo "The new thumb image has been added successfully";
} else
{
echo "Error copying thumb file";
}
} else
{
echo "Error uploading new image - please check the format and size";
}
}
Again, the idea is that you do not need to upload file twice in a row. All you need to do is just copy it on server.
As you've been advised you should use copy(). I didn't fully test this but give it a try:
<?php
if ($_FILES['photo'])
{
$target = "images/properties/";
$ext = array_pop(explode('.', $_FILES['photo']['name']));
$copy = $target . basename($_FILES['photo']['name'], '.' . $ext) . 't.' . $ext;
$target = $target . basename($_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
copy($target, $copy);
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
}
else
{
echo "Error uploading new image - please check the format and size";
}
}
?>