This baffles me. For some weird reason, move_uploaded_file() doesn't put the file into the directory, yet it returns a valid tmp_name and name. So in this case $file always = to false.
Anyway, can anyone point some problems with this code? It would be greatly appreciated.
<?php
include 'realtydevkit.php';
session_start();
$name = $_FILES['yourlogo']['name'];
$tmpname = $_FILES['yourlogo']['tmp_name'];
if ($name) {
$directory = $name;
$userid = $_SESSION['userid'];
$type = "logo";
$file = move_uploaded_file($tmpname, $directory);
if ($file == true) {
mysql_query("INSERT INTO usercontent
(`userid`, `type`, `url`) VALUES
('$userid', '$type', '$directory')");
echo 'Uploaded';
echo "<img src='".$directory."'/>";
} else {
echo 'There was an error moving the file.';
}
}
?>
You're not checking $_FILES['yourlogo']['error'], either.
Here is what you check with an uploaded file:
Check $_FILES['yourlogo']['error']. If it is UPLOAD_ERR_OK (0), then proceed.
Check is_uploaded_file($_FILES['yourlogo']['tmp_name']). If this fails, PHP doesn't know what went wrong, but it doesn't trust the file.
Assemble the destination path.
Use move_uploaded_file().
If move_uploaded_file() errors, then PHP can't write the file at the destination. This is usually an invalid path or it doesn't have permissions.
Note that $_FILES['yourlogo']['name'] is the name the file had on the uploader's PC. It shouldn't have any path information.
<?php
include 'realtydevkit.php';
session_start();
$name = $_FILES['yourlogo']['name'];
$tmpname = $_FILES['yourlogo']['tmp_name'];
if ($name) {
$directory = $name;
$userid = $_SESSION['userid'];
$type = "logo";
$file = move_uploaded_file($tmpname, "path of ur directore/".$directory);
if ($file == true) {
mysql_query("INSERT INTO usercontent
(`userid`, `type`, `url`) VALUES
('$userid', '$type', '$directory')");
echo 'Uploaded';
echo "<img src='".$directory."'/>";
}
else
{
echo 'There was an error moving the file.';
}
}
?>
Related
I've tried to add image upload to an already working script that posts a subject and description. For some reason it's failing at the point where I'm using move_uploaded_file
The file name is successfully inserting into the database and the print_r statement is showing that the file is going into /tmp. I've tried to echo and print the $tempname and $folder but they seem to be blank and I don't know why. I'm guessing this is the problem.
My php.ini and httpd.conf and permissions are all good as another upload script written by someone else works fine.
if(isset($_POST['submit']))
{
$date = date('Y-m-d H:i:s');
$subject = $_POST['subject'];
$description = $_POST['description'];
$upload_dir = './image';
$filename = $_FILES["choosefile"]["name"];
$tempname = $_FILES["choosefile"]["temp_name"];
move_uploaded_file($tempname, "$upload_dir/$filename");
$insert = mysqli_query($db,"INSERT INTO xv.post (subject, description, creation_date, image) VALUES ('$subject', '$description', '$date', '$filename')");
if(!$insert)
{
echo mysqli_error();
}
else
{
print "<p>Here is some more debugging info:</p>";
print_r($_FILES);
echo $tempname . $folder;
}
}
It should be tmp_name instead of temp_name.
So changing to below should do the trick:
$upload_dir = './image';
$filename = $_FILES["choosefile"]["name"];
$tempname = $_FILES["choosefile"]["tmp_name"];
move_uploaded_file($tempname, "$upload_dir/$filename");
$insert = mysqli_query($db,"INSERT INTO xv.post (subject, description, creation_date, image) VALUES ('$subject', '$description', '$date', '$filename')");
please add a print_r to the $_FILES to see the content:
print_r($_FILES);
Provably there is another structure that you have to get.
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'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 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
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);