PHP File upload, image not posted - php

I'm trying to create a form to upload a file, the problem is that the file won't be uploaded. in my code it returns "Image not uploaded".
I've searched a lot online and all the examples uses the same code.
Code:
<?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
$is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
if (!$is_img) {
$userfile_name = "It isn't an image";
}
else {
if (!file_exists("/images/products/" . $_FILES['image_url']['name'])) {
$uploaddir = '/images/products/';
$userfile_tmp = $_FILES['image_url']['tmp_name'];
$userfile_name = $_FILES['image_url']['name'];
move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
}
else {
$userfile_name = $_FILES['image_url']['name'];
}
}
}
else {
$userfile_name = "Image not uploaded";
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype=”multipart/form-data”>
<p><label for="image">Immagine: </label>
<input type="file" name="image_url"/></p>
<p><input type="submit" value="Salva" /></p>
</form>
The form has also other fields and the data are correctly send to the server.

Try this
<?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
$is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
if (!$is_img) {
$userfile_name = "It isn't an image";
}
else {
if (!file_exists("images/products/" . $_FILES['image_url']['name'])) {
$uploaddir = 'images/products/';
$userfile_tmp = $_FILES['image_url']['tmp_name'];
$userfile_name = $_FILES['image_url']['name'];
move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
}
else {
$userfile_name = $_FILES['image_url']['name'];
}
}
}
else {
$userfile_name = "Image not uploaded";
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype="multipart/form-data">
<p><label for="image">Immagine: </label>
<input type="file" name="image_url"/></p>
<p><input type="submit" value="Salva" /></p>
</form>

Related

Upload PDF Files PHP

I am trying to upload only PDF files in my form, but nothing happens. It doesn't save the file name in the database and the file does not save into the directory.
My PHP code is
if (isset($_POST['submit'])) {
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname)) {
if ($_FILES['healthfile']['type'] != "application/pdf") {
echo "<p>Class notes must be uploaded in PDF format.</p>";
} else {
$filesql = "INSERT INTO tbl_health (link) VALUES ('{$filename}')".die(mysql_error());
$fileresult = mysql_query($filesql, $con).die(mysql_error());
}
if ($fileresult) {
echo 'Success';
} else {
echo 'fail';
}
}
}
my form is
<form action="allhealth.php" method="post" enctype="multipart/form-data">
<label>Upload Your Health Certificate</label>
<span class="btn btn-default btn-file">
Browse <input name="healthfile" type="file">
</span>
<br/><br/>
<button type="button" name="submit" class="btn-success">Submit</button>
</form>
Please help!!
Use this
if(isset($_POST["submit"]))
{
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
$FileType = pathinfo($newname,PATHINFO_EXTENSION);
if($FileType == "pdf")
{
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname))
{
$filesql = "INSERT INTO tbl_health (link) VALUES('$filename')";
$fileresult = mysql_query($filesql);
if (isset($fileresult))
{
echo 'File Uploaded';
} else
{
echo 'Something went Wrong';
}
}
else
{
echo "<p>Upload Failed.</p>";
}
}
else
{
echo "<p>Class notes must be uploaded in PDF format.</p>";
}
}
Note Before upload file you should check whether its in correct format
and MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Use this it's working now I have tested at local.
<?php
if (isset($_POST['submit'])) {
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
if ($_FILES['healthfile']['type'] == "application/pdf")
{
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname))
{
$filesql = "INSERT INTO tbl_health (link) VALUES('$filename')";
$fileresult = mysql_query($filesql);
}
else
{
echo "<p>Upload Failed.</p>";
}
if (isset($fileresult))
{
echo 'Success';
} else
{
echo 'fail';
}
}
else
{
echo "<p>Class notes must be uploaded in PDF format.</p>";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label>Upload Your Health Certificate</label>
<span class="btn btn-default btn-file">
Browse <input name="healthfile" type="file">
</span>
<br/><br/>
<input type="submit" name="submit" class="btn-success" value="submit">
</form>

Upload mp4 file

I'm trying to upload a mp4 file with php, and I succeed it, but after that, the file can't be run with VLC, even though it could be run before upload. The error message says that the file can't be opened gives me the path of the file and ends with (Bad File Descriptor).
I've made the following configurations in php.ini file:
file_uploads = On
upload_max_filesize = 25M
post_max_size = 25M
Here is my code:
if ($_FILES["video"]["name"] == "") {
$error = "No video imported.";
}
else {
if (file_exists("uploads/" . $_FILES["video"]["name"])) {
$error = "The file already exists.";
}
else if ($_FILES["video"]["type"] != "video/mp4") {
$error = "File format not supported.";
}
else if ($_FILES["video"]["size"] > 26214400) {
$error = "Only files <= 25ΜΒ.";
}
else {
move_uploaded_file($_FILES["video"]["tmp_name"], "uploads/" . $_FILES["video"]["name"]);
}
}
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div class="area">
<label for="path">Select file:</label>
<input class="upload" type="file" name="video"></input>
<span><?php echo $error; ?></span><br />
</div>
</fieldset>
<input type="submit" name="insert" value="upload"></input>
</form>
You had a syntax error on line 4 & 5. It should be
} elseif (file_exists("uploads/" . $_FILES["video"]["name"])) {
Not:
} else {
if (file_exists("uploads/" . $_FILES["video"]["name"])) {
This code has been tested and is working.
<?php
if ($_FILES["video"]["name"] == "") {
$error = "No video imported.";
} elseif (file_exists("uploads/" . $_FILES["video"]["name"])) {
$error = "The file already exists.";
} elseif ($_FILES["video"]["type"] != "video/mp4") {
$error = "File format not supported.";
} elseif ($_FILES["video"]["size"] > 26214400) {
$error = "Only files <= 25??.";
} else {
move_uploaded_file($_FILES["video"]["tmp_name"], "uploads/" . $_FILES["video"]["name"]);
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div class="area">
<label for="path">Select file:</label>
<input class="upload" type="file" name="video"></input>
<span><?php echo $error; ?></span><br />
</div>
</fieldset>
<input type="submit" name="insert" value="upload"></input>
</form>

Image - Upload not responding, no access to $_FILES

Here is my file-upload script, and i am getting the following error
Notice: Undefined index: fupload in C:\Users\Tuskar\Desktop\Projekt\htdocs\Project IT-Space\Profile\edit_profile_parse.php on line 8
But according there should not error, because i identified the index. It seems i don't have access to the $_FILES array, because before i got this error ive been getting other similar errors or the programm completely passes the if and goes directly to the else (file not chosen)
I know the script is primitive and includes almost no security, but i just want it to work first before i add other features like max file size or file restriction ... :(
Here is the code i am using.
Upload Picture
<form action="edit_profile_parse.php" method="get" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
Here is the php that handles the form
if (isset( $_GET['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['sizw']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
You should use form method to POST instead of get.
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.
I hope this works:
the form:
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
the php file:
<?php
if($_POST) {
$max_size = mysql_real_escape_string(strip_tags($_POST['MAX_FILE_SIZE']));
$file = $_FILES['fupload']['name'];
if(isset($max_size) && !empty($max_size) && !empty($file)) {
$file_type = $_FILES['fupload']['type'];
$tmp = $_FILES['fupload']['tmp_name'];
$file_size = $_FILES['fupload']['size'];
$allowed_type = array('image/png', 'image/jpg', 'image/jpeg', 'image/gif');
if(in_array($file_type, $allowed_type)) {
if($file_size < $max_size) {
$path = 'images/'.$file;
move_uploaded_file($tmp, $path);
//if you want to store the file in a db use the $path in the query
} else {
echo 'File size: '.$file_size.' is too big';
}
} else {
echo 'File type: '.$file_type.' is not allowed';
}
} else {
echo 'There are empty fields';
}
}
?>
Upload Picture
<form action="edit_profile_parse.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
PHP file
<?php
if (isset( $_POST['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['size']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
?>

PHP image upload function, save in a dir and then return save image url

I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.
HTML:
<input name="photo" type="file" />
PHP
save_string_to_database( upload_img($_POST['photo']));
I have not much idea of PHP, I got a code from SO, but it did not do anything. Kindly help me to fix this code, or give a simple code to perform an upload:
function upload_img($img){
if ((($_FILES[$img]["type"] == "image/gif")
|| ($_FILES[$img]["type"] == "image/jpeg")
|| ($_FILES[$img]["type"] == "image/pjpeg")
|| ($_FILES[$img]["type"] == "image/jpg")
|| ($_FILES[$img]["type"] == "image/png"))
&& ($_FILES[$img]["size"] < 20000)
&& (strlen($_FILES[$img]["name"]) < 51)){
if ($_FILES[$img]["error"] > 0){
echo "Return Code: " . $_FILES[$img]["error"];
}
else{
// echo "Upload: " . $_FILES["image"]["name"] . "<br />";
// echo "Type: " . $_FILES["image"]["type"] . "<br />";
// echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
// echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
echo $_FILES[$img]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/" . $_FILES[$img]["name"]);
return THEME_DIR."/images/" . $_FILES[$img]["name"];
}
}
}
}
Here's a simple one.
HTML form to upload image
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Your PHP file that does the Upload
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Source
First you need a multipart/form-data form for uploading. This is a must :)
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
The PHP part is fairly simple:
This would result your file stored in "upload/{filename}"
The main part you want to consider is how to get the filename and back to your write_string_to_database procedure, you could do a simple script after the upload page like
save_string_to_database("upload/" . $_FILES["file"]["name"]);
would do the trick.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
for file upload try this
<?php if(isset($_POST['submit']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = 'images/';
$location = $path . $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $location);
} ?>
<form name="form1" id="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" name="submit">
</form>
This my function, variable $ten_anh is name of file image in html.
function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
if(isset($_FILES[$ten_anh])){
$errors= array();
$file_name = $_FILES[$ten_anh]['name'];
$file_size =$_FILES[$ten_anh]['size'];
$file_tmp =$_FILES[$ten_anh]['tmp_name'];
$file_type=$_FILES[$ten_anh]['type'];
$file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
}
if($file_size > 2097152){
$errors[]='Kích cỡ file nên là 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../images/".$file_name);
echo "Thành công!!!";
}
else{
print_r($errors);
}
}
}
Example:
- html code:
<input type="file" id="avatar" name="avatar"accept="image/png, image/jpeg" required/>
call function php: upload_anh('avatar');
<form method='post' action='' enctype='multipart/form-data'>
Name : <input type="text" name="name" required=""/><br><br>
Code : <input type="text" name="code" required=""/><br><br>
Price : <input type="text" name="price" required=""/><br><br>
Image : <input type="file" name="image" required=""/><br><br>
<button type='submit' class='buy' name="submit">Add Now</button>
</form>
<!--insert data -->
<?php
session_start();
include('db.php');
if(isset($_POST["submit"]));
{
/*echo "<pre>";
print_r($_POST);
print_r($_FILES);*/
$name = $_POST["name"];
$code = $_POST["code"];
$price = $_POST["price"];
$image = $_FILES["image"]["name"];
/* folder image save */
// $target_dir = "/var/www/html/shivam/new/upload/";
// $target_file = $target_dir.basename($_FILES["image"]["name"]);
// /*echo "1121".$target_file;*/
// $name = basename($_FILES["image"]["name"]);
// mysqli_query($con,$qry);
// /* move file */
// move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$name);
/* move_uploaded_file($tmp_name, "$target_dir/$name");*/
/* end */
$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
echo '44'.$uploadfile;
echo "<p>";
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';enter code here
print_r($_FILES);
print "</pre>";
}
?>

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories