Main issue is image file is not moving from temp location to new location. But it is not giving any error. And all mysql queries are working. Al the html part also working.
$newFileName = $_POST['filename'];
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['temp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode(".",$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg","jpeg","png");
if(in_array($fileActualExt,$allowed)){
if($fileError === 0){
if($fileSize < 20000000){
$imageFullName = $newFileName . "." . uniqid("",true) . "." . $fileActualExt;
$fileDestination = "../gallery/" . $imageFullName;
include_once 'dbh.inc.php';
if(!empty($imageTitle) || !empty($imageDesc)){
$sqlSelect = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$sqlSelect)){
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount+1;
$sqlInsert = "INSERT INTO gallery(title,description,imgfullname,ordergallery) VALUES(?,?,?,?);";
if(mysqli_stmt_prepare($stmt,$sqlInsert)){
mysqli_stmt_bind_param($stmt,"ssss", $imageTitle,$imageDesc,$imageFullName,$setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
}
}
}
}
}
}
Your $imageTitle and $imageDesc variables are empty in this code since they are never given a value. Therefore it will not enter the if statement and move the files.
You've probably been downvoted here because your description of what the code actually does is somewhat vague. You also do not appear to have tested or published a MCVE. Why, for instance, do you SELECT * FROM gallery; when all you use the data for is to display a count (which is irrelevant to the problem you describe).
You're handling of the filename is sensibly done, although ideally the path should be outwith the document root (and subsequent read access mediated by a script).
That "all mysql queries are working" suggests that the execution thread is reaching move_uploaded_file(), we shouldn't be guessing how the code works / what diagnostics you may have run. Each of those "if" statements should have an "else". Each of the mysqli_*() calls should check the return value. You should be checking the return value of move_uploaded_file(). You should also be checking your log file for errors and warnings (after verifying that the logging mechanism is working as expected).
From a cursory glance through the code (I imagine that the relevant POST vars are populated) the next place I would be looking (after the return values and logs) is at the permissions on the target directory.
Related
i have this weird problem never faced it before. the code is working fine when i upload a small file but when i upload larg file (105mb) the query dose not work and gives me this output
MySQL server has gone away - 2006 ../uploads/sermons/2019.03.08-Bro-GK.mp3
$uploadDirectory = "../uploads/sermons/";
require '../includes/config.php'; // this contains the connection ($conn)
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['mp3','wav']; // Get all the file extensions
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
$fileExtension = explode('.',$fileName);
$fileExtension = end($fileExtension);
$fileExtension = strtolower($fileExtension);
$uploadPath = $uploadDirectory . basename($fileName);
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a mp3 or wav file";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
$title = mysqli_real_escape_string($conn,$_POST["Title"]);
$speaker = mysqli_real_escape_string($conn,$_POST["Speaker"]);
$date = mysqli_real_escape_string($conn,$_POST["date"]);
$date = date('Y-m-d', strtotime($date));
$description = mysqli_real_escape_string($conn,$_POST["Description"]);
$query = "Insert into `sermons` (`Title`,`Description`,`Speaker`,`Date`,`Link`) values('$title','$description','$speaker','$date','$uploadPath');";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn)." - ".mysqli_errno($conn)." ".$uploadPath);
It seems like you're running into a read timeout, because the upload takes longer than the script keeps the connection open. Try setting the value of the MYSQLI_OPT_READ_TIMEOUT to something suitable like so mysqli_options($conn, MYSQLI_OPT_READ_TIMEOUT, value_in_seconds);. You'll probably have to setup $conn before actually connecting, in case you run into this bug https://bugs.php.net/bug.php?id=76703
Lets start from the begining. I am a student and have recently had a course in webdevelopement with databases (Im sure the course has different name in english) and I am creating a dynamic website.
You can add, edit and remove sites/articles.
I wanted to be able to upload you own logo on your navbar neside your "tabs" but I have come to a dead end. I followed a guy on youtube that explained how to upload files to my server into a specific folder and limiting it to be only certain file types and a specific filesize.
But now i need to retrieve the filepath of that image so i can display it as a logo on my navbar on the website.
The way i started thinking was that i need to somehow get the latest modified file and then somehow get its location/filepath and then save it to a variable.
The current code i have for uploading an image is this:
its in the root folder and called "upload.php"
<?php
if (isset($_POST['upload'])) {
$file = $_FILES['file'];
/* $_FILES gives you an array of info of an file */
/* below i give each variable some info from my file */
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
/* Ext = extension.*/
/* i only want .jpg and. png files on my site */
/* Here i check if it has .jpg or png at the end of the file name */
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
/* Creating an array with accepted file endings */
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
/* newimages get uniq names inside database */
/* in this case it uses milliseconds */
$fileNameNew = uniqid('', true).".".$fileActualExt;
/* set file destination */
$fileDestination = 'images/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header('Location: index.php?uploadsuccess');
}else {
echo "Your file was to big! Make sure it's less than 1MB!";
}
}else {
echo "There was an error uploading your file! Please try again!";
}
}else {
echo "You cannot Upload files of this type!";
}
}
And then i need to put the filepath into a variable and then add it to:
<img src="images/file_name.jpg>" class="navbar-logo" alt="">
Then replace the file_name.jpg with my variable.
I dont understand how i can achieve this. I dont have the knowledge for it and i hope that turning to stackoverflow i can get some help and learn something new on the way.
I have searched and tried out this code:
(written inside of the "upload.php" file at the bottom, outside of the "if" statement.
/* get latest image name */
$path = "images";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
Maybe i can't access the variable from the file im trying to get it from?
As mentioned, this file ("upload.php") is inside the root folder. Im trying to use the variable $latest_filename in the following place: root/views/master.php
I dont know what more to add, i tried making this as transparent as possible.
I'm having a strange issue with a component I'm working on. The component has a form that includes a file upload. The code checks for duplicate filenames and appends a counter to the end. All of this works perfectly except with I try and modify the record and change the associated file.
I used component creator to build the skeleton at that code works for updates -
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = '/var/www/plm_anz/' . $filename;
$fileTemp = $file['tmp_name'];
if(!JFile::exists($uploadPath)){
if (!JFile::upload($fileTemp, $uploadPath)){
JError::raiseWarning(500, 'Error moving file');
return false;
}
}
$array['ping_location'] = $filename;
When I update the code to remove the MD5 sum and append the counter it all falls apart..
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
$originalFile = $finalFile = $file['name'];
$fileCounter = 1;
//Rename duplicate files
$fileprefix = pathinfo($originalFile, PATHINFO_FILENAME);
$extension = pathinfo($originalFile, PATHINFO_EXTENSION);
while (file_exists( '/var/www/plm_anz/'.$finalFile )){
$finalFile = $fileprefix . '_' . $fileCounter++ . '.' . $extension;
}
$uploadPath = '/var/www/plm_anz/' . $finalFile;
$fileTemp = $file['tmp_name'];
if (!JFile::upload($fileTemp, $uploadPath)){
$fileMessage = "Error moving file - temp file:". $fileTemp . " Upload path ". $uploadPath;
JError::raiseWarning(500, $fileMessage);
return false;
}
I've narrowed down the cause to the filename that the while loop creates but cannot figure out why it only breaks the form update and not the new form submission.
The error I get in Joomla (3.4) is:
Error
Error moving file - temp file:/tmp/phpgwag5r Upload path
/var/www/plm_anz/com_hotcase_6.zip
Save failed with the following error:
I know it's something simple but I've been staring at it too long to see it!
Thanks!
Ok as it is I can not see any good reason why is failing.
The only thing I can suggest you is that JFile::upload is failing go to debug in /libraries/joomla/filesystem/file.php#449 and step by step try to understand what's wrong.
That's actually the file and line of JFile::upload.
In there probably the only line that matter to you is line 502 which is :
if (is_writeable($baseDir) && move_uploaded_file($src, $dest))
Especially try to see what's going on the variable $ret.
I'm studying on MySQL & PHP, and for my first production I've started to work on a review panel. You can simply upload your product reviews to the database and browse them later on, directly from the panel, which in this case is a local website.
The problem is, I can't figure out how to rule over every file format on upload, except .pdf! To be more clear: I only want my upload form to accept .pdf files to be uploaded. At the moment it doesn't restrict anything, here is my code:
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$revName = $_POST['revname'];
$revRating = $_POST['rating'];
$revRecommend = $_POST['recommend'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
rename($tmpName,"C:\\xampp\\htdocs\\ReviewArchieve\\files\\reviews\\".$fileName);
include 'include/config.php';
include 'include/opendb.php';
$query = "INSERT INTO files (revname, rating, recommend, name, size, type, content)".
"VALUES ('$revName', '$revRating', '$revRecommend', '$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
include 'include/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
?>
Got it working!
Thanks to the MIME refer, I managed to learn something new, and accomplished my task with a little bit of investigation! It was not the part of code offered in the correct answer, that did not work at all in my case, no matter what I did, but instead, I used this method:
I noticed I have already included the file type.
$fileType = $_FILES['userfile']['type'];
So now I just had to make an if from it, like this:
if($fileType == 'application/pdf') {
*** Code to be driven here, same as above on the original code ***
}
else {
echo "Invalid file, upload interrupted!";
}
Answer:
....
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
if (mime_content_type($tmpname) != 'application/pdf') {
die("uploaded file not valid");
}
....
You have a number of problems here the biggest are:
SQL Injection. You must sanitize your user inputs or little bobby tables will visit you. Think about using parametrized queries
You should check the file's mimetype.
http://www.php.net//manual/en/function.mime-content-type.php works out the box although is deprecated. You should use fileinfo.
I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.