I have included an upload script, which currently ONLY checks the upload folder to make sure that the file isn't there, which works just fine. However, I would like to somehow silently include a search function to see if it is already in one of the other directories.
The process: User uploads a prl, it checks upload folder if its there. This works. I need it to check another directory (recursively) to see if it is in any subdirectory already, and then list them out.
Just a note: $carrier is an existing subdirectory. I would like it to check the parent directory and all of its subs for the filename minus the extension, and if it exists, Error: this file already exists for "this" carrier.
<?php
$allowedExts = array("prl");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$carrier = $_POST['carrier'];
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
if (file_exists("./prls/" . $carrier . "/" . $_FILES["file"]["name"])){
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " is already listed in the " . $carrier . " directory. ";
echo "<hr><br />If you feel this PRL is listed incorrectly, please let us know.";
die;
}
if (file_exists("upload/" . $_FILES["file"]["name"] . "-" .$carrier)) {
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " for <b>" . $carrier . "</b> has already beeb submitted for approval. ";
die;
}
if ($_FILES["file"]["error"] == 0 && in_array($extension, $allowedExts))
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"] . "-" . $carrier);
echo "<h2><u>Submitted for approval:</u></h2>";
echo $_FILES["file"]["name"] . " for " . $carrier . ". <b>Thank you</b>.";
}
else
{
echo "Invalid file. Please choose a PRL with a \".prl\" extension.";
}
?>
You want to use RecursiveIteratorIterator. Here's a function that will behave like file_exists():
function file_exists_recursive($dir, $filename) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );
foreach($iterator as $path) {
if (!$path->isDir()) {
if(file_exists($filename.$path->__toString()))
return true;
}
return false;
}
}
Then call this function in your file:
if (file_exists_recursive("upload/", $_FILES["file"]["name"] . "-" .$carrier)) {
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " for <b>" . $carrier . "</b> has already beeb submitted for approval. ";
die;
}
Related
I am not sure what is wrong here but I know it has to do with move_uploaded_file. I have tried changing the name that the file gets changed to and I have changed the chmod of the directory to 777. From what I can tell there is no reason why the file isn't getting moved, but it isn't.
Here is the code in question. Keep in mind this is part of a Wordpress plugin, so I use functions from there in my code.
if ( isset($_FILES["file"])) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"];
die;
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
die;
} elseif(strtolower(end(explode('.', $_FILES['file']['name']))) != "csv") {
echo "File is not a .csv";
die;
} else {
if(move_uploaded_file($_FILES["file"]["tmp_name"], plugin_dir_path( __FILE__ ) . "uploads/uploaded_file.csv")) {
echo "Stored in: " . plugin_dir_path( __FILE__ ) . "upload/uploaded_file.csv<br />";
} else {
echo "Temp file was not moved.<br />";
echo '<pre>';
echo 'Here is some more debugging info:<br />';
print_r($_FILES);
print "</pre>";
}
}
}
echo '<form method="post" action="" enctype="multipart/form-data">';
echo '<input type="file" name="file" id="file" />';
submit_button('Import CSV');
echo '</form>';
In the same situation i used: $name = basename($_FILES["file"]["name"]); before calling move_uploaded_file(), i'm not saying it's the solution but maybe you are repeating the path.
Hope it helps.
So I have a problem I want to upload a file to php but I also want to POST a key as well, you see my PHP code requires a key or "k" via POST to allow a file to be uploaded or the user will be redirected.
PHP:
<?php
error_reporting(0);
ini_set('display_errors', 0);
header("Content-Type: text/text");
$key = "Place Key Here";
$uploadhost = "http://example.com/i/index.php";
$redirect = "http://example.com/index.php";
if (isset($_POST['k'])) {
if ($_POST['k'] == $key) {
$target = getcwd() . "/" . basename($_FILES['d']['name']);
if (move_uploaded_file($_FILES['d']['tmp_name'], $target)) {
$md5 = md5_file(getcwd() . "/" . basename($_FILES['d']['name']));
rename(getcwd() . "/" . basename($_FILES['d']['name']), getcwd() . "/" . $md5 . "." . end(explode(".", $_FILES["d"]["name"])));
echo $uploadhost . $md5 . "." . end(explode(".", $_FILES["d"]["name"]));
} else {
echo "Sorry, there was a problem uploading your file.";
}
} else {
header('Location: '.$redirect);
}
} else {
header('Location: '.$redirect);
}
?>
I have looked around for a solution but all examples are for just uploading via
My.Computer.Network.UploadFile(Label1.Text, "http://example.com/i/index.php")
I have tried to POST the Key then Upload the file with the code above but no ball.
There is probably a far easier way to this that I maybe over thinking/looking.
Kind Regards,
Nimesh Patel
I have a script in php that is used to upload files to a server. It was working first but i dont know why its not working again. It shows no error but the file is not still uploaded to the directory that i assigned to hold all uploaded files. Here is the part that takes care of the upload:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Uploaded: " . basename($_FILES["file"]["name"]) . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
//by default the size of the file is in bytes so u need to divide by 1024 in order to bring it to KB
echo "Temporarily stored in: " . $_FILES["file"]["tmp_name"] . "<br />";
$target="/file/" . basename($_FILES["file"]["name"]) . "<br />";
}
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target))
{
echo "<h2>" . "The file has been stored on the server" . "<br />" . "<h2 />";
echo "New storage location is : " . '<a href="/public/files/" >' . $target . '</a>';
?>
<html>
<body>
<div align="right"><a href="/public/files/" >Uploaded files</a></div>
<br />
</body>
</html>
<?php
}
else
{
echo "<h2>" . "Error while saving the file to the server." . "<br />" . "File wont be found in the uploaded files directory" . "<br />" . "<h2 />";
echo "The error says: " . $_FILE["file"]["error"] . " What do we do now?" ;
echo"<pre>".print_r($_FILES,true)."</pre>";
?>
<?
/file/ is a directory in the root of your server's filesystem, which almost certainly doesn't exist. move_uploaded_file() works at the filesystem level and has absolutely NO awareness of your site's URI structure. You probably want something more like:
move_uploaded_file(...,. $_SERVER['DOCUMENT_ROOT'] . '/file/');
^^^^^^^^^^^^^^^^^^^^^^^^^^^---- add this
so that the file gets moved to a /file subdir of your site's root directory.
SOLUTION: How to Save Uploaded File's Name on Database
this ended up helping me.
i am trying to add a file upload to a custom component using XML and database.
I know how to get file upload done in a static PHP environment but my knowledge
about the PHP MVC structure in joomla makes it so I am unable to add it.
What I have done so far:
• Added the field in the XML file (of the type file)
• Added the form fields in admin view project
• Added an extra field My_project table(same as the image upload column)
Until this point it works.(fields are shown in admin backend component)
Now when you save the document with a file uploaded in the admin back end it does not save it to the database.
if i put media as field type then it works, but when i change it to file it breaks down.
XML file
<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset>
<field name="project_file" type="file"
label="Upload file"
description="Upload file"
directory="mysites" />
<field name="main_image" type="media"
label="COM_MYSITES_FORM_LBL_PROJECT_MAIN_IMAGE"
description="COM_MYSITES_FORM_DESC_PROJECT_MAIN_IMAGE"
filter="raw"
directory="mysites" />
</fieldset>
PHP file upload script i normaly use
<?php
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
but what part goes in the model and what part goes in the controller?
and how to call it.
entire view is called in the controller
class MysitesControllerProject extends JControllerForm {
function __construct() {
$this->view_list = 'projects';
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['project_file'];
$this->upload($file);
parent::__construct();
}
public function upload($files)
{
$file_name = $files['name'];
$src = $files['tmp_name'];
$size = $files['size'];
$upload_error = $files['error'];
$type = $files['type'];
$dest = "/home/vol3/byethost33.com/b33_13467508/bim-portfolio.cu.cc/htdocs/tmp";
if (isset( $file_name)) {
// Move the uploaded file.
JFile::upload( $src, $filepath );
}
}
}
Placing new field in database and XML form is only half of work. You also have to write file save/upload functionality. There are two places you can do it. In controller (for example save task procedure) or model (there are 2-3 functions where you can do it). Look into this file /administrator/components/com_media/controllers/upload.php (upload procedure). I would just extend your save function so before data will be saved into database file will be stored on file system. You can find original save function declaration in /libraries/legacy/controller/legacy.php (for Joomla 3.0.1, for other versions it shouldn't be hard to find)
Here is sample save function:
public function save($key = null, $urlVar = null){
// youre file upload code
return parent::save($key = null, $urlVar = null)
}
<?php
$file= $_FILES["file"]["name"];//file selected in form
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],
"c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"];
if(($_FILES['file']['size'] >0))
{echo 'imagetrue';$con=mysql_connect('localhost','abc','YES') or die ("con");;
$db=mysql_select_db("website",$con) or die ("db");
$query=mysql_query("insert into website.picture (imagew) values ('$file')") or die('query'); //storing in db}
//echo $_FILES['file']['error'] ;
$query2= mysql_query("select * from website.picture");
$res=mysql_fetch_array($query2);
foreach($res as $row){
$str = "c:/EasyPHP-12.1/www/new website/upload/ ".$row['imagew'];
echo '<img src="'.$str.'" alt="no">' ;}
?>
i am using this script to store image and then displaying it on webpage but it is not working it only displays empty thumbnails...
I'd be very suspect about using absolute paths like c:/EasyPHP-12.1/www/new website/upload/
I'f you're then accessing the page from http://127.0.0.1/new-website (which I presume you are - or something similar) then having windows system pathnames could be a problem - do browsers even read the local filesystem like that ?
Also, it makes it very un-portable for when you move it to another server.
I'd suggest $str = 'upload/'.$row['imagew']; So it's relative to the document hosted in (I presume) 127.0.0.1/new website/image-viewer.php (or whatever you called it)
Check the return value of move_uploaded_file() - if it's false then it has failed. If that's failing try using the relative path :
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
This again presumes your script is sitting in 127.0.0.1/new-website
EDIT - NOTE ::: Is your form using enctype="multipart/form-data" ? If it's not then the images never get to the server !