I am trying to validate the file when it is uploading, I am using the following code to achieve it, but I am not getting the desired output.
Even though I am uploading the allowed extension types, I am still getting the echo message "You cannot upload files of this type!". which means the If conditionif (in_array($fileActualExt, $allowed, true)) is not getting true,
thanks in Advance for helping me,
<?php
if(isset($_POST['submit'])) {
if (!empty ($_FILES['file'])){
$fileName = $_FILES['file']['name'];
$fileTempName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed, true)) {
if ($fileError === 0) {
if ($fileSize <8000) {
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTempName, $fileDestination);
header("location: player_home.php?uploadSucess");
echo "success";
}else{
echo "your file is too big";
}
}else{
echo "There was an Error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
}
?>
HTML CODE
<form method="post">
<div class="form-group">
<input type="file" name="file">
</div>
<span class="sml">Maximum size of <span>8.0MB</span> for a file.
<br>
Allowed Types : jpg, jpeg, png
</span>
<br>
<button class="btn btn-primary" type="submit" name="submit" style="margin-top:15px;">Save</button>
</form>
You may be tripping with the true option in the in_array() method. Remove that and the condition should work.
Related
I have made a form on php and I am adding an image input option there.
<form action="./assets/actions/gallery_post.php" id="upload-form" method="POST">
<input type="text" name="title" placeholder="Image title..." class="form-control" required>
<br>
<input type="text" name="description" placeholder="Image description..." class="form-control">
<br>
<input type="file" name="file", class="form-control" required>
<br>
<button type="submit" name="picture-submit" class="form-control submit">Upload Photo</button>
</form>
The following is my php code to upload the file.
// Check if the button was pressed
if (isset($POST['picture-submit'])) {
echo "Entered";
// Get the inputs
$newfilename = 'gallery';
$title = $_POST['title'];
$description = $_POST['description'];
$file = $_FILES['file'];
if($file){
echo "FILE";
}else{
echo "No File found";
}
console.log($file);
// Obtaining some file information
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileError = $file['error'];
$fileType = $file['type'];
// Checking file extensions
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
echo "$fileActualExt";
// Allowed extensions
$allowed = array('jpeg', 'jpg', 'png', 'JPG');
// if extension is allowed
if(in_array($fileActualExt, $allowed)){
// check if any error
if($fileError === 0){
// Creating a unique file name
$fileNew = $newfilename. "." . uniqid('', true) . "." . $fileActualExt;
$fileDest = "assets/images/gallery/" . $fileNew;
// Function to upload file
move_uploaded_file($fileTmpName, $fileDest);
// Making a database connection
include_once ('dbh.php');
$stmt = mysqli_stmt_init($conn);
// Move to the database as well using prepared statements
$sql = "INSERT into gallery(location, title, description) VALUES(?, ?, ?)";
echo $sql;
// Binding parameters
mysqli_stmt_bind_param($stmt, "sss", $fileDest, $title, $description);
mysqli_stmt_execute("$stmt");
// Perform a query, check for error
mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "Query Sent";
header("Location: ../gallery.php?upload=sucess");
}else {
echo "There was an error in file upload.";
}
}else {
echo "You cannnot upload files of this type!";
}
}
It is not even entering the if condition in the above scenario. When I remove the if condition, I get "No file Found". Sort of stumped here now because I have made it work in the past. I even tried the basic HTML query format like this mysqli_query($conn, $sql) or die(mysqli_error($conn)); and this does not work either.
Your form tag has to be enabled enctype="multipart/form-data".
Try this code.
<!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>
<?php
$target_dir = "uploads/";
$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 if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$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.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
I'm trying to upload files to be more precise images from my web-pages to my webserve but it doesn't work. If i do it locally everything works fine but on the Server it doesn't work.
It doesn't give me out any Error message and i don't know why either.
I've tried to give the right permissions and it didn't work it. I tried another way to program it and it didn't work either. It always shows my first else-loop.
<?php
$SBA_ID = $_GET['SBA_ID'];
if (isset($_POST['submit'])) {
$file = $_FILES['my_file'];
print_r($file);
$fileName = $_FILES['my_file']['name'];
$fileTmpName = $_FILES['my_file']['tmp_name'];
$fileSize = $_FILES['my_file']['size'];
$fileError = $_FILES['my_file']['error'];
$fileType = $_FILES['my_file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'pdf');
if(in_array($fileActualExt, $allowed)){
if ($fileError === 0) {
if($fileSize < 1000000){
$fileNameNew = "Auftrag".$SBA_ID.".".$fileActualExt;
$fileDestination = 'AuftragFotos/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
header("refresh:2;url= ../Startseite.php");
}else {
echo "Your File is too big!";
}
}else {
echo "There was an error uploading your file!";
}
}else {
echo "You cannot uplaod files of this Type";
}
}
My Form
<form action="<?php echo"speichern/Fotospeichern.php?SBA_ID=$SBA_ID"?>"
method="POST" enctype="multipart/form-data">
<input type="file" name="my_file"/>
<button type="submit" name="submit">UPLOAD</button>
</form>
I expect the output to be that the Image is uploaded to the "AuftragFotos" Dir but it always shows: "You cannot upload files of this Type" even though i specified that Type of file to uploaded.
You have a problem with string escaping.
Change:
<form action="<?php echo "speichern/Fotospeichern.php?SBA_ID=$SBA_ID"?>"
method="POST" enctype="multipart/form-data">
<input type="file" name="my_file"/>
<button type="submit" name="submit">UPLOAD</button>
</form>
to:
<form action="speichern/Fotospeichern.php?SBA_ID=<?php echo $SBA_ID; ?>"
method="POST" enctype="multipart/form-data">
<input type="file" name="my_file"/>
<button type="submit" name="submit">UPLOAD</button>
</form>
I wanted to create a PHP code that allows me to upload a photo to my website. The problem is first time I clicked the upload button, the message was " Succes" but no file into my folder, and second time I didnt change the code, it throws me and error message. Can you please look over and tell me if I did something wrong?
<?php
if(isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg','png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
if($fileSize < 2048000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/images'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: profile.html?upload=succes");
} else {
echo "Your file is too big!";
}
} else {
echo " There was an error uploading your file!";
}
}else {
echo "You cannot upload files of this type!";
}
}
I got the error "There was an error uploading your file " .
HTML FORM
<form action="upload.php" method="POST" enctype="multipart/form-data">
<span> Change Profile Picture</span>
<input class="btn btn-default btn-rounded mb-4" type="file" name="file">
<button class="btn btn-default btn-rounded mb-4" type="submit" name="submit">Upload</button>
</form>
When i hit the print_r($file);
It throws me `Array ( [name] => IMG_6389.jpg [type] => [tmp_name] => [error] => 1 [size] => 0 )
` I got the error 1 instead of 0
This is a problem of filesize. You have to increase the maximum size of an uploaded file in php.ini.
Error 1 is UPLOAD_ERR_INI_SIZE:
The uploaded file exceeds the upload_max_filesize directive in
php.ini.
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 a script:
if(isset($_FILES['image'])){
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILE['image']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILE['image']['size'];
$file_tmp = $_FILE['image']['tmp_name'];
if(in_array($file_ext, $allowed_ext) === false){
$errors[] = 'Extension not allowed';
}
if($file_size > 2097152){
$errors[] = 'file size must be under 2mb';
}
if(empty($errors)){
if(move_uploaded_file($file_tmp, "../../img/usr/profile/.$file_name")){
echo 'File uploaded';
}
}else{
foreach($errors as $error){
echo $error, '<br>';
}
}
}
And it's not working. It is supposed to upload an image to a certain directory. Here's the html:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="submit" value="Update Info">
</form>
When I click submit, there is an error at the top of the screen saying 'Extension not allowed'. The html and php is in the same file (I just gave you a small snippet.) Does anything look wrong with my code? thanks!
To access the files, you have to use the $_FILES variable.
In your code, you have sometimes used $_FILE, which does not work ;)