How do I upload an image using PHP? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How do I upload an image and store it into a cookie? I want to be able to upload an image with limitations on e.g. file size restrictions.
Here is my PHP code:
<?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;
}
}
// 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.";
}
}
?>
In this code is the function to upload a file with restrictions on.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<link href="bitnami.css" media="all" rel="Stylesheet" type="text/css" />
<link href="test.php"/>
</head>
<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>

You have multiple faults in your logic.
1) You never check if an upload was actually performed. You just start working on the ['tmp_name'] without ever checking if it actually exists. Your FIRST action on processing an upload must be to check for errors:
if ($_FILES["fileToUpload"]['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileToUpload']['error']);
}
2) You're checking file types based on filename extensions. Nothing says a user can't do ren nastyvirus.exe cutekittens.jpg and get through your filename check. You're already using getimagesize() later on, so the extension check is pointless:
$info = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($info === false) {
die("Not an image at all");
}
if (($info[2] != IMGTYPE_GIF) && ($info[2] != IMGTYPE_JPG) && ($info[2] != IMGTYPE_PNG)) {
die("Not a gif/jpg/png");
}
if (($info[0] > $maximum_width) || ($info[1] > $maximum_height)) {
die("Too tall/wide");
}
And then, after all that - why store it in a cookie? Cookies are naturally limited in the maximum amount of data that can be stored. You shouldn't exect to be able to store more than a couple kilobytes at most. Since you've set your upload size limit at 500k, you WILL end up with corrupted/truncated images if you do store a 500k into that 1-2k cookie.

Related

How to get image src in php/javascript

I have an HTML image tag with the source blank. The source will change based on input type file when the user uploads an image. So how do I get the image source? I can't hardcode the source as it will change based on what the user selects.So i want to retrieve the image src based on the file user has selected.
Here are the codes i used:
i want to get the image directory by retrieving image src so i can check if there's an XML file created in the folder which has the same name as the image.
thank you
I believe the PHP code you are specifically asking for is
$_FILES["fileToUpload"]["name"]
However, take a look at the tutorial from w3schools.
HTML upload form
<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 uploader
<?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 = 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;
}
}
?>

PHP - Auto-submit forms in PHP using onchange

