i'm trying to upload mp3 format file in to a folder using PHP. But this following coding is not working.Please can some one help my?
define("UPLOAD_DIR", "mp3_upload_folder/");
if (!empty($_FILES["myFile"]))
{
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK)
{
echo "<p>An error occurred.</p>";
exit;
}
// verify the file is a GIF, JPEG, or PNG
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$parts = pathinfo($name);
$sanjiv=$_POST['user_id'];
$name= $sanjiv.".".$parts["extension"];
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
This works, and make sure that it has permissions to write to the mp3_upload_folder. I think it's still short of a complete solution, but I am lacking a full view of the problem.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
define("UPLOAD_DIR", "./mp3_upload_folder/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = $myFile["name"]; //preg_replace("/[^A-Z0-9\.\-]/i", "_", $myFile["name"]); //this is pointless if you're not using it
// don't overwrite an existing file
$parts = pathinfo($name);
$name= $_POST['user_id'].".".$parts["extension"];
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR .$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="text" value="testUserId" name ="user_id"/>
<input type="file" name="myFile"/>
<input type="submit"/>
</form>
</body>
</html>
Also make sure that you edit your server settings as well as your php settings for uploading file sizes(in the php.ini):
Post_max_size
Upload_max_size (probably your offender default is 2M)
I'm not sure what server you are using, but information can be found easily enough by googling the server type and "max upload size"
Related
Sorry I know there's a lot of posts about that but I can't find a solution in those.
Here's my form :
<form id="form1" action="upload.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name : </td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Image :</td>
<td><input type="file" name="image"/></td>
</tr>
<tr><td id='submitAdd' colspan='2'><input type="submit"
value= " Add " /></td></tr>
</table>
</form>
And here upload.php :
<?php
$ext = strtolower(substr(strrchr($_FILES['image']['name'], '.'),1));
$ret = move_uploaded_file($_FILES['image']['tmp_name'], 'item_images/'.$_POST['name'].'.'.$ext);
if ($ret) {
echo 'works';
}
else {
echo 'doesnt work'."</br>";
echo $_FILES['image']['error'];
}
?>
The directory's permission are ok, no uploading error, but still it won't move the file.
Am I missing something ?
Thanks in advance
I think you need to be specifying the absolute save path rather than the relative path it looks like you have now.
Ex. dirname(__FILE__).'/item_images/'.$_POST['name'].'.'.$ext
I would move the file under the uploaded file name, and then rename it. Also, some file type checking and security should be added to this.. Sanitize the post ect.. Here is how I would do it.
upload.php
<?php
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
//now we do some security checks
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than xxx Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
//give it the new name
$userstring= $_POST['name'];
$string = $fname.$userstring.'.'.$exten;
$image_name = preg_replace('/\s+/', '', $string);
//now we move it.
$moveResult = move_uploaded_file($fileTmpLoc, "item_images/$image_name");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
$imageFile = "item_images/$image_name";
//$imageFile is the variable to use in the rest of your script.
?>
I just how to fix this problem. This worked for me you can give it a try:
Just change
item_images/'.$_POST['name'].'.'.$ext);
to
'item_images/'basename($_FILES["image"]["name"])
I have an HTML form that is intended to allow file uploads to a server. I am programming an FTP client which is going well so far except that the files will not upload to the server. My form is as follows:
<form action='upload.php' id='upload'>
<input type='file' name='file' />
<input name='file_name' placeholder='File Name' />
<input type='submit' value='upload' />
</form>
And here is my php:
<?php
$ftp_connection = ftp_connect($_COOKIE['domain']);
if(#ftp_login($ftp_connection, $_COOKIE['username'], $_COOKIE['password'])) {
ftp_put($ftp_connection, $_REQUEST['file_name'], $_REQUEST['file']);
}
ftp_close($ftp_connection);
?>
Also note that all of those cookies work perfectly fine, as I use them to login to the FTP GUI.
Your form is missing enctype="multipart/form-data" which is required when uploading files.
Plus a POST method is also required.
Modify your <form... to read as:
<form action='upload.php' id='upload' enctype='multipart/form-data' method='post'>
<form> defaults to GET when omitted.
Also have a look at:
http://php.net/manual/en/book.ftp.php
Example from that page:
<?php
$ftp_server="";
$ftp_user_name="";
$ftp_user_pass="";
$file = "";//tobe uploaded
$remote_file = "";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
exit;
} else {
echo "There was a problem while uploading $file\n";
exit;
}
// close the connection
ftp_close($conn_id);
?>
and
http://php.net/manual/en/function.ftp-put.php
Example from that page:
<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
?>
and
<?PHP
$destination_path = "src/bin/";
//where you want to throw the file on the webserver (relative to your login dir)
$destination_file = $destination_path."img.jpg";
//This will create a full path with the file on the end for you to use, I like splitting the variables like this in case I need to use on on their own or if I'm dynamically creating new folders.
$file = $myFile['tmp_name'];
//Converts the array into a new string containing the path name on the server where your file is.
$upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);// upload the file
if (!$upload) {// check upload status
echo "FTP upload of $destination_file has failed!";
} else {
echo "Uploaded $file to $conn_id as $destination_file";
}
?>
I am setting up a file upload service on my website. Here is what I got so far,
upload.php
<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input type="submit" value="Upload">
</form>
uploader.php
<?php
define("UPLOAD_DIR", "/uploads");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// verify the file is a GIF, JPEG, or PNG
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
// file type is not permitted
echo "<p>Unable to save file.</p>";
exit;
}
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
There is a folder in my directory called uploads, I want my files to upload to there.
However when running it using XAMMP, I try and upload a image called example.png and it comes up with the following errors.
Warning: move_uploaded_file(/uploadsexample.png): failed to open stream: Permission denied in C:\xampp\htdocs\assembly\uploader.php on line 37
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpBAE5.tmp' to '/uploadsexample.png' in C:\xampp\htdocs\assembly\uploader.php on line 37
Unable to save file.
If you could help me solve my issue I would be very grateful! thanks.
Add a trailing slash / for
define("UPLOAD_DIR", "/uploads");
^ missing slash
change it to:
define("UPLOAD_DIR", "/uploads/");
Notice the error you got => to '/uploadsexample.png'
and in
Warning: move_uploaded_file(/uploadsexample.png):
^
it's missing a slash after uploads, between uploads and the filename.
Plus, just to be on the safe side, if that still throws you an error that it won't let you upload with another "permission denied" message, make sure that the folder is indeed writeable with proper write permissions set for it.
N.B.:
You may need to modify /uploads/ to uploads/ or ../uploads/ depending on the script's execution location.
I'm trying to upload a file and rename it if it already exists.
The way I want i to do is that when det same file uploads the name just adds 1, then 2, then 3, and so on.
Example: If file "file" exists, the new file should be "file1", then the next one "file2".
I've seen some examples on the net, but nothing that I could see fit to my code (noob)
This is my code now:
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {die("You can only upload PDF files");}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {die("The file is too big. Max size is 1MB");}
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
// Creates new catalogue then move the file in place
mkdir("filer/".$id);
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname); } }
Can somebody help me where I can put in code that solves this problem?
Big thank you!
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {
die("You can only upload PDF files");
}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("filer/".$id."/")) {
mkdir("filer/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("filer/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);
}
But don't forget to secure your script (eg see comment of Marc B above) and maybe you could optimize some more ;-)
so if folder exists:
file_exists("filer/".$id."/")
check if file exists
file_exists("filer/".$id."/".$fname)
and then if it does,
$fname = $fname . "(1)" // or some appending string
So in the end you change your code to:
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
while (file_exists("filer/".$id."/".$fname)) // Now a while loop
$fname = "copy-" . $fname; // Prepending "copy-" to avoid breaking extensions
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
<form action="test.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
$id = $_SESSION['id'];
$fname = $_FILES['fileToUpload']['name'];
// Checking filesize
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/".$id."/".$fname)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}else {
echo "Sorry, there was an error uploading your file.";
}
// Check file size$
if ($_FILES['fileToUpload']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("uploads/".$id."/")) {
mkdir("uploads/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("uploads/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['fileToUpload'] ['tmp_name'],"uploads/".$id."/".$fname);
?>
I am able to generate a link using my file upload system, now after five visits... i need the link if opened should display a message it has been expired.
<?php
function display_upload_form()
{
echo <<<DISPLAY_UPLOAD_FORM
<html>
<head>
<title>Yet Another Upload Form</title>
<style type="text/css" media="screen">
<!--
html body
{background:#fff; font: 76%/1.5em arial, helvetica, sans-serif; color:#333;}
input
{color:#333;}
-->
</style>
</head>
<body>
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data">
<p>Select a file.<br />
<input type="file" name="myfile" tabindex="1" /></p>
<p><input type="hidden" name="execute" value="1" /></p>
<p><input type="submit" value="Upload File" tabindex="2" />
</form>
</body>
</html>
DISPLAY_UPLOAD_FORM;
}
function execute_upload()
{
// root path
$path = $_SERVER['DOCUMENT_ROOT'];
// upload directory. path will originate from root.
$dirname = '/uploads';
// permission settings for newly created folders
$chmod = 0755;
// create file vars to make things easier to read.
$filename = $_FILES['myfile']['name'];
$filesize = $_FILES['myfile']['size'];
$filetype = $_FILES['myfile']['type'];
$file_tmp = $_FILES['myfile']['tmp_name'];
$file_err = $_FILES['myfile']['error'];
$file_ext = strrchr($filename, '.');
// check if user actually put something in the file input field.
if (($file_err == 0) && ($filesize != 0))
{
// Check extension.
if (!$file_ext)
{
unlink($file_tmp);
die('File must have an extension.');
}
// extra check to prevent file attacks.
if (is_uploaded_file($file_tmp))
{
/*
* check if the directory exists
* if it doesnt exist, make the directory
*/
$dir = $path . $dirname;
if (!is_dir($dir))
{
$dir = explode('/', $dirname);
foreach ($dir as $sub_dir)
{
$path .= '/' . $sub_dir;
if (!is_dir($path))
{
if (!mkdir($path, $chmod))
{
unlink($file_tmp);
die('<strong>Error:</strong> Directory does not exist and was unable to be created.');
}
}
}
}
/*
* copy the file from the temporary upload directory
* to its final detination.
*/
if (#move_uploaded_file($file_tmp, $dir . '/' . $filename))
{
// success!
echo "
<p>Success!</p>
<p><strong>View File:</strong> $filename</p>
";
}
else
{
// error moving file. check file permissions.
unlink($file_tmp);
echo '<strong>Error:</strong> Unable to move file to designated directory.';
}
}
else
{
// file seems suspicious... delete file and error out.
unlink($file_tmp);
echo '<strong>Error:</strong> File does not appear to be a valid upload. Could be a file attack.';
}
}
else
{
// Kill temp file, if any, and display error.
if ($file_tmp != '')
{
unlink($file_tmp);
}
switch ($file_err)
{
case '0':
echo 'That is not a valid file. 0 byte length.';
break;
case '1':
echo 'This file, at ' . $filesize . ' bytes, exceeds the maximum allowed file size as set in <em>php.ini</em>. '.
'Please contact your system admin.';
break;
case '2':
echo 'This file exceeds the maximum file size specified in your HTML form.';
break;
case '3':
echo 'File was only partially uploaded. This could be the result of your connection '.
'being dropped in the middle of the upload.';
case '4':
echo 'You did not upload anything... Please go back and select a file to upload.';
break;
}
}
}
// Logic Code *****************************************************************
if (isset($_POST['execute']))
{
execute_upload();
}
else
{
display_upload_form();
}
?>
I am using the following code which i got.
You're likely going to have to store the counter someplace. A text-file, or preferably a database. You would benefit heavily from a single-table database that has a field for the file, and a field for the current count.
When the file is requested, you check the count from the database. If it's < 5, you deliver the file and increment the value. If it's >= 5, you return an error, and remove the file.