<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-`enter code here`scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>file upload</title>
</head>
<body>
<form action="upload.php" method ="POST" enctype="multipart/form-data">
Uploadfile <input type="file" name="userfile">
<input type="submit">
</form>
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your `enter code here`file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
</body>
</html>
Related
I was trying to upload a folder inside my htdocs folder in XAMPP.
I followed the rules of move_uploaded_file still did not work.
Here's my current code:
<?php
if(isset($_POST['submit'])){
$allowed_ext = array('png', 'jpg', 'jpeg', 'gif');
if(!empty($_FILES['upload']['name'])){
print_r($_FILES);
$file_name = $_FILES['upload']['name'];
$file_size = $_FILES['upload']['size'];
$file_tmp = $_FILES['upload']['tmp_name'];
$target_dir = "uploads/{$file_name}";
// Get file ext
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
// Validate file ext
if(in_array($file_ext, $allowed_ext)) {
// verify size
if($file_size <= 1000000) { // 1000000 bytes = 1MB
// Upload file
move_uploaded_file($file_tmp, $target_dir);
$message = '<p style="color: green;">File uploaded!</p>';
} else {
$message = '<p style="color: red;">File to large</p>';
}
} else {
$message = '<p style="color: red;">Invalid file type</p>';
}
} else {
$message = '<p style="color: red;">Please choose a file</p>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<?php echo $message ?? null; ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="upload" />
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>
Right now the images are not getting move to the uploads folder inside my current directory.
Any idea why?
Try this:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 1000000){
$errors[]='File size must be excately 1 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name); //create a folder 'uploads' in your folder
echo "Success";
}else{
print_r($errors);
}
}
?>
I wanted to write a code which will let me upload a text file and then find the words repeated inside the file but my program is not even printing the lines. What to do?
This is upload.php file which will be reading and verifying the file received.
<?php
$target_dir = "text/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "Sorry, file already exists."."<br>";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large."."<br>";
$uploadOk = 0;
}
if($fileType != "txt" ) {
echo "Sorry, only txt files are allowed."."<br>";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded."."<br>";
}
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$lines = file("$target_file");
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
This is index.php file from which I am sending the file as POST request.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/use.css">
<meta charset="utf-8">
<title>File Upload</title>
</head>
<body>
<h2>Upload a file for word matching</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload" required>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
Uploading the file is okay, but storing the path and the name of the file into my database is not.
This is my form html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<form action="../model/uploadcredentials.php" method="POST" enctype="multipart/form-data">
<input type="file" name="fileToUpload" placeholder="Upload your credentials">
<button type="submit" name="submit">Upload</button>
</form>
And here is my action file
<?php
if(isset($_FILES["fileToUpload"]["name"]))
{
$target_dir = "../assets/credentials/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
}
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$file = stripcslashes($_FILES["fileToUpload"]["name"]);
$file = mysqli_real_escape_string($con,$file);
$query = $con->query("INSERT INTO `portfolio`(p.desc) VALUES('$file')");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
I`am trying to get the filename and the path to store it in my database
It's always worth checking for and reporting errors.
In your INSERT, (p.desc) is trying to find a table called p (usually an alias) which isn't defined. Try...
$query = $con->query("INSERT INTO portfolio(desc) VALUES('$file')");
(Without the p.).
BUT I still recommend using prepared statements, have a read of How to create a secure mysql prepared statement in php?
I'm trying to upload a file to a server then display it to the user. I'm having difficulties to display the image to the user.
If you could provide code that helps me out to display the image to the user. The code should fit in the php file right under //Display image here <---------
html file
<html>
<body>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
php file
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: server.php?uploadsuccess");
//Display image here <----------
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
first you have to change .html file to .php and note that i have renamed file as index.php
<html>
<body>
<?php if(isset($_GET['filename'])){ ?>
<img src="<?php echo $_GET['filename']; ?>" />
<?php } ?>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
server.php
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: server.php?uploadsuccess");
//Display image here <----------
header("Location:index.php?filename=$fileDestination");
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
I have done using php but better option is using ajax call .just google it you will get man examples
To be able to display the image, do this :
//Display image here <----------
echo "<img src='" . $fileLocation . "'>";
Replace $file_location with the variable containing the file location
<!-- index.php -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file2upload">
<input type="submit" value="upload">
</form>
<!-- sorry i didn't got php code section here , so i m posting php file code here -->
<!-- upload.php file -->
<?php
// target directory where files goes after uploading
$target_dir = "uploads/pictures/";
// target files name and extension save to this target_file variable
// $target_file specifies the path of the file to be uploaded
$target_file = $target_dir . basename($_FILES["file2upload"]["name"]);
$uploadOk = 1;
// checking that target_file is been uploading is a true image file extenion or not
// $audioFileType holds the file extension of the file (in lower case)
$picFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
echo $picFileType."<br />";
if(isset($_POST["submit"])) {
// The filesize() function in PHP is an inbuilt function which is used to return the size of a specified file.
// The filesize() function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.
$check = getimagesize($_FILES["file2upload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// step:2
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// step: 3
// Check file size
if ($_FILES["file2upload"]["size"] > 5000000) { // 5MB manual set
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// step: 4
// Allow certain file formats
if($picFileType != "jpeg" && $picFileType != "jpg" && $picFileType != "bmp" && $picFileType != "gif" && $picFileType != "png" ) {
$uploadOk = 0;
echo "<b style='color:red;'> File to be uploading is not have image formates like : .jpeg,.jpg,.bmp, .gif, .png etc </b><br />";
}
// step: 5
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file2upload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["file2upload"]["name"]). " has been uploaded. <br />";
<!-- this is the ANSWER -->
<!-- ----------------------------- -->
echo $file_name = basename( $_FILES["file2upload"]["name"]);
echo $file_size = $_FILES["file2upload"]["size"];
echo $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
<!-- ----------------------------- -->
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
// }else{ echo "<b style='color:red;'> form have diffrent method ( post/get ) </b><br />"; $uploadOk = 0; }
?>
I have the following code, but even when I upload a valid image it echoes "Error: your file cannot be uploaded". It's passing all the checks but something is going wrong with the saving to a folder. I have a directory called 'uploads' in the same directory as the php file, so I'm not sure why it isn't saving the images there. I know I could do it with a database but I'm not too sure how. I just want to be able to save the uploaded images somewhere, and display the most recently uploaded image on the page.
Any tips on how to get this to work would be thoroughly appreciated.
Thanks!
upload.html
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>File Upload</title>
</head>
<body>
<header>
<h1>File Upload</h1>
</header>
<form action="/fileUpload.php" method="post" enctype="multipart/form-data">
<br>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
fileUpload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
$uploadCheck = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$uploadCheck = 1;
} else {
echo "Error: the file you attempted to upload is not an image";
$uploadCheck = 0;
}
}
if (file_exists($target_file)) {
echo "Error: file already exists.";
$uploadCheck = 0;
}
if ($_FILES["fileUpload"]["size"] > 500000) {
echo "Error: file is too large.";
$uploadCheck = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Error: incompatible type. only JPG, JPEG, PNG & GIF files.";
$uploadCheck = 0;
}
if ($uploadCheck == 0) {
echo "Error: your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "Success! Your file - ". basename( $_FILES["fileToUpload"]["name"]). " - has been uploaded.";
} else {
echo "Error: your file could not be uploaded";
}
}
?>
Your solution is here ( it contained errors),
First of all in Upload.html change /fileUpload.php to fileupload.php.
In upload.html & fileUpload.php, name attribute for file should be same.
upload.html
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>File Upload</title>
</head>
<body>
<header>
<h1>File Upload</h1>
</header>
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
<br>
Select image to upload:
<input type="file" name="fileUpload" id="fileUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
fileUpload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
$uploadCheck = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$uploadCheck = 1;
} else {
echo "Error: the file you attempted to upload is not an image";
$uploadCheck = 0;
}
}
if (file_exists($target_file)) {
echo "Error: file already exists.";
$uploadCheck = 0;
}
if ($_FILES["fileUpload"]["size"] > 500000) {
echo "Error: file is too large.";
$uploadCheck = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Error: incompatible type. only JPG, JPEG, PNG & GIF files.";
$uploadCheck = 0;
}
if ($uploadCheck == 0) {
echo "Error: your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
echo "Success! Your file - ". basename( $_FILES["fileUpload"]["name"]). " - has been uploaded.";
} else {
echo "Error: your file could not be uploaded";
}
}
?>
Instead of using this:
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
Try using this:
list($name,$ext)=explode(".",$_FILES["fileUpload"]["name"]);
and then try to validate the extension part:
if($ext!= "jpg" && $ext!= "png" && $ext!= "jpeg"&& $ext!= "gif" )
I suggest you to use in_array() for the above validation like this:
$img_ext=array("jpg","png","jpeg","gif");
if(!in_array($ext,$img_ext)){ //Your code here }
Try this $target_dir = "./uploads/";
also if your using windows pc under a wamp Environment grant the folder permission