I am trying to create a form where when the user chooses a file, the file chosen will automatically upload to the database by going to the action in form. I used the onchange function and it just sends me to my php file in which that file contains my uploading system. What i think my problem is about my $_POST['asdasd'], but i cant really think of any other solutions to this.
Here is my form:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
The PHP File:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$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["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$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. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
It is not saving because in the php file you have the line
if (isset($_POST['submit'])) {
add in the form a hidden field
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
<input type="hidden" name="submited" value="1" />
</form>
And in php change the line
if (isset($_POST['submit'])) {
to
if (isset($_POST['submited'])) {
That should do it
Instead of doing the $_POST['submit'] validation, try to check if the request is a $_POST.
To do that you can use something like
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
or
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
i recommend you to use the first one.
PHP doc: http://php.net/manual/pt_BR/function.filter-input.php

How to call a php function from javascript alert

Basically what i am trying to do is- create a page to upload file. Below is the code and its working fine:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function wow_default_alert() {alert("Successfully saved!"); }
</script>
</head>
<body>
<form action="index.php" method="post" name="myForm" 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
if(isset($_POST["submit"])) {
if (!file_exists('.\\tigerimg\\'))
{
mkdir('.\\tigerimg\\', 0777, true);
}
$target_dir = '.\\tigerimg\\';
$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
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
"File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
"File is not an image.";
$uploadOk = 0;
}
// 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.";
echo '<script type="text/javascript">
wow_default_alert();
</script>';
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
But the problem is that if i refresh the page again -after uploading one file successfully, it works with the same post values.
Previously i used the below code to unset post data-which worked for other pages.
clear Code-1
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
But i cant use it in this one. It shows error:
Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62
So, i tried to also clear the FILES array too by adding 3 lines with the above code.
clear Code-2
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
$_SESSION['filedata'] = $_FILES; //new code
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
$_FILES = $_SESSION['filedata']; //new
unset($_SESSION['postdata']);
unset($_SESSION['filedata']); //new
}
?>
But now its showing only one error:
Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51.
>>> So, here is one question- why is this happening?
Ok, now i tried another way put the above [clear Code-1] inside a php function function remove_post() and call it just after the code of successful uploading- where i called the alert.
This time its working fine. But now the problem is that the alert doesn't appear. So, is it possible to call the function remove_post() when user clicks the ok in alert.
It looks like you are trying to copy from W3Schools web site, which is not the greatest of places. At any rate, in this instance, I think you may want to do all your processing at the top of your page like so:
<?php
// Not sure if you are storing anything in sessions...
session_start();
// Create a root
define("ROOT_DIR",__DIR__);
// Create a function so you can customize it if you want to
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif"))
{
// Make directory if not exists
if(!is_dir($mkdir = ROOT_DIR.$dir)) {
if(!mkdir($mkdir,0755,true))
return 'mkdir';
}
// Filter filename
$name = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]);
// Assign name
$filename = (!empty($name))? $name : false;
// If empty, record error
if(!$filename)
$error[] = 'nofile';
// Get mime type
$mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false;
// Record if invalid
if(!$mime)
$error[] = 'invalid';
// Filter out double forward slashes (if user decides to change $dir)
// and adds too many forward slashes
$final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename);
// If file exists, record error
if(is_file($final))
$error[] = 'exists';
// If too big record error
if($filename > 500000)
$error[] = 'size';
// If not in the allowed file types, record error
if(!in_array($_FILES["fileToUpload"]["type"],$allow))
$error[] = 'type';
// Return array of errors
if(!empty($error))
return $error;
// True or false if no errors are recorded previously
return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final));
}
// Just create a simple error returning function
// This is expandable by adding error descriptions stored in database if desired
function ErrorReporting($value = false)
{
$msg['invalid'] = "INVALID File!";
$msg['type'] = "The file you are trying to upload is not a valid image type.";
$msg['exists'] = "The file you are trying to upload is already uploaded.";
$msg['size'] = "The file you are trying to upload is too large.";
$msg['nofile'] = "The file you are trying to upload has no name.";
if($value === true)
return "Successfully uploaded!";
elseif(is_array($value)) {
foreach($value as $error) {
$err[] = (!empty($msg[$error]))? $msg[$error]:"";
}
if(!empty($err))
return implode("",$err);
}
else
return "File failed to upload.";
}
// If post is submitted
if(isset($_POST["submit"]))
// Run the uploader function
$success = SaveFileToDisk();
?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
<?php
// if there is an upload, run the js alert
if(isset($success)) {
?>
function error_alert(errmsg)
{
alert(errmsg);
}
error_alert("<?php echo ErrorReporting($success); ?>");
<?php }
?>
</script>
</head>
<body>
<form action="" method="post" name="myForm" 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>
After user clicks OK for alert you can call the php function as
alert('Your alert');
document.write(' <?php remove_post(); ?> ');
Your remove_post() function will get called after user click OK on alert

Image Upload Not Working (Froala Editor)

