How to find out the relative path to upload image in php? - php

I have a problem to find out the relative path to
upload the images to other directories
target directory
htdocs/dt3/tadi/adm/dim/dim_images/tadi_user_images/
source directory
htdocs/dt3/tadi/adm/cbt/uploadfile.php
uploadfile.php
<html>
<form method="post"enctype="multipart/form-data">
<input type="file" name="fileimg1" ><input type="submit" name="upload">
</form>
</html>
<?php
$dirname = "/dt3/tadi/adm/dim/dim_images/tadi_user_images/";
$of = $_FILES['fileimg1']['name'];
$ext = pathinfo($of, PATHINFO_EXTENSION);
$changename3 = time() * 24 * 60;
$image_name3 = "timage_" . $changename3 . "." . $ext;
$final_pathdir = $dirname . $image_name3;
$suc = move_uploaded_file($_FILES['fileimg1']['tmp_name'], $final_pathdir);
if ($suc > 0)
{
echo "Image uploaded successfully";
}
else
{
echo "Error : " . $_FILES['filimg1']['error'];
}
?>
I tried out some of the paths, I didnt got any solution for that.
How can I upload images to that path?
htdocs/dt3/tadi/adm/dim/dim_images/tadi_user_images/
With relative path only.

I believe you could do
$dirname = dirname(__FILE__)."/../dim/dim_images/tadi_user_images/"

Related

Multiple file uploads to a specific folder

I'm attempting to create a plugin on wordpress and I need to upload multiple images to a specific folder on the server...
I currently have
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple">
<input type="submit" value="Upload">
</form>
And this is the code that reads and should upload the files...
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$name = $myFile["name"][$i];
$error_msg = $myFile["error"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $photo_dir."/".$name);
if ($success) {
echo $name ." uploaded<br>";
} else {
echo $error_msg;
}
}
}
Is there a way to get it to report an error - at the moment if the file name already exists then it jsut overwrites the old version...
When you do a upload of files PHP store the files in a temporary folder.
You have to move the file from temporary folder to the folder that you want to store the files.
Here is an example using your code:
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
// The folder that you want to store the file
$folderName = 'tmp/';
for ($i = 0; $i < $fileCount; $i++) {
$fileName = $myFile["name"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $folderName . $fileName);
if ($success) {
echo 'File ' . $fileName . ' uploaded!<br>';
}
}
}

How to upload excel file to php server from <input type="file">

I want to upload excel file using to php and wanted to perform some file operation in that excel file. I am not able to upload the file , If any one have some Idea please help , in the server side how to get the path from where the file has been uploaded?
$target_dir = 'uploads/'; is not working for me. and My file is in D: Please help.
PHP CODE:
<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
require_once dirname(__FILE__) . '/Includes/Classes/PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($target_file);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($target_file);
$i=2;
$val=array();
$count=0;
for($i=2;$i<34;$i++)
{
$val[$count++]=$objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
}
//echo'<pre>';print_r($val);
}
?>
HTML CODE:
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="filepath" id="filepath"/></td><td><input type="submit" name="SubmitButton"/>
</body>
You first need to upload the file before the read line:
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["filepath"]["tmp_name"], $target_file);
// rest of your code...
now you should be able to continue working on the file.
before this, the file never have been in your uploads folder.
if(isset($_POST['SubmitButton'])){
try { //attached file formate
$statement = $db->prepare("SHOW TABLE STATUS LIKE 'table_name'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
$new_id = $row[10]; //10 fixed
$up_filename=$_FILES["filepath"]["name"];
$file_basename = substr($up_filename, 0, strripos($up_filename, '.')); // strip extention
$file_ext = substr($up_filename, strripos($up_filename, '.')); // strip name
$f2 = $new_id . $file_ext;
move_uploaded_file($_FILES["filepath"]["tmp_name"],"uploads/" . $f2);
// Client's info Insert MySQl
$statement = $db->prepare("INSERT INTO table_name (files) VALUES (?)");
$statement->execute(array($f2));
$success_message = "Excel file upload successfully!";
}
catch(Exception $e) {
$error_message = $e->getMessage();
}
}
Form code:
<form action="" method="post" enctype="multipart/form-data"> <input
type="file" name="filepath" id="filepath"/></td><td><input
type="submit" name="SubmitButton"/>
</form>
U did not write code to upload file.
move_uploaded_file()
You have to move your file from the temporary upload directory to the directory you want it in with the move_uploaded_file() function.
There are 2 arguments you need to put for the move_uploaded_file() function - the temporary file you just uploaded (ex. $_FILES["file"]["tmp_name"]), and then the directory you want to move it to... So it would end up looking something like this: move_uploaded_file($_FILES["file"]["tmp_name"], $path_of_new_file)

How to upload files to specific subdirectory

I am working on a simple thing that uploads files using PHP.
My form:
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="file_upload">
<input type="submit" name="submit" value="Upload">
</form>
And PHP:
$id = '3';
if (isset($_POST['submit'])) {
$tmp_file = $_FILES['file_upload']['tmp_name'];
$file = basename($_FILES['file_upload']['name']);
$upload_dir = "uploads";
if (file_exists($upload_dir."/".$file)) {
die("File {$file} already exists in {$upload_dir} folder.");
}
if(move_uploaded_file($tmp_file, $upload_dir."/".$file)) {
$message = "File " . $file . " uploaded to " . $upload_dir;
echo $message;
} else {
# Code with message about error.
}
}
Files successfully uploads only in uploads folder. In that uploads folder, I have few other folders: 1, 2, 3 and so on.
My question: How to move files in a specific subfolder after upload? (Subfolder name — from variable id.) Thanks!
Efficient way to do this:
This method move file when it get uploaded.
if (!empty($post_array['IconURI'])) {
$IconURI_current_path = "./" . $post_array['IconURI'];
if (file_exists($IconURI_current_path)) {
// Desired folder structure
$structure = './uploads/' . $primary_key . "/";
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (is_dir($structure) || mkdir($structure, 0777, true)) {
$dir = './uploads/' . $primary_key . "/" . $post_array['IconURI'];
chmod("$IconURI_current_path", 0777);
if (copy("$IconURI_current_path", "$dir")) {
#unlink("$IconURI_current_path");
//rename IconURI from [ 9723d-632ac-e325b-db1b8-icon.jpg ]
$IconURI = "uploads/" . $primary_key . "/" . $post_array['IconURI'];
}
} else {
die('Failed to create folders...');
}
} else {
echo "Banner file does not exist";
}
}
the script also handle file permissions. some time due to directory or files permission file couldn't moved.
Can be used as callback function like in Grocery CRUD or other third party Plugins. i.e these plugins uploads files to their default directory and you some time need to move file to other specific directory.

Rename a file if same already exists

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);
?>

