I'm trying to post a random value from a form's hidden input type.. but it's not posting any values..
using a function to post the values..
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
$('#multiple_upload_form').ajaxForm({
target:'#images_preview',
beforeSubmit:function(e){
$('.uploading').show();
},
success:function(e){
$('.uploading').hide();
},
error:function(e){
}
}).submit();
});
});
</script>
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="randnum" id ="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
and this is upload.php
if($_POST['image_form_submit'] == 1)
{
$rand = $_POST['randnum'];
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
I'm trying to store a random number every time the form gets posted...
You need to echo the value produced by mt_rand() like below:-
<input type="hidden" name="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
Note:- your code along with my change is working fine if i changed (form.js library file):-
<script type="text/javascript" src="jquery.form.js"></script><!--local URL-->
To:-
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script><!-- I used live URL -->
Instead of
<input type="hidden" name="randnum" id ="randnum"
value="<?php echo mt_rand(1000,10000000); ?>" />
You can generate after submitting form in php code
$rand=mt_rand(1000,10000000);
this will help you to generate key everytime you submit file to upload
if($_POST['image_form_submit'] == 1)
{
$rand = mt_rand(1000,10000000);
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
Please use try this,
Your ajax script is not working try this and check if opening and closing {} having error
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Bootstrap Starter</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
/*CUSTOM CODE HERE*/
</style>
</head>
<body>
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="randnum" id ="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type='text/javascript' src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
var formObj = $("#multiple_upload_form");
var formURL = formObj.attr("action");
var formData = new FormData(formObj[0]);
$('.uploading').show();
$.ajax({
url: formURL,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log(data);
$('.uploading').hide();
}
});
});
});
</script>
</body>
</html>
<?php
if($_POST['image_form_submit'] == 1)
{
$rand = $_POST['randnum'];
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
}
?>
Related
I need to upload the image to a server and store to the directory created by PHP using current timestamp. Below is the relevant part of the code, but not working as expected, it's not creating a folder as well it's not printing to the console. What could be the issue?
Edit:
Modified php based on below comment
upload.php
<?php
//get unique id
$up_id = uniqid();
?>
<?php
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$user = "user";
//console.log("debug.......");
echo "debug.......";
if (!file_exists("/var/www/Scan")) {
mkdir("/var/www/Scan", 0777, true);
}
$folderName = date("Y-m-d") . "_" . date("h_i_sa") . "_" . $user;
if (!file_exists("/var/www/Scan/$folderName")) {
mkdir("/var/www/Scan/$folderName", 0777, true);
}
$folder = "/var/www/Scan/$folderName";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
//
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
//document.getElementById("message").innerHTML = "";
});
//
});
</script>
</head>
<body>
<div id="outPopUp">
<h1 >Upload your file </h1>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<br />
<br />
<!--Choose a file to upload<br />-->
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $up_id; ?>"/>
<!---->
<!-- <input name="file" type="file" id="file" size="30"/>-->
<label class="custom-file-upload">
<input name="file" type="file" id="file" onclick="myFunction()" />
Choose Video
</label>
<!--Include the iframe-->
<br />
<br />
<iframe id="upload_frame" name="upload_frame" color= black frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<!---->
<br />
<input class="btn btn-blue" name="Submit" type="submit" id="submit" value="Submit" />
<br />
<br />
<?php if (isset($_GET['success'])) { ?>
<span style="color:#FFFFFF;" id="message" class="notice">Your file has been uploaded.</span>
<?php } ?>
</form>
</div>
<script>
function myFunction() {
document.getElementById("message").innerHTML = "";
}
/*document.getElementById('file').onchange = function () {
//alert('Selected file: ' + this.value);
var path = this.value;
var fileName = path.replace(/.*(\/|\\)/, '');
alert('Selected file: ' + fileName);
//myFunction(fileName);
};*/
</script>
</body>
</html>
try a simple example for understanding:
<?php
//php content
if ($_POST) { //here we are checking $_POST values that $_POST has some values.
//specify folder for file upload
$tempDir = __DIR__ . DIRECTORY_SEPARATOR . 'upload'; //it means make a directory uploads where this php file is kept.
if (!file_exists($tempDir)) { // if $tempDir is not there, so it will create that directory.
mkdir($tempDir);
}
if(!empty($_FILES))//now checking your uploaded file is not empty
{
$nm=$_FILES['file']['name']; //here $nm get the name of the file
$tmp=$_FILES['file']['tmp_name'];//$tmp get the temporary file stored path
$mDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR .time().$nm; //this your destination path with time+nameof file as a name of file.
if(move_uploaded_file($tmp,$mDir)) //uploading file to your destination path, if uploaded then it will go in the if scope and echo.
{
echo "file uploaded with timestamp in uploads folder";
//now redirect from here any where
}
else
{
echo "fail to upload a file";
}
}
}
?>
I've downloaded an image uploading script with Ajax from this Link
The codes are:
index.php
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + str+'<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
Uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result.",".$target_path; ?>);</script>
I want to show the url of uploaded image. So that it can be use instantly.
I've a little knowledge about ajex. I tried by writing two three of codes but it's not working.
Anyone can help to show the file url.
Thanks in advance.
Hope this helps...
index.php
<html>
<head>
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str, filename){
var result = '';
var file_link = '';
var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
file_link = "<br/><a href='"+directoryPath+"/"+filename +"'>"+filename+"</a><br/>";
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + file_link +'<br/><br/><label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="ajax-uploader.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
</body>
</html>
ajax-uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
$actual_name = basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.stopUpload(<?php echo "$result, '$target_path','$actual_name' "; ?>);</script>
change Uploader.php to upload.php.
Add php code after sleep as follows..
sleep(1);
$target_path = str_replace('\\', '/', $target_path);
$spath = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/".$_FILES['myfile']['name'];
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo "'".$result."','".$target_path.',img url :'.$spath."'";?>);</script>
I just made a file upload code and I was wondering why the file upload wasn't working? I checked the permission of my image folder in localhost and that seems to be ok. I don't know where the problem exactly is. Any ideas?
<?php
require "config.php";
require "functions.php";
require "database.php";
if(isset($_FILES['fupload'])){
$filename = addslashes($_FILES['fupload']['name']);
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
$description = addslashes($_POST['description']);
$src = $path_to_image_directory . $filename;
$tn_src = $path_to_thumbs_directory . $filename;
if (strlen($_POST['description'])<4)
$error['description'] = '<p class="alert">Please enter a description for your photo</p>';
if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename))
$error['no_file'] = '<p class="alert">Please select an image, dummy! </p>';
if (!isset($error)){
move_uploaded_file($source, $target);
$q = "INSERT into photo(description, src, tn_src)VALUES('$description', '$src','$tn_src')";
$result = $mysqli->query($q) or die (mysqli_error($myqli));
if ($result) {
echo "Succes! Your file has been uploaded";
}
createThumbnail($filename);
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>My photos</h1>
<ul><?php getPhotos(); ?></ul>
<h2>Upload a photo</h2>
<form enctype="multipart/form-data" action="index.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="fupload" /><br/>
<textarea name="description" id="description" cols="50" rows="6"></textarea><br/>
<input type="submit" value="Upload photo" name="submit" />
</form>
<?php
if (isset($error["description"])) {
echo $error["description"];
}
if (isset($error["no_file"])) {
echo $error["no_file"];
}
?>
</body>
</html>
Please make sure that you appended directory separator in $path_to_thumbs_directory.
And you don't need to use addslashes to $filename.
I have created a new way of uploading my images using two different php pages.
1 does the uploading while thye other does the cropping. Inpart it seems to work to an extent I had to set permissions on the folder it was saving to and it seemed to work but know it does not for some strange reason. It suppose to save a copy of the cropped image to the same folder but it does not seem to do that at the moment. I have no idea why it worked and has stopped working. I have been looking at the code for a while but for the life of me can't see the problem I am reletively new to php but it seems to be a solution to being able to upload images and crop them wether you are using IE 8,9 or the other browsers.
Here is the code for the upload.php section:
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
</head>
<body >
<?php
$folder = 'imgtest/';
$orig_w = 500;
if(isset($_POST['submit']) )
{
$imageFile = $_FILES['image']['tmp_name'];
$filename = basename( $_FILES['image']['name']);
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$orig_h = ($height/$width) * $orig_w;
$tmp = imagecreatetruecolor($orig_w,$orig_h);
imagecopyresampled($tmp, $src, 0,0,0,0, $orig_w,$orig_h,$width,$height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
$filename = urlencode($filename);
header("Location: crop.php?filename=$filename&height=$orig_h");
}
?>
<h1>php Upload Form</h1>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<label for="image">Image:</label>
<input type="file" name="image" id="image"/><br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Image!"/>
</p>
</form>
</body>
<script>
</script>
</html>
and here is the code for the crop section :
<?php
$folder = 'imgtest/';
$filename = $_GET['filename'];
$orig_w = 500;
$orig_h = $_GET['height'];
$targ_w = 120;
$targ_h = 100;
$ratio = $targ_w / $targ_h;
if (isset($_POST['submit']))
{
$src = imagecreatefromjpeg($folder.$filename);
$tmp = imagecreatetruecolor($targ_w, $targ_h);
imagecopyresampled($tmp, $src, 0,0,$_POST['x'],$_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
imagejpeg($tmp, $folder.'t_'.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
echo "<h1> Saved Thumbnail</h1> <img src=\"$folder/t_$filename\"/>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php crop form</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<script type="text/javascript" src="js/jquery-1.9.1.min.js" ></script>
<script type="text/javascript" src="js/jquery.Jcrop.js" ></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css"/>
<style type="text/css">
#preview
{
width: <?php echo $targ_w?>px;
height:<?php echo $targ_h?>px;
overflow:hidden;
}
</style>
</head>
<body >
<h1>Jcrop Plugin Behavior</h1>
<table>
<tr>
<td>
<img src="<?php echo $folder.$filename?>" id="cropbox" alt="cropbox" />
</td>
<td>
Thumb Preview:
<div id="preview">
<img src="<?php echo $folder.$filename?>" alt="thumb" />
</div>
</td>
</tr>
</table>
<form action="<?php echo $_SERVER['REQUEST_URI']?>" method="post">
<p>
<input type="hidden" id="x" name="x"/>
<input type="hidden" id="y" name="y"/>
<input type="hidden" id="w" name="w"/>
<input type="hidden" id="h" name="h"/>
<input type="submit" id="submit" value="Crop Image!"/>
</p>
</form>
</body>
<script type="text/javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: <?php echo $ratio?>,
setSelect:[0,0,<?php echo $orig_w.','.$orig_h;?>],
onSelect:updateCoords,
onChange:updateCoords
});
});
function updateCoords(c)
{
showPreview(c);
$("#x").val(c.x);
$("#y").val(c.y);
$("#w").val(c.w);
$("#h").val(c.h);
}
function showPreview(coords)
{
var rx =<?php echo $targ_w;?> / coords.w
var ry =<?php echo $targ_h;?> / coords.h
$("#preview img").css({
width: Math.round(rx*<?php echo $orig_w;?>)+'px',
height: Math.round(ry*<?php echo $orig_h;?>)+'px',
marginLeft: '-' + Math.round (rx*coords.x)+'px',
marginTop: '-' + Math.round(ry*coords.y)+'px'
});
}
</script>
</html>
Help would be greatly appreciated.
Headers(in this case location php headers) have to be sent before any content already echoed. So move your php part in your upload.php to top of that file:
<?php
$folder = 'imgtest/';
$orig_w = 500;
if(isset($_POST['submit']) )
{
$imageFile = $_FILES['image']['tmp_name'];
$filename = basename( $_FILES['image']['name']);
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$orig_h = ($height/$width) * $orig_w;
$tmp = imagecreatetruecolor($orig_w,$orig_h);
imagecopyresampled($tmp, $src, 0,0,0,0, $orig_w,$orig_h,$width,$height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
$filename = urlencode($filename);
header("Location: crop.php?filename=$filename&height=$orig_h");
}
?>
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
</head>
<body >
<h1>php Upload Form</h1>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<label for="image">Image:</label>
<input type="file" name="image" id="image"/><br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Image!"/>
</p>
</form>
</body>
<script>
</script>
</html>
Tell if its still not working.
I'm doing data entry program based on PHP every thing is working no issue (still under construction) but there is a problem that I can't find a solution. The issue is when the database doesn't have any data the image path wont get registered.
Now I'm using uplodify to upload an image file at the same moment I'm sending some data as well. The data contains a name, contact details and description this will directly be inserted to the DB and I also upload image which will get saved in to a folder and the name get saved in the database. But this processes are handled by two different PHP files one is AddPOIPro.PHP which handles the data adding and the uplodify.php to handle file upload and the updating of the file name.
The first issue I had was uplodify was not adding the file name in the same row as the submitted data so what I did was to get the last ID and decrement it by one and the updated the row that works when there is data but when theirs no data it fails. So what should I do to over come this. Below is my complete scripts thank you for your time.
Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
}
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendData").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="sendData" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Process PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
uplodify php
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
Please help.
To get Last id you can do Query As Like Following
SELECT `ID`
FROM `poiinfo`
ORDER BY `ID` DESC
LIMIT 0 , 1
If you face any more problem then you can knock me..
I think this would be a better approach
$("#sendData").click(function(){
//upload the file programatically (Method Call'upload')[http://www.uploadify.com/documentation/uploadify/upload/]
// echo the name of the uploaded file (make sure to rename the file for uniquiness)
// create a hidden element with the filename as the value inside the form
// call the ajax submit and submit the form. You can use (onuploadsuccess)[http://www.uploadify.com/documentation/uploadify/onuploadsuccess/] to trigger the element creation and ajax submit functions
});
You current implementation can cause issues consider,
Request 1 : ID 10
Upload 1 : ID 10
Request 2 : ID 11
Request 3 : ID 12
Upload 2 : ID 12
Upload 3 : ID 12
I found the Solution to my problem had some help form the guys in StackOverflow Below is my full code is any one is having the same problem similar to me you can use this code. And if it works for you pls put a vote for me thank you.
My Data Entry Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png'
});
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
$('#msg').delay(1500).fadeOut();
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
My DataProcess PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM dbname");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
This was really tricky the uploadify PHP but got it to work the way I want.
Uplodify PHP (My Version)
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
This script is working flawlessly now if some face the same situation which I faced use this and see if it works for you and you're allowed to make any changes as well.
Thank you.