I have read the Froala Help Docs over 10 times now. I still can't get it to work :(
When I click the upload icon in my editor and select an image to upload, nothing happens. The dialog box that asks you to choose an image pops up, and after selecting the image, it dismisses but nothing happens on the page afterwards.
It's definitely something wrong with my code. However, I can't figure out what it is.
My view page:
<textarea id="edit" name="message"> </textarea>
My js:
$(function() {
$('#edit').editable({
height: 400,
imageUploadURL: '/assets/upload_image.php',
imageUploadParams: {id: "edit"},
imageUploadParams: {id: "edit"},
placeholder: "Write something...",
inlineMode: false
})
});
My upload_image.php file:
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "http://localhost/assets/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/assets/uploads/" . $name;
echo stripslashes(json_encode($response));
}
What I have tried to fix this issue:
In upload_image.php, I have replaced the upload folder path (original: http://localhost/assets/uploads/ to just uploads and created an uploads folder in that directory. Still no luck.
I have tried placing all the files together in the same folder but no luck.
Any help is highly appreciated.
I have gone through the same issue and I am sharing working code for you.
index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/froala_editor.css">
<style>
body {
text-align: center;
}
div#editor {
width: 81%;
margin: auto;
text-align: left;
}
</style>
</head>
<body>
<div id="editor">
<form method="post">
<textarea id='edit' name='edit' style="margin-top: 30px;" placeholder="Type some text">
<h1>Textarea</h1>
<p>The editor can also be initialized on a textarea.</p>
</textarea>
<input name="submit" type="submit">
</form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/froala_editor.min.js"></script>
<script type="text/javascript" src="js/plugins/image.min.js"></script>
<script>
$(function() {
$('#edit').froalaEditor({
height: 300
})
});
</script>
</body>
</html>
upload_image.php
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
/* if you want to check extension of a file, then please remove the below if condition */
/*if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {*/
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/test/editor-3/html/uploads/" . $name;
echo stripslashes(json_encode($response));
//}
?>
Now Open included javascript file image.min.js and just find and change the imageUploadURL parameter to url of your upload_image.php file, in my case, it is:
imageUploadURL: "http://localhost/test/editor-3/html/upload_image.php",
I am going to add an answer here because for one Froala's documentation is terrible. I had experienced multiple issues with both image and file uploads and spent many hours going crazy till after a few weeks I finally figured out the issue and hope this can help someone else.
First
fileAllowedTypes: ['*']
documentation
The following Froala specifies that this option will allow any file type to be uploaded...wrong. The thing that Froala is not telling you is that in order to be able to upload any file type you have to specify the extension of the file as well as the MIME-type. If you don't reguardless of this option it will not work. It will only allow PDF and TXT.
What to do
When you download the Froala SDK you need to head over to
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/File.php //for File upload
and
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/Image.php //for Image upload
In those files you will see something like
'allowedExts' => array('zip', 'txt', 'pdf'),
'allowedMimeTypes' => array(
'text/plain',
'application/pdf',
'application/zip'
)
This is where you need to add your extensions and MIME-types that you want to allow. You must specify both the extension and MIME-type of the file.
If you are having trouble finding the MIME-type of a particular file just use this site.
I am guessing that this might apply to other languages as well or at least be a similar solution but I can confirm this for php
Hope this helps someone out in the future.

Multi-Step Form with File Upload

I have a multi-step form. What I want to achieve here is to allow user to upload a file (with some validation using jquery.validate plugin) and store the file to mySQL database.
Previously, I wasnt using multi-step form design (a one-page per step design instead) and therefore when user clicked the "submit" button, I would have if(isset($_POST['submit'])) and $_FILES to validate the file through PHP. Below is the PHP code that will be triggered when user clicked "submit" button .
if(isset($_POST['submit']))
{
$allowedExts = array("mov", "mp4", "mpeg", "wmv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "video/quicktime") || ($_FILES["file"]["type"] == "video/mp4") || ($_FILES["file"]["type"] == "video/mpeg") || ($_FILES["file"]["type"] == "video/x-ms-wmv")) && in_array($extension, $allowedExts) && (!empty($_POST["title"])) && (!empty($_POST["description"])))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// check if the file already exist in Uploaded folder
if (file_exists("uploaded/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"]." already exists. ";
}
else
{
echo "<br />".$_FILES["file"]["name"]." has been uploaded! <br /><br />";
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type: ".$_FILES["file"]["type"]."<br />";
echo "Size: ".($_FILES["file"]["size"] / 1024)." kB<br />";
echo "Stored in: "."uploaded/".$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded/".$_FILES["file"]["name"]);
$name = $_FILES["file"]["name"];
$url = ""; //some URL
mysql_query("INSERT INTO video (name, title, description, url) VALUES ('$name', '$title', '$description', '$url')") or die(mysql_error());
}
}
}
else
{
if (!empty($_POST["description"]) && (!empty($_POST["title"])))
{
echo "Invalid file";
}
}
}
But now, since I have change my design to multi-step form, this logic seems not working anymore. This is my fiddle.
I was thinking to change the "Upload" button type from type="button" to type="submit"so that I can use my old PHP logic to process the file and upload to database, however this causes my multi-step form to stop going to the next step.
Any brilliant ideas or suggestions?
If you want to avoid page reloads, you could try posting the form through a hidden iframe and then reading the response on load. As far as I know this should work in all browsers
<iframe name="target_iframe">..</iframe>
<form target="target_iframe">..</form>
Check out How do you post to an iframe?
If you're happy dropping support for older browsers you can post files using ajax. Maybe check out using html5 for file upload with ajax and jquery

Categories

Resources