Uploading file via PHP in form - php

(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>

Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));

when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();

Related

How do I get the full path of an image

I want the full path of a selected image to be displayed once Choose File button is clicked. Any idea on how to do that?
In your $_POST handling, use the following:
$fullpath = $_FILES["Name_Of_The_Input_Field_For_The_File"]["tmp_name"];
See Getting complete PATH of uploaded file - PHP for a similar issue.
Instead of doing a double POST, you can do something like this:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Remember, that just because you've selected a file to upload doesn't mean its been uploaded. The server still hasn't received the data, thus, doing this on the client side makes a little more sense from what i gather you want to do.
(stolen from: Preview an image before it is uploaded)

Upload a file in folder using PHP script

I am trying to upload and save an image using PHP scripting, but the image is not getting saved in the specified folder. Please help
here's my code:
<?php
if(isset($_POST['button'])){
$name= "product_name.jpg";
move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
header("location: tryupload.php");
}
?>
<html>
<body>
<form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
<table>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button"/>
</label></td>
</tr></table>
</form>
</body>
</html>
This part of your code enctype="multiple/form-data" is incorrect.
It needs to read as enctype="multipart/form-data".
Also make sure that the folder you intend on uploading to, has proper permissions to write to.
http://php.net/manual/en/features.file-upload.post-method.php
http://php.net/manual/en/function.chmod.php (setting folder/files permissions).
Uploading security-related links:
https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form
100% safe photo upload script
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
To upload multuple files you can have.
Multiupload.php
<? session_start()?>
<!DOCTYPE html>
<html>
<head>
<title>Blank</title>
<!-------Including jQuery from google------>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script.js"></script>
<!-------Including CSS File------>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<body>
<div id="formdiv">
<h1 class="uploadH2">Upload Your Artwork</h1>
<form enctype="multipart/form-data" action="" method="post">
Take a photo, upload your artwork, or choose an image from Facebook or Instagram
<label for="file">
<div id="image" style="margin-top:5%;">
<img src="img/camera.png">
</div>
</label>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" class="add_more" id="add_more" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "uploadScript.php"; ?>
</div>
</body>
</html>
uploadScript.php
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
<?
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = $path;
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png", "gif"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script will only accept, jpg, png, gif and jpeg. You can't upload or execute anything inside the directory unless you are owner and you can't have a file size bigger than 10KB.
script.js
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
else {}
});
});
This will upload multiple files, preview the image on the same page as the upload form, this will create a directory inside /uploads on the server with a directory matching the users session_id(). If the directory exists, the directory will be deleted, if it doesn't the directory will be created. The files will then be uploaded to that directory on the server.
You have incorrect enctype for the form. Instead of "multiple/form-data" use "multipart/form-data".

Preview an audio file before Post

I am new here apologies for any anomalies, The task I've been given is to create an image/audio file upload or link page with preview before POST.
Not sure how late I am but just discovered Html5 audio tag, I'd like to know how to preview an audio file on selection before upload.
here's my upload form:
<form id="attach" action="imageUpload.php" method="POST" enctype="multipart/form-data" >
<h2>Select An Audio File to Upload</h2>
<br>
<div>
<input type='file' id="files" name="files" multiple onchange="previewAudio(this);" />
<br>
<br>
<output id="list"></output>
<ul>
<li>
<label for="caption">Caption</label>
<input type="text" maxlength="30" name="caption" id="caption" />
</li>
<li>
<textarea id="desc" name="desc" rows="4" cols="32">Description
</textarea>
</li>
</ul>
<audio controls>
<source id="test3" src="" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<input type="submit" value="Upload"/>
</div>
</form>
here is the code I've been playing with tryin to get it to preview:
function previewAudio(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#test3').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
I'm most adamant that this should work but its not, any fixes or new methods will be highly appreciated
Thanks in advance.
Thanks JWarner that link was a nice starting point, learnt a lot in my almost 5 hours researching this and ended up finding a solution here Reading files in JavaScript using the File APIs
here is how I did it:
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('files').addEventListener('change', handleFileSelect,false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
var reader = new FileReader();
alert('e.target.result');
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '" width="230" height="270"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
}else if (f.type.match('audio.*')){
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<audio controls><source src="', e.target.result,' "type="audio/ogg"><source src="', e.target.result,' "type="audio/mpeg"></audio>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
}
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
} }, false);
Please point out any weak points in this code if there are any
Thank You
Here is something that may help you, allowing you to circumvent the use of Java and make use of bare HTML instead.
I also hope it doesn't insult you to point out that, I'm not sure there's a way to just "preview" a song, and that you may have to host shortened versions of the song that serve as preview-length, for your scripts to play, rather than having the code automatically truncate them.

Get SRC of image previewed in jquery

WHAT I'M DOING
I'm trying to implement profile picture changing in php/jquery. When an image is uploaded the preview of the image is shown.
WHAT I REQUIRE
I want to get the src of the previewed image. When i use $('img').attr('src'); it gives the src of the old image and not the new previewed image.
SCRIPT
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var image = $('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
HTML
<div class="pic">
<form id="form1" enctype="multipart/form-data">
<img src="profile.jpg" width="150" alt="profile" title="" id="img"/>
<span>Change Picture?</span>
<div class="up">
<input type='file' name ="file" id="imgInp" />
</div>
<input type="submit" name="picture" id="picture" value="Update"/>
</form>
</div>
There is a new security "feature" in IE 8 that hides the real path of the selected file from JavaScript calls (it returns c:\fakepath). This seems to only be activated for "Internet" servers ... not Local intranet servers...
See here for more information about C:\fakepath
Edit
Also, you should consider removing this line of code (you don't need it in your script)...
reader.readAsDataURL(input.files[0]);

ajax form data serialization failed

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you
change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php
You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

Categories