I have a form where a user fills out multiple input fields and they can also upload an image. I recently added another input field where the user can upload an additional image.
<label for="photo">Facility Roof Plan:</label>
<input type="file" id="facilityroofplan" name="facilityroofplan" />
When the user submits my form it should upload this image, as well as store a directory path into a db. The information is being saved into my db properly without any issues, however when I check to see if the image was uploaded it is not there.
$directoryPath = "../images/" . $selectedAssocAccount . "/" . $facilityID;
//create the directory
mkdir($directoryPath, 0775);
//facility roof plan
if(!empty($_FILES["facilityroofplan"]["name"])){
//directory path for the facility photo to reside in
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
} else{
echo "Error uploading facility image.";
}
//insert into photo table
$photoQuery = "INSERT INTO facility_roof_plan (facility_id, roof_plan) VALUES ('$facilityID', '$facilityRoofPlan')";
mysqli_query($dbc, $photoQuery)or die(mysqli_error($dbc));
}
And this is what my save_facility_roof_plan function looks like:
function save_facility_roof_plan($from, $to, $status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading a photo.";
return false;
}
I have done this in several other places and I have no issues uploading any images.
where am I going wrong here?
In your code, you have the line
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
But there is no variable $facilityPhoto anywhere in what you posted. My guess is that should be changed to $facilityRoofPlan since you set that path but never use it.
Then the $saved variable is never checked for errors which might have shown you why it isn't working.
Try:
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityRoofPlan, $status_msg);
if (!$saved) {
echo "Error saving roof plan image: {$status_msg}";
}
} else{
echo "Error uploading facility image.";
}
Related
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
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
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']);
My system features a conversation area which writes to and draws from a .txt file. I am obviously able to set the permissions through my FTP client but I'm looking to apply the writable functionailty to all files that are uploaded through my system within the PHP. I'll add that security is not an issue.
<?php
$adminID = $_GET['adminID'];
$name = stripslashes(trim($_POST['name']));
$area = stripslashes(trim($_POST['area']));
mysql_query("INSERT INTO chat_rooms (id, name, area, adminID) VALUES ('', '$name', '$area', '$adminID')");
$image = ($_FILES['image_url']['name']);
$empty = '';
if ($image == $empty)
{
echo 'NO IMAGE';
}else
{
$target = "room/test/";
$target = $target .basename($_FILES['image_url']['name']);
$target2 = basename($_FILES['image_url']['name']);
$image_url = ($_FILES['image_url']['name']);
$adminarea = 'admin-index.php';
mysql_query("UPDATE chat_rooms set file='$image_url' WHERE name = '$name'");
if(move_uploaded_file($_FILES['image_url']['tmp_name'], $target))
{
echo "";
echo "Your room has been created using the file " . basename( $_FILES['image_url']['name']) ." <br /> <br /> Click here to return to the admin area";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
I apologise for the layout and general syntax of my code
Just call chmod('thefile.txt', 0777) on the file after it has been uploaded.
http://php.net/manual/en/function.chmod.php
chmod:
chmod('/path/to/file.txt', 0777);
hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here