I apologize for the super long post. I'm super noob and I would LOVE to have your help.
I made a file called Upload Pictures and in this file I have four files. First, php.ini with the following code:
file_uploads = On
Second, upload.html:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Third, upload.php:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
And fourth, I have a folder called uploads, with nothing inside that folder.
My main questions are from the upload.php file. Please correct me if I am incorrect in my understanding.
I understand $target_dir to be the directory in which the files will be stored. Now to the line with &target_file. I understand that $_FILES["fileToUpload"]["name"] returns the name of the file that I am uploading. So if my file name was picture.jpg, it will return picture.jpg.
My question is then, why do I need to call the basename()? Because I thought this function just returns the name of the file. So it's almost like returning the name twice with $_FILES["fileToUpload"]["name"] and basename()?
Also, it has been my experience that having a . and some function after is calling a method from a class. Is that what is happening here $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);? If so, I'm not sure what is actually being stored into $target_file.
Also, switching gears a little bit here, when I pressed the Upload Image button from my html, it takes me to another page. Is there a way to prevent that from happening?
basename returns the actual filename from a path.
In your example basename does not need to be used on the name being retrieved from $_FILES because it will have no associated path to begin with. In an upload script basename may be more traditionally used on tmp_name to remove any temporary folders from the name of the file.
The . is how you concatenate strings (or in this case variables containing strings) in PHP.
In this example, the code is concatenating the directory and the name of the file together into a variable in which it is used to get the extension in the $imageFileType variable using pathinfo.
The form has an action attribute. action="upload.php" so you will be taken to the 'upload.php' page when the form is submitted.
I hope this answers your questions-
actually basename() function for get file name with the extension of file.
so basename function stand for
basename(path,suffix)
Explanation
Parameter | Description
--------------------------
path | Required. Specifies the path to check
suffix | Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show
Ex
<?php
$path = "/testweb/home.php";
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".php");
?>
Output will be
home.php
home
php 5 basename() function
and we use . (dot) operator on here, $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
so this will bind $target_dir and basename(). so $target_file knows where is file should be goes exactly.
Related
<body>
<form action="#" enctype="multipart/form-data" method="post">
<input multiple="" name="img[]" type="file" />
<input name="submit" type="submit" />
</form>
<?php
mmysql_connect("localhost","root","");
mysql_select_db("multiple");
if(isset($_POST['submit'])){
$filename = $_FILES['img']['name']);
$tmpname = $_FILES['img']['tmp_name']
$filetype = $_FILES['img']['type'];
for($i=0; $i<=count($tmpname)-1; $i++){
$name =addslashes(filename[$i]);
$tmp = addslashes(file_get_contents($tmpname[$i]));
mysql_query("INSERT into img(name,image) values('$name','$tmp')");
echo "uploaded";
}
}
?>
</body>
</html>
I am trying to upload a simple image to my database So I can work on this user hosted site. So far nothing has worked. I'm dyin here. I've looked through so many tutorials.
From hitting an issue with file uploads before, it's much easier on the DB and your coding to upload your file to the server using 'move_uploaded_file()' and then provide a reference in your DB. In the above example, you are storing your file in a temporary folder ['tmp_name'], saving that file name, but then not transferring the file somewhere that won't delete it.
So for something generic to help:
$fileName $_FILES['img']['name'];
$fileType = $_FILES['img']['type'];
$fileLocation = $_FILES['img']['tmp_name'];
$newFileName = "newFileName.jpg";
$img = "folder/".$newFileName;
move_uploaded_file($fileLocation, "../folder/".$newFileName);
The reason for this is that when you save to the 'tmp' folder (which you must for a bit), the file is also renamed to a seemingly random set of characters. So you need to get that file location, move it to the folder of your choice, and also name it something findable. Then you can save the $img path in your DB and call it from anywhere (with some modification). It will take some playing with, but this should help.
To upload an image to the database directly from an uploaded file, you need to upload the base64 encoded version of the image. And also make sure that the field type of the image in your database is actually blog or LongBlog.
Here is the code to do that
$file = $_FILES['file'];
$filename = $file['name'];
$convert_to_base64 = base64_encode(file_get_contents($file['tmp_name']));
$base64_image = "data:image/jpeg;base64,".$convert_to_base64;
$query = mysqli_query($con, "INSERT INTO 'table'(image)VALUES('$base64_image')")
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)
I have a script which is uploading and saving video's correctly but I want to rename the video before saving.
The page upload-video.php ends in .php?video_id=556, in this example I want to save the video as 556
$video_id=$_GET["video_id"];
$target_dir = "video_uploads/";
And the move script:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file
Can anyone advise?
You can use
$target_file = $target_dir . $video_id;
to define the destination properly before your move_script.
In this line of code:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$target_file is the name of the file being saved on the server. You can use whatever value you like there. So if you want to save it as 556 then you'd use that as the file name. For example:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], '/path/to/videos/556');
Whatever logic you want to use to determine the file name would be the logic you use to build the $target_file variable.
$video_id=$_GET["id"];
$path = $_FILES["fileToUpload"]["name"];
$ext = pathinfo($path, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "video_uploads/$video_id.$ext"
I'm trying to figure out how to allow image upload with the image showing up after it is uploaded. I have found this tutorial on uploading images but I'm not sure how to display them afterwards. Would I have to save it in the database then pull it up afterwards somehow?
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I think you would benefit from an uploading class or function that returns information for your uploaded image. This will help you store the results or display as you are looking to do. Here is one loosely based on what you provided with notation:
Form:
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Script:
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'];
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
To use:
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
RAW Feedback:
// This is what the array would look like on return of successful upload:
Array
(
[filename] => animal.png
[fullpath] => /data/19/2/133/150/2948313/user/2524254/htdocs/mydomain/uploads/animal.png
[localpath] => /uploads/animal.png
[filesize] => 35702
)
yes,you would have to save the path to the file in the database and fetch it but for your use case,you can save the path to a $_SESSION variable and then echo the path immediately the script is done.
But you first have to complete the file transfer with the move_uploaded_file function as without that,you would not be able to retrieve the file path as they are stored as temporary files and deleted once the script is interpreted
http://php.net/manual/en/function.move-uploaded-file.php
After this is done,you are to get the path to the file and use the normal img HTML tag
create <img src="" widht="" height="" /> forever u must move the image to directory path and now i get the image name from table after submit the form.. and given the url to img..example.. ur directory name uploads/img . now your file name save in database table as image01.jpg . sample
$img= 'select imagename from table name ';
if(count($img))
{
<img src="<?php echo 'uploads/img/'.$img" widht="10px" height="20px" /></div>
}
if you upload image on data base , data loading will be slow because image siz too large. better method is upload image in folder & save image file path in data base .when you retrieve image call image web root on image tag
example
Saving Filepath Of Uploaded Image To MySQL Database
GET image path
name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:
$check = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
Here is the HTML:
<h1>Upload Custom Logo</h1>
<form action="settings.php" enctype="multipart/form-data" method="post">
<input type="file" name="Logo" />
<input type="submit" value="Upload" name="logoUpload" />
</form>
Here is the PHP:
<?php /* Handle Logo Upload */
if($_POST['logoUpload']) {
$target_path = "uploads/";
$Logo = $_FILES['Logo']['name'];
$target_path = $target_path . basename( $_FILES['Logo']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<div class="statusUpdate">The file '. basename( $_FILES['Logo']['name']).
' has been uploaded</div>';
}
} else{
echo '<div class="statusUpdate">There was an error uploading the file to: '.$target_path.', please try again! Error Code was: '.$_FILES['Logo']['error'].'</div>';
}
}
?>
It always goes to the "else" statement on that code, I have an uploads folder in the same directory as this php file set to 777 file permissions. The image I am test uploading is under 10KB in size. But the move_uploaded_file() always fails and it doesn't return any error message except for the custom error message made with the else statement.
You're referring to the file in the $_FILES array by two different names -
$Logo = $_FILES['Logo']['name'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
Which one is it? Logo or uploadedfile ?
You're probably referencing an array index which doesn't exist.
Possible reasons:
The uploading of the file failed in some way.
You don't have permission to move the file to the target path.
As PHP.NET says:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
Reference: http://php.net/manual/en/function.move-uploaded-file.php