I have a php script that uploads a profile picture to the server and then edits a field in the DB.
At the top of the script, I've added a line of code that will create a new folder in a directory, that's labeled by the user's id. The ID is echoed with $id. This works for the folder, but when I set the upload path to something like ../img/users/$id, it uploads to ..img/users instead.
CODE:
<?php
require '../login_check.php';
include_once 'db_connect.php';
$dir = "../img/users/$id";
if( is_dir($dir) === false )
{
mkdir($dir);
}
fclose($file);
$dir = "./users/$result[id]";
if( is_dir($dir) === false );
$path_to_image_directory = "../img/users/$id";
if(isset($_FILES['imgupload']))
{
$id = $_SESSION['id'];
if ($_FILES["imgupload"]["size"] > 500000)
{
header('Location: ../profile');
}
if(preg_match('/[.](jpg)|(JPG)|(gif)|(GIF)|(PNG)|(png)$/',
$_FILES['imgupload']['name']))
{
$source = $_FILES['imgupload']['tmp_name'];
$randString = md5(time());
$filename = $_FILES['imgupload']['name'];
$splitName = explode(".", $filename);
$fileExt = end($splitName);
$newfilename = strtolower($randString.'.'.$fileExt);
$target = $path_to_image_directory . $newfilename;
move_uploaded_file($source, $target);
$updatestmt = $conn->prepare("UPDATE members SET profilepic= ? WHERE id = ?");
$updatestmt->bind_param("si", $newfilename, $id);
$updatestmt->execute();
header('Location: ../profile');
}
else
{
header('Location: ../profile');
}
}
?>
Can anyone tell me what I did wrong and how to fix this?
You are using $id variable before assigning $_SESSION['id'] value to it.
First you have to assign the value to $id
$id = $_SESSION['id'];
Then use this $id to setting directory path variable.
$path_to_image_directory = "../img/users/$id";
Make sure your $_SESSION['id'] is not empty/null
Move $id = $_SESSION['id']; to below include_once 'db_connect.php';
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've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;
thank you in advance for your help, i need to make a system were i can upload and update a file into my database record. To do so i made this code but for some reason i cant seem to see what i have done wrong i can update the "status and so on" but the file is not uploaded into my desired directory and the record is missing in my database too, so all the rest works just fine, except the file itself, does not get updated. Here is my code, again thanks in advance!
<?php
if(isset($_POST['submit_btn']))
{
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
require 'modules/conn.php';
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
}
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id ='".$_POST['id']."', status ='".$_POST['status']."', counts ='".$_POST['counts']."', Filename ='".$_POST['Filename']."' WHERE id = '".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
?>
Everything else gets updated in my database, but as i said, the file and the record of the file name does not, also its not uploaded into my directory. Please help me, an example would be very much appreciated.
Updated code i can get the records into the database but still no upload into the directory.
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
if(isset($_POST['submit_btn']))
{
move_uploaded_file($_FILES['Filename']['tmp_name'], $target);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status = '$status', counts = $counts , Filename = '$Filename' WHERE id = '$id'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
This last solution is correct i hope i can contribute also to other members, see solution credits bellow at the correct reply to my post, that guy rocks! Thumbs up so what was the error? Simple, the path i had was wrong...
this one is wrong:
$target = "../account-files/";
This is correct and fixes all
$target = "account-files/";
Do you really have the POST['Filename']? I think you should put the variables in you query instead of .POST
Try the code below:
if(isset($_POST['submit_btn']))
{
$target_dir = "../account-files/";
$target_file = $target_dir . basename( $_FILES['Filename']['name']);
move_uploaded_file($_FILES['Filename']['tmp_name'], $target_file);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status =
'$status', counts = $counts , Filename = '$Filename' WHERE id =
'".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
And also please make sure that you have the enctype="multipart/form-data" on your form tag.
You make some mistakes:
how you can upload the file first and then determine the target
why are you updating id? while id is its primary key
i
if(isset($_POST['submit_btn'])){
$target = "../account-files/";
$fname = $_FILES['filename']['name'];
if(!empty($target) && !empty($fname)){
move_uploaded_file($_FILES['filename']['tmp_name'], $target.$fname);
}
}
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
I am trying to add a URL to a image file name before uploading it to database. It seems that nothing worked out. Have searched Google and Stackoverflow. I guess I am missing something. Here's my code, please find the comment 'here is the issue'
I have a variable $value which pulls latest ID from database.
All I have to achieve is add path to the variable: "http://example.com/location/something/"
Desired Output : the image should be renamed as http://example.com/location/something/1.jpg
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$title = $_POST['title'];
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$folder="uploads/";
function execute_scalar($sql,$def="") {
$rs = mysql_query($sql) or die("bad query");
if (mysql_num_rows($rs)) {
$r = mysql_fetch_row($rs);
mysql_free_result($rs);
return $r[0];
mysql_free_result($rs);
}
return $def;
}
$value = execute_scalar("select max(ID)+1 from tablename");
$newname = "$value.".$ext; // Here is the issue.
$newname = "http://example.com/location/something/"."$value.".$ext; //did not work
$newname = "http://example.com/location/something/ $value.".$ext; //did not work
// even tried assingning url to variable still did not worked
if(move_uploaded_file($file_loc,$folder.$newname))
{
$sql="INSERT INTO tablename(id,title,image)VALUES('$value','$title','$newname')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
is it something with URL?
Try moving your quotes like below:
$newname = "http://example.com/location/something/". $value ."." . $ext;
The problem is that you are not allowed to use / (slash) in your file name, because it acts as directory path.
I found a solution :
$newname = "http:\\//www.example.com\/location\/something\/\/$value.".$ext;
It is working :D