I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>
Related
I'm having a form that the user can fill in like this:
<form id="regForm" action="" method="POST">
<input type="text" name="name" class="form-control">
<input type="text" name="address" class="form-control">
<input type="text" name="city" class="form-control">
<input type="text" name="country" class="form-control">
<input type="file" name="callflowfile" class="form-control"> // the file
<input type="submit" name="formpost" class="form-control">
</form>
But when I post this form including the file, the file doesn't get uploaded and added to the DB.
This is my PHP code:
if(isset($_POST['formpost'])){
// insert name- address - city - county to DB
// insert callflowfile to directory
// If The array exists, add callflowfile
if ($_FILES["callflowfile"]["name"])
{
//Count number of files in array, loop through each file
for($i=0; $i<count($_FILES['callflowfile']['name']); $i++)
{
// If the file in array exists
if ($_FILES["callflowfile"]["name"][$i])
{
// If the file isnt 0 bytes
if ($_FILES["callflowfile"]["error"][$i] > 0)
{}
else
{
//move the file
// first get the original name of the uploaded file
$filename = $_FILES["callflowfile"]["name"][$i];
// now rename the original file into a random name
// get the file extension first
$ext = substr(strrchr($filename, "."), 1);
// then generate the random file name
$randomName = md5(rand() * time());
$filePath = "documents/" . $randomName . '.' . $ext;
// move the file and rename it
if(move_uploaded_file($_FILES["callflowfile"]["tmp_name"][$i], $filePath)){
// Add uploaded file row to database
}
}
}
}
}
}
The file isn't uploaded while the other form values are saved correctly.
I get the following error:
Undefined index: callflowfile in //directory
Does anyone know how to upload a file next to other form post values?
Add an enctype="multipart/form-data" attribute to your form so that it allows file(s) to be posted/uploaded :
<form id="regForm" action="" method="POST" enctype="multipart/form-data">
And you need to adjust file processing loop conditionals, change it like this :
if (isset($_POST['formpost'])) {
// insert name- address - city - county to DB
// insert callflowfile to directory
// If The array exists, add callflowfile
if ($_FILES["callflowfile"]["tmp_name"]) {
//Count number of files in array, loop through each file
for ($i = 0; $i < count($_FILES['callflowfile']['tmp_name']); $i++) {
...
replace your form tag by this
<form id="regForm" action="" method="POST" enctype="multipart/form-data">
And after update kindly do var_dump($_POST,$_FILES) at the first line of your php file you will get the all post fields within $_POST variable and Information of file will get in $_FILES
I have an html form that is used to upload text files:
<div class="form">
<h3>Upload File:</h3>
<form action="networkSelector.php" method="post" enctype="multipart/form-data" name="FileUploadForm" id="FileUploadForm">
<label for="UploadFileField"></label>
<input type="file" name="UploadFileField" id="UploadFileField" />
<input type="submit" name="UploadButton" id="UploadButton" value="Upload" />
</form>
</div>
The php portion of the code for the form:
<?php
require('db.php');
include("auth.php");
if(isset($_FILES['UploadFileField'])){
// Creates the Variables needed to upload the file
$UploadName = $_FILES['UploadFileField']['name'];
$UploadName = mt_rand(100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadType = $_FILES['UploadFileField']['type'];
$FileSize = $_FILES['UploadFileField']['size'];
// Removes Unwanted Spaces and characters from the files names of the files being uploaded
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
// Upload File Size Limit
if(($FileSize > 125000)){
die("Error - File too Big");
}
// Checks a File has been Selected and Uploads them into a Directory on your Server
if(!$UploadTmp){
die("No File Selected, Please Upload Again");
}else{
move_uploaded_file($UploadTmp, "C:/xampp/htdocs/meg/$UploadName");
}
}
?>
It works great and as seen in the 'move_upload_file command it puts them directly into that directory.
However what I am trying to achieve is to upload these files with this form and then to add it to another form that is on the same page.
Here is an example of my other form:
<form action="networkCompiler.php" method="POST">
<h3>Choose Network/Function:</h3>
<select id ="network" name="network" />
<option value="networkA">A</option>
<option value="networkB">B</option>
</select>
So ideally if I upload networkC on the first form, I want it to then display on the second form. I am using PHP primarily on this project and was attempting to find a solution in that language. So far I have tried saving the file upload as a variable and then adding that to the bottom of the form.
<?php
if (isset($_POST['UploadButton'])) {
if (is_uploaded_file($_FILES['UploadFileField']['tmp_name'])) {
$trying = $_POST['FileUploadForm'];
}
}
?>
Any input would be appreciated. Thank you.
Use file_get_contents():
<?php
if(your_condition)
echo '<option value="the_value_you_want">' . file_get_contents('path_of_uploaded_file') . '</option>';
?>
I want to use fwrite to save data into a .txt file. The action method seems to be working, as it can show HTML tags when being transfered when pressing submit, but i wont run the PHP.
<HTML lang="da">
<style>
</style>
<header>
<title>Tilføj</title>
<meta charset="ISO-8859-1">
</header>
<body>
<form method="post" action="eksamen_save_data.php" enctype='multipart/form-data'>
<fieldset>
<legend>Filmoplysninger</legend>
<div><label>Titel: <input type="text" name="titel" id="titel" required="required" size="60" maxlength="100"></label></div>
<div><label>Hovedskuespiller: <input type="text" name="hovedskuespiller" id="hovedskuespiller" required="required" size="30" maxlength="100"></label></div>
<div><label>Genre: <input type="text" name="genre" id="genre" required="required" size="60" maxlength="100"></label></div>
<div><label>Format: <input type="text" name="format" id="format" required="required" size="60" maxlength="100"></label></div>
<div><label>Billede: <input type="file" name="billede" id="billede" required="required"></label></div>
</fieldset>
<div><input type="submit" id="ok" value="OK"></div>
</form>
</body>
This sends it to the "eksamen_save_data.php" that looks like this:
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
//$Billede = $_FILES["billede"]["navn"];
//if($_FILES){
// move_uploaded_file($_FILES["billed"]["navn"], $_FILES["billed"]["navn"]);
//}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
$fh = fopen("data.txt", "a") or die("Fejl i åbning af fil!");
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
fclose($fh);
?>
If i write some HTML in the "eksamen_save_data.php" i can show this, but it wont run the PHP. I'm using XAMPP.
The problem is that it wont save to the "data.txt" file as i tell the PHP to do.
Another question; is there also a way, I can make the PHP run in the same file as where I have my fieldset?
LAST EDIT:
Most of the time it's the little mistakes that proves to be the biggest problem. For me i personally forgot to use: localhost/eksamen_tilføj.php in the browser.
So it was me making a mistake in XAMPP.
Use file_put_contents
file_put_contents("data.txt", $user_data, FILE_APPEND);
It does all the jobs like file open, write and close. Advantage is if the file does not exist then it will create.
Find full working code
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
$Billede = $_FILES["billede"]["name"];
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["billede"]["name"];
$fileTmpLoc = $_FILES["billede"]["tmp_name"];
// Path and file name
$pathAndName = "upload/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
file_put_contents("data.txt", $user_data, FILE_APPEND);
?>
you'll have to remove the third parameter $test (because it specifies the length of the content to be written). But $test is not defined in your PHP file, so it won't write anything..
So change this
fwrite($fh, $user_data, $test) or die ("Fejl i skrivning til fil!");
into this
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
and have a look at this :)
As for your second question: sure you can merge your form and submit scripts:
<?php
if(count($_POST) > 0) { //
/** Form submit function, file write **/
} else {
?>
<html>
<form action="#" method="POST">
<!-- Enter HTMLform here -->
</form>
</html>
<?php } ?>
This pseudocode is not pretty, but will do in terms of explaining stuff. The # in the form action means that the same script is to be called upon submission. The if(count($_POST) > 0) checks whether data has been submitted. If so, the file will be written. Otherwise, the form will be displayed.
Good luck.
i'm trying to get DropzoneJS to work, i got far but it seems i've got a problem i can't solve.
so basicly what i want is to upload a file and get a download link back within the same page.
so i added this code to my index.php:
<form action="index.php" class="dropzone" id="my-awesome-dropzone"></form>
and the php code into the index.php:
<?php
include('config.php');
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$dirname = uniqid();
mkdir( $filedir.'/'.$dirname);
mkdir( $filedir.'/'.$dirname.'/file');
copy("template/d.php", "d/$dirname/index.php");
copy("template/dl.php", "d/$dirname/dl.php");
preg_match('/\.([a-zA-Z0-9]+?)$/', $_FILES['file']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['file']['size'] <= $maxsize) {
$newname = ($_FILES['file']['name']);
// file name encryption
//$newname = md5_file($_FILES['file']['tmp_name']).'.'.$matches[1];
move_uploaded_file($_FILES['file']['tmp_name'], $filedir.'/'.$dirname.'/file/'.$newname);
$linkurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).'#'.$newname;
$imgurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).$filedir.'/'.$dirname.'/file/'.$newname;
$alt = $_POST["alt"];
$dlurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).$filedir.'/'.$dirname;
print '<h2>Picture Uploaded Successfuly!!!!</h2> <p id="codes">
<img src="'.$imgurl.'" height="300" alt="Uploaded Picture" >
<label for="codebb">BBCode:</label>
<input type="text" id="codebb" value="[URL='.$siteurl.'][IMG]'.$dlurl.'[/IMG][/URL]" onclick="javascript:this.focus();this.select();" readonly="true" /><br />
<label for="codehtml">HTML Code: </label>
<input type="text" id="codehtml" value=\'<a href="'.$siteurl.'"><img src="'.$dlurl.'" alt="'.$alt.'" /></a>\' onclick="javascript:this.focus();this.select();" readonly="true" /><br />
<label for="codedirect">Direct Link:</label>
<input type="text" id="codedirect" value="'.$dlurl.'" onclick="javascript:this.focus();this.select();" readonly="true" /></p>';
echo ".$newname";
} else
print '<p>Sorry, Max Picture size is 10Mb</p>';
}
}
?>
when i upload the file the php works and the file is uploaded successfully into its folder so the php is working.
my problem now is why dont i get the print from the php script.
fully working script:
http://37.34.62.131/test/uploader%201.0/
not working NEW script:
http://37.34.62.131/test/
i think it has something to do with the uploader because my old script uses a submit button and my newer version is using a automatic submit.
i very appreciate your time!
I am a newbie and have spent over 3 hours trying to find a way to get the filename, filesize, path, from the uploaded file. But this form is doing it in a way i am not able to understand. I need the filename, filesize, path variables stored in the db. How can i implement a $sql insert in the code below:
Code:
$upload_dir = "/var/www/anyexample/aeu"; // Directory for file storing
// filesystem path
$web_upload_dir = "/aeu"; // Directory for file storing`
// Web-Server dir
/* upload_dir is filesystem path, something like
/var/www/htdocs/files/upload or c:/www/files/upload
web upload dir, is the webserver path of the same
directory. If your upload-directory accessible under
www.your-domain.com/files/upload/, then
web_upload_dir is /files/upload
*/
// testing upload dir
// remove these lines if you're shure
// that your upload dir is really writable to PHP scripts
$tf = $upload_dir.'/'.md5(rand()).".test";
$f = #fopen($tf, "w");
if ($f == false)
die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
or something like this");
fclose($f);
unlink($tf);
// end up upload dir testing
// FILEFRAME section of the script
if (isset($_POST['fileframe']))
{
$result = 'ERROR';
$result_msg = 'No FILE field found';
if (isset($_FILES['file'])) // file was send from browser
{
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) // no error
{
$filename = $_FILES['file']['name']; // file name
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
// main action -- move uploaded file to $upload_dir
$result = 'OK';
}
elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
$result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
else
$result_msg = 'Unknown error';
// you may add more error checking
// see http://www.php.net/manual/en/features.file-upload.errors.php
// for details
}
// outputing trivial html with javascript code
// (return data to document)
// This is a PHP code outputing Javascript code.
// Do not be so confused ;)
echo '<html><head><title>-</title></head><body>';
echo '<script language="JavaScript" type="text/javascript">'."\n";
echo 'var parDoc = window.parent.document;';
// this code is outputted to IFRAME (embedded frame)
// main page is a 'parent'
if ($result == 'OK')
{
// Simply updating status of fields and submit button
echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';
echo 'parDoc.getElementById("filename").value = "'.$filename.'";';
echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';
echo 'parDoc.getElementById("upload_button").disabled = false;';
}
else
{
echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';
}
echo "\n".'</script></body></html>';
exit(); // do not go futher
}
// FILEFRAME section END
// just userful functions
// which 'quotes' all HTML-tags and special symbols
// from user input
function safehtml($s)
{
$s=str_replace("&", "&", $s);
$s=str_replace("<", "<", $s);
$s=str_replace(">", ">", $s);
$s=str_replace("'", "'", $s);
$s=str_replace("\"", """, $s);
return $s;
}
if (isset($_POST['description']))
{
$filename = $_POST['filename'];
$size = filesize($upload_dir.'/'.$filename);
$date = date('r', filemtime($upload_dir.'/'.$filename));
$description = safehtml($_POST['description']);
// Let's generate file information page
$html =<<<END
<html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>
<body>
<h1>{$filename}</h1>
<p>This is a file information page for your uploaded file. Bookmark it, or send to anyone... </p>
<p>Date: {$date}</p>
<p>Size: {$size} bytes</p>
<p>Description:
<pre>{$description}</pre>
</p>
<p>download file<br>
back to file uploading<br>
upload-log</p>
<br><br>Example by AnyExample
</body></html>
END;
// save HTML
$f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
fwrite($f, $html);
fclose($f);
$msg = "File {$filename} uploaded,
<a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";
// Save to file upload-log
$f = fopen($upload_dir."/upload-log.html", "a");
fwrite($f, "<p>$msg</p>\n");
fclose($f);
// setting result message to cookie
setcookie('msg', $msg);
// redirecting to the script main page
// we're doing so, to avoid POST form reposting
// this method of outputting messages is called 'flash' in Ruby on Rails
header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
exit();
// redirect was send, so we're exiting now
}
// retrieving message from cookie
if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')
{
if (get_magic_quotes_gpc())
$msg = stripslashes($_COOKIE['msg']);
else
$msg = $_COOKIE['msg'];
// clearing cookie, we're not going to display same message several times
setcookie('msg', '');
}
?>
<!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for outputing message
echo '<p style="font-weight: bold;">'.$msg.'</p>';
?>
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>
<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileframe" value="true">
<!-- Target of the form is set to hidden iframe -->
<!-- From will send its post data to fileframe section of
this PHP script (see above) -->
<label for="file">text file uploader:</label><br>
<!-- JavaScript is called by OnChange attribute -->
<input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
// this is just an example of checking file extensions
// if you do not need extension checking, remove
// everything down to line
// upload_field.form.submit();
var re_text = /\.txt|\.xml|\.zip/i;
var filename = upload_field.value;
/* Checking file type */
if (filename.search(re_text) == -1)
{
alert("File does not have text(txt, xml, zip) extension");
upload_field.form.reset();
return false;
}
upload_field.form.submit();
document.getElementById('upload_status').value = "uploading file...";
upload_field.disabled = true;
return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
"display: none" from style="" attribute -->
<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status"
value="not uploaded" size="64" disabled>
<br><br>
File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>
<form action="<?=$PHP_SELF?>" method="POST">
<!-- one field is "disabled" for displaying-only. Other, hidden one is for
sending data -->
<input type="hidden" name="filename" id="filename">
<br><br>
<label for="photo">File description:</label><br>
<textarea rows="5" cols="50" name="description"></textarea>
<br><br>
<input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
upload-log
<br><br><br>
Example by AnyExample
</body>
</html>
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
I would suggest adding something like the following after the previous mentioned line:
$size = filesize($upload_dir.'/'.$filename);
$path = $upload_dir.'/'.$filename;
mysql_connect(YOUR_HOST, YOUR_USERNAME, YOUR_PASSWORD);
mysql_select_db(YOUR_DATABASE);
mysql_query('INSERT INTO your_table SET filename=$filename, size=$size, path=$path');