Retrieve uploaded filepath of latest added file in php - php

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.

Related

How to validate multiple uploaded file using php?

I am using PHP to upload multiple file to the database. So when I check file extension its always showing me my given error message even if file extension is correct:
File type is not allowed, We accept only .jpg, .png and .gif extension
file
Here is the validation :
$total = count($_FILES['client_doc']['name']);
for($i=0; $i<$total; $i++) {
$file_name = htmlspecialchars($_FILES['client_doc']['name'][$i]);
$file_tmp = htmlspecialchars($_FILES['client_doc']['tmp_name'][$i]);
$file_size = htmlspecialchars($_FILES['client_doc']['size'][$i]);
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed_type = array('jpg', 'jpeg', 'gif', 'png');
}
if(!empty($file_name)) {
if(!in_array($file_ext, $allowed_type)) {
$msg[] = 'File type is not allowed, We accept only .jpg, .png and .gif extension file';
$msg['error'] = true;
}elseif($file_size > 2097152) { // only 2 mb size is allowed
$msg[] = 'Uploaded file name must be less than 2MB';
$msg['error'] = true;
}
}
I've tested your code by giving the $file_name variable test.png value and it works fine. Are you sure your file form works correctly? Try to echo $file_name's at the end of for loop and check if there's any output.
Another tips:
Do you want to validate all the files? As far as I'm concerned your current code validates only the last file - you iterate through all the files, but you overwrite variables storing file's data. In order to validate all the elements you have to put your condition inside the for loop.
Because your $allowed_type is a constant, you don't have to overwrite it inside the loop.

PHP upload multiple files code assistance

I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}

How to make auto updating image gallery?

Well I have a upload script. What I need is how would I go about making it auto upload to a page on my site where it can be displayed as an image gallery?
Code:
<?php
// Configuration - Your Options
$allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); // These will be the types of file that will pass the validation.
$max_filesize = 1000000; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './images/uploaded_images/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if ( ! in_array($ext, $allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if ( ! is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if (move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
Any Ideas?
One approach would be to scan the directory you are storing the images and write html for each file you encounter. Take a look at the scandir function. Some rudimentary code to get you started:
$upload_path = './images/uploaded_images/';
$files = scandir($upload_path);
foreach($files as $filename) {
if(is_image($filename)) {
echo "<div class='gallery-image'><img src='{$filename}'/></div>";
}
}
function is_image($filename) {
$image_extensions = array('jpg', 'jpeg', 'png', 'gif');
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return in_array($ext, $image_extensions);
}

Saving Uploaded File Path in MySQL with PHP

I am trying to upload a file, and save the path to MySQL.
I want to make a custom path for each file, which will be based on a variable, however the actual file name of the file will stay the same.
I am submitting the file via POST. I believe I have to use $_FILE? The name of the form item is "file".
How would I go about doing this? Note: I DO NOT want to store the actual file on the database, just the path.
EDIT: I also want to save the actual file to a path, too.
Take a look at this page: http://www.php.net/manual/en/features.file-upload.post-method.php There is an example of moving an uploaded file to some folder.
So yes the relevant information is stored in $_FILE
First create appvars.php like something below
<?php
// Define application constants
define('GW_UPLOADPATH', 'foldername/');
define('GW_MAXFILESIZE', 32768); // 32 KB
?>
then create the code to save the file like something like this
<?php
require_once('appvars.php');
$file = mysqli_real_escape_string($dbc, trim($_FILES['file']['name']));
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
//do some checks to make sure the person upload the file type you like
if ((($file_type == filetype) // check for the size also
&& ($file_size > 0) && ($file_size <= GW_MAXFILESIZE)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = GW_UPLOADPATH . $file;
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
// Write the data to the database
mysqli_connect( database info);
$query = "INSERT INTO table (file ) VALUES ($file)";
mysqli_query($dbc, $query);
}
}
}
mysqli_close($dbc);
?>

Why this php file upload validation script not working?

Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.

Categories