i need to save in a folder on server pdfs and in a db the relative url.
but with the code that i show you below i get the error in php:"please choose a file"...i don't know why.
I show you my code:
REST CLIENT SIDE:
enter image description here
SERVER SIDE:
<?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://'.$server_ip.'/AndroidImageUpload/'.$upload_path;
$upload_url = 'http://'.$server_ip.'/azz/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
//connecting to the database
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');
//getting name from the request
$nome = $_POST['nome_pdf'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['nome_pdf']);
//getting the file extension
$extension = $fileinfo['extension'];
$id = $_POST['id'];
//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['pdf']['tmp_name'],$file_path);
$sql = "INSERT INTO `my_db`.`pdfss` (`id_pdf`, `nome_pdf`, `url_pdf`,`id_user`) VALUES (NULL, '$nome','$file_url', '$id');";
//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;
$response['nome_pdf'] = $nome;
$response['url_pdf'] = $file_url;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
//displaying the response
echo json_encode($response);
}
I hope that you can help me!
This line
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
Should be
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['tmp_name']) && isset($_POST['id'])){
Or
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['name']) && isset($_POST['id'])){
Your error comes from here
isset($_FILES['pdf']['nome_pdf'])
NOTE: You do not use $_POST when dealing with file uploads in PHP. Use $_FILES. I think you are confused with the name of the file and also the array_keys that are associated with the $_FILES array
nome_pdf is not in the $_FILES array. If you try a dump of var_dump($_FILES['pdf']);, you will see that nome_pdf is not in the array.
Replace the line with:
if( isset($_FILES['pdf']) && $_FILES['pdf']['tmp_name'] != '' && isset($_POST['id'])){
#add your code
else{
$response['error']=true;
$response['message']= 'PDF FILE: '. $_FILES['pdf'].' ID of post: '.$_POST['id'];
exit;
}
echo(json_encode($reponse));
The above change will make sure the tmp_name is not empty.
Also before moving the file, i suggest using mime type to check for the extensions
Related
I currently created a system that allowed a user to upload a photo only. The photo the already upload can be replaced if the user want to change it.
The current code shows that there's no error in this function. The URL updated at MySQL database. But the problem is the image doesn't update. Below is my current code:
update_photo_before.php
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
if ($sql){
move_uploaded_file($_FILES['uploadFile']['name'], $imgPath); //line 28
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}else{
echo "Error!! Not Saved";
}
} else {
echo "<script>alert('File not allowed')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
?>
My folder images are located at 'tgotworker_testing' --> 'android' --> 'images'.
For update_photo_before.php:
'tgotworker_testing' --> 'pages' --> 'dashboard' --> 'engineer' --> 'view_task' --> 'update_photo_before.php'
Can anyone fix my problem? Thanks!
You check to see if the database gets updated, but not if the image is saved to the server.
move_uploaded_file() returns true on success and false on failure. So you can do a similar test as you have for $sql in your code.
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
// Check if image is uploaded to folder
if(move_uploaded_file($_FILES['uploadFile']['name'], $imgPath) === true) {
// If upload succeeds, then update database
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Check if database updated
if (!$sql){
echo "Error!! Database not updated.";
} else {
// Success!
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
} else {
// Could not upload file
echo "Error!! Could not upload file to server.";
}
}
When PHP can't upload the file it will throw a warning. If you turn on your warnings while you are debugging, it should give you the reason why it's not working and you will be better able to solve the problem.
Put these lines at the top of the script to show all warnings and errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
i have the following code in android
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(getContext(), uploadId, url_upload_cert)
.addFileToUpload(path, "pdf") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
and in php
<?php
//importing dbDetails file
require_once __DIR__ . '/db_connect.php';
//this is our upload folder
$upload_path = 'android/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
//$upload_url = 'http://'.$server_ip.'/pavo_project/'.$upload_path;
$upload_url='/src';
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['name']) and isset($_FILES['jpg']['name'])){
// connecting to db
$db = new DB_CONNECT();
//getting name from the request
$name = $_POST['name'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['jpg']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . $name . '.' . $extension;
//file path to upload in the server
$file_path = $upload_url . $name . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['jpg']['tmp_name'],$file_path);
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//closing the connection
// mysqli_close($db);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
//displaying the response
echo json_encode($response);
}
?>
when i run the android code it runs succesfully with no error but when i check the image in the src folder its not there
The same things happens when i test the script using postman
Am using wamp server on windows .
what might be the reason causing this?
Check the writing permissions of your folder.
For example in Linux, a level above your folder you can user the following command:
sudo chmod -R 777 <your-folder-name>
And that might let the php code save the file inside of it, because it will grant the permissions to write/read/delete to every user.
Also you can check the php.ini file, and check if the line:
file_uploads = On
Has the On value
If that doesn't work you can check for a default php.ini file and try replacing your php.ini file with that.
I'm trying to upload the file's path into my database. But nothing is being inserted. My file gets uploaded to target directory successfully. I want to insert the path too, but can't do it. I believe I'm doing some mistake in the Insert Into statement. Please let me know what's wrong?
My upload.php code is below:
<?php
// variables
$conn = mysqli_connect('localhost','root','abcdef','trademark');
if(!$conn) {
echo "Not Connected To Server";
}
else {
define('UPLOAD_DIR', 'uploads/');
$fileName = $_FILES['file'];
// check for which action should be taken if file already exist
//Rename file name
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo"FILE SUCCESSFULLY UPLOADED!! " . "<br/><br/><br/>"; //after renaming
}
// If no such file already exists, then upload it as it is
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo " FILE SUCCESSFULLY UPLOADED!! ". "<br/><br/>";
}
// function to rename file
function update_file_name($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = trim($arr[(count($arr) - 1)],$ext);
$exist = FALSE;
$i = 2;
while(!$exist)
{
$file = $dr.$fName.'_'.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
} // function to rename ends
$sql = "INSERT INTO file (Path) VALUES (' " . mysqli_real_escape_string( UPLOAD_DIR.$fileName['name']) . " ')";
$r = mysqli_query($conn,$sql);
echo 'file info inserted';
}
?>
Check syntax for function mysqli_real_escape_string
getting warning message as,
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name']) ){
//connecting to the database
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');
$resume_name = $_POST['exp'];
$employee_id = $_POST['employee_id'];
$file_data = $_FILES['pdf']['name'];
$upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_path . getFileName($employee_id). '.'. $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName($employee_id);
try{
if(file_exists($upload_path))
{
$existing_file = glob($upload_path."/*.*");
$empty_file = implode(" ",$existing_file);
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
else
{
mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql))
{
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
}
}
//here is my method getFileName
function getFileName($employee_id)
{
//mysql query to fetch data
$sql = mysql_query("SELECT resume_path from employee_registration where
employee_id = '$employee_id'") or die(mysql_error());
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$response=$row['resume_path'];
}
$resume_name = explode("/", $response);
echo $resume_name[4];
return $resume_name;
}
Change below line:
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
To
move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);
I'm using backbonejs for my project. My question is, how to perform CRUD operation in amazon S3? so far I can upload/create files into bucket and retrieve files but I dont know how to do update and delete files.
config.php
<?php
//Bucket Name
$bucket_name ="my_bucket";
//include the S3 class
if (!class_exists('S3'))require_once('S3.php');
//AWS access informations
if (!defined('awsAccessKey')) define('awsAccessKey', 'access_key');
if (!defined('awsSecretKey')) define('awsSecretKey', 'secret_key');
//instantiate the s3 class
$s3 = new S3(awsAccessKey, awsSecretKey);
//this is used to create a bucket in amazon S3
$s3->putBucket($bucket_name, S3::ACL_PUBLIC_READ);
?>
upload_image.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
if(isset($_POST) && !empty($_FILES) && !empty($_FILES['uploadfile']['name']) && isset($_POST['productId'])) {
//upload file formats
$valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$filename = $_FILES['uploadfile']['name'];
$tmp_filename = $_FILES['uploadfile']['tmp_name'];
$filetype = strtolower($_FILES['uploadfile']['type']);
//get file extenstion to verify the format
$extension = get_file_extension($filename);
if(in_array($extension,$valid_file_formats)){
//include config.php
include_once "config.php";
//set content type in headers inorder to display image in browser
$header = array('Content-Type' => $filetype);
//change filename
$new_file_name = "w3_".time().".".$extension;
if($s3->putObject(S3::inputFile($tmp_filename), $bucket_name , $new_file_name, S3::ACL_PUBLIC_READ, array(), $header) ){
$img = "http://".$bucket_name.".s3.amazonaws.com/".$new_file_name;
// array for JSON response
$response = array();
// check for required fields
$productId = $_POST['productId'];
$imageLink = $img;
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO tbl_images(productId, imageLink,dateCreated) VALUES('$productId', '$imageLink',NOW())");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Image successfully uploaded.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
echo "1-".$img;
} else {
echo "2-Upload Failed";
}
} else {
echo "3-Not a Valid Format";
}
} else {
echo "4-Please Select a File";
}
?>
Thanks a lot in advance.
Have a look at the php sdk
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html
There is commands there for deleteMatching to remove items from a bucket.
As for update, call putObject again to overwrite the file.