How is this PHP/IFRAME file upload working? - php

Check out this link.
How is the code working out? I mean the src attribute of IFRAME is set to # then how does upload.php get to know that the form was submitted?
Here is the code : index.php :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Max's AJAX File Uploader</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<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){
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 + '<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>
</html>
upload.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;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>

The flow in this code is pretty simple if you follow the HTML form tag an it's related attributes. What is happening is the follwing:
Select upload
Submit form
The onSubmit() triggers a JS function which enables the loading.. visualization and disables the upload form. Because of the * return true* the form is still submitted.
The form submit is done into the iFrame because of the 'target=' attribute. With that action you make the iFrame source 'upload.php'
Upload.php is called from within the iFrame.
The Upload.php result calls the main window JS function 'stopUpload' which informs on the rest of actions to take.
This script will work although it's result might change cross browser. This is a good script for a fast AJAX upload implementation.

You have form action set to upload.php <form action="upload.php" hence when you submit upload.php knows form is submitted (if i understand your question correctly then above line is true)

Related

Uploading files to Google Cloud Storage in PHP

I've been trying to upload files to google cloud storage, but I couldn't.
Because createUploadUrl function is not returning any result.
My index.php is as follows.
<?php
require 'google/appengine/runtime/autoloader.php';
use google\appengine\api\cloud_storage\CloudStorageTools;
echo "DDDDDD";
$options = [ 'gs_bucket_name' => 'test-server.appspot.com' ];
$upload_url = CloudStorageTools::createUploadUrl('/upload.php', $options);
echo $upload_url;
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document upload</title>
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/multiupload.js"></script>
<script type="text/javascript">
var config = {
support : "text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document", // Valid file formats
form: "demoFiler", // Form ID
dragArea: "dragAndDropFiles", // Upload Area ID
uploadUrl: '<?php echo $upload_url; ?>' // Server side upload url
}
$(document).ready(function(){
initMultiUploader(config);
});
</script>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body lang="en">
<center>
<h1 class="title">Document File Upload</h1>
</center>
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Document File Here</h1>
</div>
<form name="demoFiler" id="demoFiler" enctype="multipart/form-data">
<input type="file" name="multiUpload" id="multiUpload" />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>
<div class="progressBar">
<div class="status"></div>
</div>
</body>
</html>
And my upload.php is as follows.
<?php
$filename = $_FILES['file']['name'];
$gs_name = $_FILES['file']['tmp_name'];
if (move_uploaded_file($gs_name, 'gs://test-server.appspot.com/'.$filename)) {
echo "succeed!";
} else echo "failed!";
?>
I think everything is fine, but the script is not working while executing createUploadUrl function.
Why is that?

submit should not redirect to another page in HTML form

I have a HTML form which reads some data and saves in the text file with help of PHP. The form's HTML code looks like below.
What is happening now:
1. once i click on submit button it redirects to the 'myprocessing.php'
2. successfully saving in data.txt
The help i required on
1. when i click on submit it shouldn't redirect me to the php page, it should stay on the HTML form page
2. it should show the php file's output on the same HTML page
In simple words, I want to stay on the HTML page itself. Since I'm pretty new to HTML and PHP, struggling much to do these. Thanks in advance :-)
<html>
<head>
<title></title>
</head>
<body>
<form action="myprocessing.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
This is my data prcoessing PHP file.
<?php
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
?>
Try below. Call refresh_div() on button click :-
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
</script>
Write php code in same html file and use isset() function to check for $_POST data
Try this
<?php
if(isset($_POST['field1']) && isset($_POST['field2']))
{
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="current_page.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST" name="testForm" id="testForm">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
<div class="result"></div>
</body>
</html>
add the name and id for form tag. if you keep action as blank, it will submit your form to current page itself.
You need a ajax call to perform as per your requirement.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( "#testForm" ).on( "submit", function( event )
{
$.ajax({
url:'myprocessing.php',
type:'POST',
data: $("#testForm").serialize()
success:function(results) {
jQuery(".result").html(results);
}
});
return false;
});
</script>
Dont forget to put a return false at the end. If we dont put return false, it will submit your form after the ajax call.

PHP with jQuery simple upload with process bar

I am trying to put on דוגמנות website that Simple PHP Upload Progress Bar script
APC is already installed on your server and I have tweaked my php.ini as described on the instructions.
apc.rfc1867 = on
Now the problem is that I am getting a %NaN instead of the real number from the upload process.
I know that this script IS working on some other servers so I am going to assume that there is no bug on the script and it's just something related to the php.ini or to the APC.
This is my upload.php file:
<?php
//get unique id
$up_id = uniqid();
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$folder = "tmp/";
//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);
}
});
});
</script>
</head>
<body>
<h1>Upload your file </h1>
<div>
<?php if (isset($_GET['success'])) { ?>
<span class="notice">Your file has been uploaded.</span>
<?php } ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Name<br />
<input name="name" type="text" id="name"/>
<br />
<br />
Your email address <br />
<input name="email" type="text" id="email" size="35" />
<br />
<br />
Choose a file to upload
<br />
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?=$up_id?>"/>
<input name="file" type="file" id="file" size="30"/>
<!--Include the iframe-->
<br />
<iframe id="upload_frame" name="upload_frame" frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<input name="Submit" type="submit" id="submit" value="Submit" />
</form>
</div>
</body>
</html>
this is my upload_frame.php
<?php
$url = basename($_SERVER['SCRIPT_FILENAME']);
//Get file upload progress information.
if(isset($_GET['progress_key'])) {
$status = apc_fetch('upload_'.$_GET['progress_key']);
echo $status['current']/$status['total']*100;
die;
}
//
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function() {
//
setInterval(function()
{
$.get("<?php echo $url; ?>?progress_key=<?php echo $_GET['up_id']; ?>&randval="+ Math.random(), {
//get request to the current URL (upload_frame.php) which calls the code at the top of the page. It checks the file's progress based on the file id "progress_key=" and returns the value with the function below:
},
function(data) //return information back from jQuery's get request
{
$('#progress_container').fadeIn(100); //fade in progress bar
$('#progress_bar').width(data +"%"); //set width of progress bar based on the $status value (set at the top of this page)
$('#progress_completed').html(parseInt(data) +"%"); //display the % completed within the progress bar
}
)},500); //Interval is set at 500 milliseconds (the progress bar will refresh every .5 seconds)
});
</script>
<body style="margin:0px">
<!--Progress bar divs-->
<div id="progress_container">
<div id="progress_bar">
<div id="progress_completed"></div>
</div>
</div>
<!---->
</body>
and this is my style_progress.css
/*iframe*/
#upload_frame {
border:0px;
height:40px;
width:400px;
display:none;
}
#progress_container {
width: 300px;
height: 30px;
border: 1px solid #CCCCCC;
background-color:#EBEBEB;
display: block;
margin:5px 0px -15px 0px;
}
#progress_bar {
position: relative;
height: 30px;
background-color: #F3631C;
width: 0%;
z-index:10;
}
#progress_completed {
font-size:16px;
z-index:40;
line-height:30px;
padding-left:4px;
color:#FFFFFF;
}
Let me know if there is a quick fix for that.
Where did you call apc_store()? I'm pretty sure this needs to be done before you can fetch the value using apc_fetch().

