I'm having a little trouble with this. Thought it'd be easier, but turning out to frustrate. All I'm trying to do is have a text field where I can type the name of a new directory, check if that directory exists, and if not create it. I have found about 50 other people with almost the exact same code, so thought I had it correct but I keep getting Directory exists as per the "if" statement.
Eventually I want to tie this into my file upload script.
Here is the insert.php
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="directory">Directory:</label>
<input value="<?php if ($_POST && $errors) {
echo htmlentities($_POST['directory'], ENT_COMPAT, 'UTF-8');
}?>" type="text" name="directory" id="directory" />
</p>
<p>
<input type="submit" name="insert" id="insert" value="insert" />
</p>
</form>
And here is the post.php
try {
if (isset($_POST['insert'])) {
$directory = $_POST['directory'];
$photo_destination = 'image_upload/';
$path = $photo_destination;
$new_path = $path . $directory;
$mode = 0755;
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
} else {
mkdir($new_path , 0777);
echo "The Directory {$new_path} was created";
}
}
}
Change this :
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
to this :
if(is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
Try and tell me the result :)
Instead of using is_dir in the if block you can use file_exists. Because file_exists is the function to check whether file exists or not. For the same you can also refer to http://php.net/manual/en/function.file-exists.php
Try
if( is_dir( $new_path ) ) {
echo "The Directory {$new_path} exists";
}
Let someone wants to create a sub-folder,
with a year name under /uploads folderthen he/she want to create
another sub-folder under an /uploads/<year_name_folder>/,
named project_number.
$yearfolder = date('y');
if (!file_exists('uploads/'.$yearfolder)) {
mkdir("uploads/".$yearfolder);
}
*// Folder named by year has been created.*
$project_number = Any Unique field ,Come from database or anywhere !
$target_directory = mkdir("uploads/".$yearfolder."/".$project_number);
*// project number wise folder also created.
// If project number is not unique do check like year folder. I think every project number is unique.*
$target_dir = "uploads/$yearfolder/$project_number/";
*//my target dir has created where my document or pic whatever will be uploaded.*
Now Upload ! Woo
$target_file = $target_dir.($_FILES["file"]["name"]);
Related
This is my html form
<form action="index.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
This is my index.php file
<?php
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
}
}
?>
**The code is working properly. But, What I really need is to change the name of the 1st uploaded file to birthcertificate and the name of the 2nd uploaded file into NIC. **
**Example : If I upload a file named 123 or abc (whatever the name) the 1st file's name should be birthcertificate and the 2nd file's name should be NIC. **
There are probably lots of ways to do this.
I thought that making a list of the new file names
might be the way to go.
<?php
// Make a list of the new file names
$newFileNames = ['birthcertificate', 'NIC'];
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
// Grab new file name
$newFileName = array_shift($newFileNames);
// Make sure we actually got one
if ( $newFileName ) {
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$newFileName)
or die("Problems with upload");
}
}
}
move_uploaded_file(file, location);
You can use file and new name in location parameter like this:
$newname = "yourimg.png";
enter code here
move_uploaded_file($_FILES["userfile"]["tmp_name"][$key], "your location" . $newname);
This is the basic way of renaming, make changes to the loop for renaming both files. If you only upload 2 files at a time, you can use the array index for your logic.
You can rename a file:
Instead of below code inside foreach you have shared
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
You can use:
$temp = explode(".", $_FILES["userfile"]["name"]);
$newfilename = 'birthcertificate' . '.' . end($temp);
move_uploaded_file($_FILES["userfile"]["tmp_name"], $newfilename) or die("Problems with upload");
Try giving the file seperate names, in PHP you can receive them and make in one array if you need
You can also refer to this link:
How to rename uploaded file before saving it into a directory?
I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
i have this form to upload images:
<form method="post" action="upld.php" name="insertForm" enctype="multipart/form-data">
Image name:<br />
<input type="text" name="iname" /><br />
<input type="file" name="file" />
<input type="submit" name="upload" value="Upload" />
</form>
and here is the upld.php
<?php
$db_name = "DB_name";
$table_name = "tble";
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db($db_name, $connection) or die(mysql_error());
if(isset($_POST['upload'])){
if (($_FILES["file"]["error"] > 0))
{
echo "<h3> Error in File! </h3>";
}
else
{
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
//$id=mysql_insert_id();
$time=strftime("%Y-%m-%d %H:%M:%S", time());
$img_name=$_POST['iname'];
$img=$_FILES["file"]["name"];
$sql="INSERT INTO $table_name VALUES('{$img}','{$time}','{$img_name}')";
$result=mysql_query($sql,$connection);
mysql_close($connection);
echo "<h3>uploaded successfully</h3>";
}
}
}
echo "<br><br><a href='GalleryAdmin.php'>GO back to Admin Gallery</a>
";
?>
the problem is:
when i run it always say me file not exsist, acording to this if
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
i have the images folder with upld.php in the same folder
what would you guess is the problem?
I think you have a slight logical error
file_exists("images/" . $_FILES["file"]["name"])
Will return true if the file exists in the images folder (my guess would me if somebody already uploaded it). But, based on your log statement, what you want is
!file_exists("images/" . $_FILES["file"]["name"])
OK so you uploaded your file. But, what you checked was if it was in say "images/my.jpg". At this point its in tmp_name, in your tmp directory, most likely so, no it would always not exist at this point as the file is only in a temporary name, you need to check its in your temp location, move it, and then check if its in images surely?
First:
PHP uploads the file to a temp directory. This is the file you need to move to your images/ folder. You find the file in this location on your server:
$_FILES['file']['tmp_name']
This is the file on which you want to run file_exists to make sure the upload completed successfully. So:
if (file_exists($_FILES['file']['tmp_name']) {
// File upload successful. Now move file to your directory.
move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]);
// Now do the database stuff here.
// ...
} else {
// Nothing was uploaded and something is wrong!
}
Secondary:
Your code
file_exists("images/" . $_FILES["file"]["name"])
will return TRUE, and therefore (in your code) it will say that there are no file. That's a logical error on your part.
Try:
!file_exists("images/" . $_FILES["file"]["name"])
instead.
Third:
Make sure that the file to which you move the file (images/) have the proper chmod. It needs 775 for it to be possible to create files into. This is made via the ftp program.
Read more here: CHMOD tutorial
You will also need to move the file from the tmp dir to images before checking if it's there with file_exists.
Please use move_uploaded_file before you check if the file exists;)
Otherwise try this:
1.) error_reporting(E_ALL);
2.) chmod the images directory (775), right mouse click on directory
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];
I need customers to upload files to my website and I want to gather their name or company name and attach it to the file name or create a folder on the server with that as the name so we can keep the files organized. Using PHP to upload file
PHP:>>
if(isset($_POST['submit'])){
$target = "upload/";
$file_name = $_FILES['file']['name'];
$tmp_dir = $_FILES ['file']['tmp_name'];
try{
if(!preg_match('/(jpe?g|psd|ai|eps|zip|rar|tif?f|pdf)$/i', $file_name))
{
throw new Exception("Wrong File Type");
exit;
}
move_uploaded_file($tmp_dir, $target . $file_name);
$status = true;
}
catch (Exception $e)
{
$fail = true;
}
}
Other PHPw/form:>>
<form enctype="multipart/form-data" action="" method="post">
input type="hidden" name="MAX_FILE_SIZE" value="1073741824" />
label for="file">Choose File to Upload </label> <br />input name="file" type="file" id="file" size="50" maxlength="50" /><br />
input type="submit" name="submit" value="Upload" />
php
if(isset($status)) {
$yay = "alert-success";
echo "<div class=\"$yay\">
<br/>
<h2>Thank You!</h2>
<p>File Upload Successful!</p></div>";
}
if(isset($fail)) {
$boo = "alert-error";
echo "<div class=\"$boo\">
<br/>
<h2>Sorry...</h2>
<p>There was a problem uploading the file.</p><br/><p>Please make sure that you are trying to upload a file that is less than 50mb and an acceptable file type.</p></div>";
}
Look at mkdir(), assuming the user PHP is running as has appropriate permissions, you can simply make a directory inside of uploads/.
After that, you can modify $file_name to contain some of the other posted variables that you mentioned you will add. Just take care to ensure those variables contain only expected characters.
Do your customers need to Log into your site before they upload? If that's the case perhaps you can store/grab $_SESSION information regarding their company and name. You could then append that info to the $file_name or the $target directory.
the mkdir() idea below this looks like it will probably work, but have you considered what would happen if a user entered someone else's name, had someone else's name, or entered someone else's company?
use this code on the top of the page
$path = dirname( __FILE__ );
$slash = '/';
(stristr( $path, $slash )) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . $slash );
& use below code after inside if below exit;}
$folder = $file_name; // folder name
$dirPath = BASE_DIR . $folder; // folder path
$target = #mkdir( $dirPath, 0777 );
move_uploaded_file($tmp_dir, $target . $file_name);
here is your code as it is
I figured it out, I just made a input for the name ant attached it to the file name.