Cannot upload .mpg files

I've built a rather straightforward file uploader in PHP. So far I've had no troubles uploading images and zip files. However, I can't seem to upload .mpg's. Whenever I try then it after hanging for a moment the page seems like it didn't try to upload anything at all. For example: this
// This is also manually set in php.ini
ini_set("upload_max_filesize", "524288000");
...
print_r($_FILES);
print_r($_POST); // I'm sending along one variable in addition to the file
returns nothing but empty arrays. For completeness, here's the front-end
<form action="uploadVideo.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000"/>
<input type="hidden" name="extravar" value="value" />
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<i>Accepted formats: .mp4, .3gp, .wmv, .mpeg and .mpg. Cannot exceed 500MB.</i>
</p>
<p>Description:</p>
<textarea name="description" rows="4" cols="40"></textarea>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The file I am testing with is only 33MB and I tested a .wmv of similar size and it uploaded just fine.
Edit: Entire PHP file listed below
<?php
// Ensure that the user can upload up to the maximum size
ini_set("upload_max_filesize", "524288000");
ini_set("post_max_size", "524288000");
print_r($_POST);
print_r($_FILES);
if(!$link = mysql_connect($SERVER_LOCATION, $DB_USER, $DB_PASS)) die("Error connecting to server.");
mysql_select_db($DB_NAME);
$eventID = $_POST['event'];
// Select the event this is associated with
$query = "SELECT eventName FROM event WHERE eventID = $eventID";
if(!$res = mysql_query($query, $link)) die("Error communicating with database.");
$path = mysql_fetch_row($res);
$path = "media/$path[0]";
// If this event doesn't have a media folder, make one
if(!file_exists($path)) {
mkdir($path);
}
// If this event doesn't have a GIS subfolder, make one
$path = "$path/videos";
if(!file_exists($path)) {
mkdir($path);
}
// Generate todays date and a random number for the new filename
$today = getdate();
$seed = $today['seconds'] * $today['minutes'];
srand($seed);
$random = rand(0, 999);
$today = $today['mon']."-".$today['mday']."-".$today['year'];
$fileType = $_FILES["file"]["type"];
$fileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$isMP4 = ($fileType == "video/mp4" && $fileExtension == "mp4");
$isWMV = ($fileType == "video/x-ms-wmv" && $fileExtension == "wmv");
$isMPG = ($fileType == "video/mpeg" && ($fileExtension == "mpeg" || $fileExtension == "mpg"));
$is3GP = ($fileType == "video/3gp" && $fileExtension == "3gp");
$sizeIsOK = ($_FILES["file"]["size"] < 524288000);
if( ($isMP4 || $isWMV || $isMPG || $is3GP) && $sizeIsOK ) {
if($_FILES["file"]["error"] > 0) {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
die();
} else {
// Ensure that the file get's a unique name
$filename = $today . "-" . $random . "." . $fileExtension;
while(file_exists("$path/$filename")) {
$random = rand(0, 999);
$filename = $today . "-" . $random . "." . $fileExtension;
}
move_uploaded_file($_FILES["file"]["tmp_name"], "$path/$filename");
$description = $_POST['description'];
$query = "INSERT INTO media (eventID,FileName,File,filetype,Description) VALUES ($eventID,'$filename','$path','video','$description')";
if(!$res = mysql_query($query, $link))
echo "<p>Error storing file description. Please contact a system administrator.</p>";
else {
echo "<h3>File: <i>".$_FILES["file"]["name"]."</i></h3>";
if(strlen($description) > 0) {
echo "<h3>Description: <i>".$description."</i></h3>";
}
echo "<p><strong>Upload Complete</strong></p>";
}
echo "<button onclick=\"setTimeout(history.go(-1), '1000000')\">Go Back</button>";
}
} else {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
}
?>
You cannot adjust the file upload limits using ini_set() from within the script that the uploads go to - the script does not get executed until after the upload is completed, so the ini_set() overrides cannot take place. The default parameters in PHP will be in place with the lower limit, and will kill the upload if it exceeds the system upload_max_filesize.
You need to override at the .ini level in PHP, or via a php_value directive in a .htaccess file. Those will change PHP's settings as the upload starts.
Ok, the first thing i thougt would be a problem with the filesize but other files with this size are working as you wrote.
But just do get shure it isn't a file size problem:
When you rise the max filesize you hmust also rise the max post size: post_max_size

Categories