iframe Url search

I want to make a url search input for an iframe with HTML (and maybe JS).
I searched in alot of site and I didn't found.
Does anyone know how?
I think I'll need to use something like
<form action="http://" method="get" target="myiframe">
<input id="search" type="text">
</form>
?
You can use jQuery:
// Send search form data
$("#searchFormId").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get search form input field value
var s = $('#inpuFieldId').val();
// update iframe url
$('#iframeid').attr('src', 'http://example.com?formvalue='+s);
}
);
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Update iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body id='body'>
<div><form action="" method="get" id="myform"> <input id="search" type="text" /><input type="submit" value="go" /> </form></div>
<div align="center"><iframe name="MyIframe" id="myiframe" src="" width="980" height="500" scrolling="yes" frameborder="0"></iframe><div>
<script>
// Send search form data
$("#myform").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get search form input field value
var s = $('#search').val();
// update iframe url
$('#myiframe').attr('src', 'http://jquery.com/?s='+s);
}
);
</script>
</body>
</html>

How to call external javascript file in PHP?

I am learning how to call external javascript files in my PHP code. I got some codes from the internet and tried it but its not working. Can somebody pls give me some advice or explain to me this. I am not a programmer but I am studying how to program and just started learning that's why I have difficulty understanding some concepts.
I have here the codes, PHP File and JS file. They are in the same folder.
Here are the codes:
index.php
<html>
<head>
<script language="JavaScript" src="exer_1.js"></script>
</head>
<body>
<form name="myform">
<input type="text" id="input_1" name="input_1" /><br />
<input type="text" id="input_2" name="input_2" /><br />
<input type="submit" value="Check!" onclick="javascript:parseTest() return false;" />
</form>
</body>
</html>
exer_1.js
function parseTest() {
var elem_1 = document.getElementById('input_1');
var elem_2 = document.getElementById('input_2');
var inp_1 = elem_1.value;
var inp_2 = elem_2.value;
if (inp_1 == "" && inp_2 == "") {
alert("You need to enter integers!!!");
elem_1.focus();
} else if (inp_1 == ""){
alert("You need to enter Integer 1!!!");
elem_1.focus();
} else if (inp_2 == ""){
alert("You need to enter Integer 2!!!");
elem_2.focus();;
} else {
if (!parseInt(inp_1) || !parseInt(inp_2)) alert ("Enter Integers only!!!");
else {
alert("Correct Inputs!!!");
}
}
}
<script language="JavaScript" src="exer_1.js"></script>
The language attribute is deprecated, use type instead
<script type="text/javascript" src="exer_1.js"></script>
The correct syntax for inline event binding is
<input type="submit" value="Check!" onclick="parseTest(); return false;" />
You may want to consider moving the event handler to the form's submit event. Your function could then return false on error or true on success, which can then be used to determine whether the form submission continues or not, eg
<form onsubmit="return parseTest()">
You have not really specified what is not working but i am noticing something in your code.
<html>
<head>
<script language="JavaScript" src="exer_1.js"></script>
</head>
<body>
<form name="myform">
<input type="text" id="input_1" name="input_1" /><br />
<input type="text" id="input_2" name="input_2" /><br />
<!-- The following will cause an error -->
<input type="submit" value="Check!" onclick="javascript:parseTest() return false;" />
<!-- instead use this -->
<input type="submit" value="Check!" onclick="javascript:parseTest(); return false;" />
</form>
</body>
</html>
semicolon error
I would look into JQuery for a nice javascript framework. Instead of putting javascript code on the button's "onclick" event, with jquery you could do something like:
$('#submit').click(function() {
// whatever code you want to run when submit is clicked.
alert('Submit clicked');
}
<script type="text/javascript" src="exer_1.js"></script>

Categories