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
Related
On desktop, the upload works correctly, but when I try to upload from a mobile device, it says that the extension is outside the array, and print returns octet-stream, any thoughts? I can't see what could be wrong. I have tried many audio extensions, checked MIME and tested with a few smartphones, no success.
if (isset($_POST['submit_atrack'])) {
$fileinfo=PATHINFO($_FILES["audio"]["name"]);
$newFilename=$fileinfo['filename'] . uniqid($usr_idLogged) . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["audio"]["tmp_name"],"atracks/" . $newFilename);
$location = 'atracks/' . $newFilename;
$formatos = array('audio/mpeg', 'audio/ogg', 'audio/mp3', 'audio/*', 'audio/wav');
$tamanho_max = 500000000; //500 mb
if (empty($_FILES['audio']['name']))
{
$upload_empty = urlencode("empty");
header("Location:playlist?newtrack=".$upload_empty . "&playlist=" . $selectedPlaylist);
exit;
}
else if (!in_array($_FILES['audio']['type'], $formatos))
{
$upload_incorrectformat = urlencode("incorrectext");
header("Location:playlist?newtrack=".$upload_incorrectformat . "&playlist=" . $selectedPlaylist);
exit;
}
else if (in_array($_FILES['audio']['type'], $formatos))
{
if($_FILES['audio']['size'] >= $tamanho_max)
{
$upload_maxsize = urlencode("maxsizereached");
header("Location:playlist?newtrack=".$upload_maxsize . "&playlist=" . $selectedPlaylist);
exit;
}
else
{
$atitle = mysqli_real_escape_string($connection, $_POST['atitle']);
$atag = mysqli_real_escape_string($connection, $_POST['atag']);
$atagcolor = mysqli_real_escape_string($connection, $_POST['atagcolor']);
mysqli_query($connection,"INSERT INTO tbl_users_atrack (atrack_title, atrack_path, atrack_tag, atrack_tagColor, atrack_playlistId) VALUES ('$atitle', '$location', '$atag', '$atagcolor', '$selectedPlaylist')");
$upload_success = urlencode("success");
header("Location:playlist?newtrack=" . $upload_success . "&playlist=" . $selectedPlaylist);
exit;
}
}
}
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;
}
My Requirement is as follows:
When user uploads a file i should check for "File already Exists", if file exists i must show confirm box if 'OK' i have to replace and if cancel the reverse.
This is my following code
if (file_exists($path . $documentName)) {
$msg = $documentName . " already exists. ";
?>
<script type="text/javascript">
var res = confirm('File already exists Do you want to replace?');
if (res == false) {
<?php
$msg = 'File Upload cancelled';
?>
} else {
<?php
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " File Replaced Successfully";
$successURL = $document_path . $documentName;
}
else
$msg = $documentName . "Upload Failed";
?>
}
</script>";
<?
}
My problem is even if i give cancel the file is getting replaced.
just let me know where I'm wrong or Is there any other approach?
Please help me to close this issue
Note:jquery Not allowed.
Your problem is that you mix javascript and PHP. The PHP-Code will be run on the server and generates the HTML-document. At this point, the file gets replaced already.
Then, this document (with the javascript-code inside) will then be send to the user and there the javascript-code is run. And in that moment, the user gets to see the confirmaion-dialog, even though the file already was replaced!
Take a look at the source-code that your php-code is generating and you will see what I mean.
A solution would be to add a checkbox to confirm overwriting files. Then after hitting the upload-/submit-button, your php-script would check if this box was checked and either replace the file or not.
#Gogul, honestly, this is not the right way to go. Better that you handle the file submission with an AJAX request which receives a response back from your server (either uploaded successfully, or file exists) which you handle appropriately. If presenting the user an option to replace the file, again handle that action with AJAX.
You can do AJAX request in raw JavaScript (jQuery not required) - see here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You are mixing server side code with client side javascript. The solving of your problem is more complicated if you don't want the user to reupload the document:
Store the file in a temporary location under random filename. Output a yes/no form to the user, including the random filename and original filename.
If the user answers yes, move from temporary location to $path, else remove the file from temporary location.
Guys i came with with this following solution
upload
uploaddocument.php
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_FILES["document"]["name"]);
if (file_exists($path . $documentName)) {
move_uploaded_file($_FILES["document"]["tmp_name"], "F:\\Content\\enews_files\\temp\\" . $documentName);
$msg = $documentName . " already exists. <a href='confirm.php?confirm=1&filename=" . $documentName . "&language=" . $lang . "'>Replace</a>||<a href='confirm.php?confirm=0&filename=" . $documentName . "'>Cancel</a>";
} else {
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " Upload Success";
$successURL = $document_path . $lang . '/' . $documentName;
}
else
$msg = $documentName . " Upload Failed";
}
confirm.php
include("config_enews.php");
$lang = $_GET['language'];
$path = "F:\\Content\\enews_files\\" . $lang . "\\";
//$path = "D:\\test\\test\\" . $lang . "\\";
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_GET["filename"]);
if ($_GET['confirm'] == 1) {
//echo sys_get_temp_dir();die;
if (copy("F:\\Content\\enews_files\\temp\\" . $_GET["filename"], $path . $documentName)) {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=success&fname=$documentName&lang=$lang");
} else {
echo $res = move_uploaded_file($_GET["tempname"], $path . $documentName);
echo $msg = $documentName . " Upload Failed";
header("Location: uploaddocument.php?message=failed&fname=$documentName");
}
} else {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=cancelled&fname=$documentName");
}
I got this spark from #Marek. If any one has better solution kindly provide.
I don't have enough reputations to vote your answers sorry.
Thank you so much for all your support.
I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.
Code:
$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
It keep return fail. The sample.docx does reside on that particular path. Kindly advise.
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual
error to unlink file. To delete file you must to change the file's owner.
An example:
chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($tempDirectory . '/' . $fileName);
So try something like this:
$path = './doc/stuffs/sample.docx';
chown($path, 666);
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
EDIT 1
Try to use this in the path:
$path = '.'
. DIRECTORY_SEPARATOR . 'doc'
. DIRECTORY_SEPARATOR . 'stuffs'
. DIRECTORY_SEPARATOR . 'sample.docx';
Try this:
$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file does not exist";
}
If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.
This should work once you are done with the permission issue. Also try
ini_set('display_errors', 'On');
That will tell you whats wrong
define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$path = "doc/stuffs/sample.docx";
if (unlink(ROOT_PATH . $Path)) {
echo "success";
} else {
echo "fail";
}
// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx
You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.
I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)