I'm new to php and javascript...So I don't really know how to achieve my goal. Here I have 2 php files,
first file :
<?php
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
</div>
<label>Foto Tamu</label>
<!-- form yang akan menempatkan jendela webcam untuk menampilkan layar webcam ya....-->
<p>
<script language="JavaScript" name="foto" id="foto">
document.write( webcam.get_html(320, 240) );
webcam.set_api_url( '../camera/saveImage.php' );
webcam.set_quality( 90 ); // JPEG quality (1 - 100)
webcam.set_shutter_sound( true ); // play shutter click sound
webcam.set_hook( 'onComplete', 'my_completion_handler' );
<!-- record gambar -->
function take_snapshot(){
webcam.freeze();
var x;
if (confirm("Simpan gambar?") == true) {
x = "Menyimpan gambar ...";
webcam.upload()
} else {
x = "Gambar tidak tersimpan.";
webcam.reset();
}
document.getElementById("upload_results").innerHTML = x;
}
function my_completion_handler(msg) {
// extract URL out of PHP output
if (msg.match(/(http\:\/\/\S+)/)) {
// show JPEG image in page
document.getElementById('upload_results').innerHTML ='Penyimpanan berhasil!';
// reset camera for another shot
webcam.reset();
}
else {
alert("PHP Error: " + msg);
}
}
</script>
</p>
<p>
<input type="button" class="btn btn-warning" value="Ambil Gambar" onclick="take_snapshot()">
echo $GLOBALS['$imagename'];
</p>
?>
and the second php file is like this :
<?php
session_start();
// untuk membangun koneksi ke database
include '../config/connect.php';
$imagename = $GLOBALS['nama_tamu'].date('YmdHis');
$newname="../camera/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "ERROR: Gagal menyimpan $filename, cek permissions \n";
exit();
}
else
{
// menyimpan gambar ke database
$sql="Insert into entry(camera) values('$newname')";
$result=mysqli_query($con,$sql) or die("error sql connect");
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
My goal here is I want to send nama_tamu (first php file) value to saveImage.php (second php file) buuut because saveImage.php is called withouth using POST or GET method, so I'm using GLOBALS variable there :
$imagename = $GLOBALS['nama_tamu'].date('YmdHis');
Unfortunaly it doesn't work, and I have no idea how to send this nama_tamu value to saveImage.php... Any idea...???
The second goal is in saveImage.php there is a variable called $imagename. I want to send it's value back to the first php file and print it to the user like this :
echo $GLOBALS['$imagename'];
That doesn't work too...May be because GLOBALS only work for the same file not for different file....!
So any idea how to achieve my two goals here..???
Thanks in advance, I really appreciate your help... :)
Related
I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.
For example, I'd like to select a series of images and then upload them to the server, all at once.
It would be great to use a single file input control, if possible.
Does anyone know how to accomplish this?
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:
<form enctype="multipart/form-data" action="post_upload.php" method="POST">
Then the key to success;
<input type="file" name="file[]" multiple />
do NOT forget those brackets!
In the post_upload.php try the following:
<?php print_r($_FILES['file']['tmp_name']); ?>
Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:
$_FILES['file']['tmp_name'][0]
You can use php count() to count the number of files that was selected. Goodluck widdit!
Full solution in Firefox 5:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
in the first you should make form like this :
<form method="post" enctype="multipart/form-data" >
<input type="file" name="file[]" multiple id="file"/>
<input type="submit" name="ok" />
</form>
that is right . now add this code under your form code or on the any page you like
<?php
if(isset($_POST['ok']))
foreach ($_FILES['file']['name'] as $filename) {
echo $filename.'<br/>';
}
?>
it's easy... finish
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.
If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.
Update:
There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.
http://swfupload.org/
If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))
partial answer: pear HTTP_UPLOAD can be usefull
http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
i have created a php function which is used to upload multiple images,
this function can upload multiple images in specific folder as well it can saves the records into the database
in the following code
$arrayimage is the array of images which is sent through form
note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
$dir is the directory in which you want to save the image
$fields is the name of the field which you want to store in the database
database field must be in array formate
example
if you have database imagestore and fields name like id,name,address then you need to post data like
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
$table is the name of the table in which you want to store the data..
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code
I've tried the following code for capture a image, it stores image in specified folder but the path of image which i want to store in database doesn't work.The execution of code stops after Uploding... message.Please help me,whats going wrong with my code.
<!--test.php-->
<?php
session_start();
include 'connection.php';
$name = date('YmdHis');
$newname=mysql_real_escape_string("images/".$name.".jpg");
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "ERROR: Failed to write data to $filename, check permissions\n";
exit();
}
else
{
$sql="Insert into entry(images) values('$newname')";
$result=mysql_query($con,$sql)
or die("Error in query");
$value=mysql_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
<!--index.php-->
<?php
session_start();
if(isset ($_POST["send"]))
{
$getname=$_POST["myname"];
include 'connection.php';
$idvalue=$_SESSION["myvalue"];
$sql="update entry set name='$getname' where id='$idvalue'";
$result=mysql_query($sql)
or die(mysql_error());
if($result)
{
echo "Uploaded $_SESSION[myvalue] re ..... ";
}
else
{
echo "$_SESSION[myvalue] nahi hua";
}
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="text" name="myname" id="myname">
<input type="submit" name="send" id="send">
</form>
<script type="text/javascript" src="webcam.js"></script>
<script language="JavaScript">
document.write( webcam.get_html(320, 240) );
</script>
<form>
<input type=button value="Configure..." onClick="webcam.configure()">
<input type=button value="Take Snapshot" onClick="take_snapshot()">
</form>
<script language="JavaScript">
document.write( webcam.get_html(320, 240) );
</script>
<script language="JavaScript">
webcam.set_api_url( 'test.php' );
webcam.set_quality( 90 ); // JPEG quality (1 - 100)
webcam.set_shutter_sound( true ); // play shutter click sound
webcam.set_hook( 'onComplete', 'my_completion_handler' );
function take_snapshot(){
// take snapshot and upload to server
document.getElementById('upload_results').innerHTML = '<h1>Uploading...</h1>';
webcam.snap();
}
function my_completion_handler(msg) {
// extract URL out of PHP output
if (msg.match(/(http\:\/\/\S+)/)) {
// show JPEG image in page
document.getElementById('upload_results').innerHTML ='<h1>Upload Successful!</h1>';
// reset camera for another shot
webcam.reset();
}
else {alert("PHP Error: " + msg);
}
}
</script>
<div id="upload_results" style="background-color:#eee;"></div>
instead of giving relative path in the file_get_contents() give full path/actual path.
Hope this might help you.
Is it possible to run a php file/function without entering the page?
I mean it is really disturbing if you create for example a chat app and when you submit your message the whole page get reloaded.
I've tried AJAX but didn't worked. Is it impossible to post the text of the chat_area to the PHP file?
<form action="..." method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<?php
session_start();
include_once( "database.php" );
if( $_POST["chat_area"] ){
$name = $_SESSION["firstname"]
$time = "[" . date( "H:i", time() + 3600 ) . "]";
$message = $_POST["chat_area"]
mysql_query( "INSERT INTO chat( name, time, message ) VALUES ('$name', '$time', '$message' )" );
}
?>
It's default behaviour of the form. For chat-like app, you should use ajax. Not only for posting the form data, but also for receiving messages from backend app. Otherwise, you'll have to reload a page to check whether or not you got some new messages.
With jQuery you could use event.preventDefault() to stop the default action of the form to be triggered, and then post the data to PHP.
You should split your app to 2 files. Main page, and file, where all the data is sent to (and received from).
Your front end:
<?php
session_start();
// rest of the PHP, if any...
?>
<form method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#chat_submit').on('click', function(e){
e.preventDefault();
$.ajax({
type : "POST",
url : 'your_php_file.php',
dataType : 'text',
data :{
message : $('#chat_area').val()
},
success : function(data){
if(data == 'success'){
// E.g.: append the message to chat area after it is successfully stored in DB.
}
},
complete : function(status){
// call on complete
},
error : function(response){
// call when error
}
});
});
});
</script>
PHP (your_php_file.php):
<?php
session_start();
include_once("database.php");
if( isset($_POST["message"]) ){
$name = $_SESSION["firstname"];
$time = "[" . date( "H:i", time() + 3600 ) . "]";
// a little of safety:
$unsafe_message = trim($_POST["message"]);
$safe_message = mysql_real_escape_string($unsafe_message);
mysql_query
( "INSERT INTO chat( name, time, message )
VALUES
('$name', '$time', '$safe_message' )" ) or die('error');
echo 'success';
}else{
echo 'error';
}
?>
whenever I refresh the page or leave and come back, the image disappears from the site and the database. I dont want the form to redirect to a different page, I just want it to stay on the same page but only run the query when the submit button is pressed.
<?php
$display = mysql_query("SELECT image FROM `blog_users` WHERE username = '$session->username'");
$res = mysql_fetch_array($display); echo "<image style='height: 50px; width:50px;' src='".$res['image']."'>";
$close = 0;
?>
//the above code displays the image
<?php
define ("MAX_SIZE","1000");
//This function reads the extension of the file. It is used to determine if the
// file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no
// error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and
// will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension !=
"png") && ($extension != "gif"))
{
//print error message
echo '<h3>Unknown extension!</h3>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images
//folder)
$newname="upload/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h3>Copy unsuccessfull!</h3>';
$errors=1;
}}}}
//this code sends the image location to the database
mysql_query("UPDATE blog_users SET image = '$newname' WHERE username = '$session->username'") ;
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
?>
<form name="newad" method="post" enctype="multipart/form-data"
action=""><img src="" alt="" />
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
$(document).ready(
function(){
$('input:submit').attr('disabled',true);
$('input:file').change(
function(){
if ($(this).val()){
$('input:submit').removeAttr('disabled');
}
else {
$('input:submit').attr('disabled',true);
}
});
});
</script>
</head>
<table>
<tr><td><input type="file" name="image" id="file"></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image" id="image_upload" disabled>
</td></tr>
</table>
</form>
Comments to answer to close the question.
if(isset($_POST['Submit'])){...} - ... = code to execute.
The way you have it now, is that mysql_query("UPDATE... will run regardless.
In other words, relocate the brace for it.
You have }}}}
Remove one of the braces and relocate it just before your ?> tag, and you should be good to go.
if(isset($_POST['Submit'])){
...
$errors=1;
}}}
//this code sends the image location to the database
mysql_query("UPDATE blog_users SET image = '$newname' WHERE username = '$session->username'") ;
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
} // brace for if(isset($_POST['Submit']))
?>
I have spent days looking for a fairly simple integration of angularjs file upload method that includes a basic php server side script..
I need a simple form one field and file upload upload.
All examples I find are either heavily relying of jQuery or if they seem like something I could use their "examples" are completely unclear and messy.
These two examples (if I could figure out how to incorporate with PHP) would solve my puzzle..
Example 5 on this page
http://ng-upload.eu01.aws.af.cm/
And the example on this page is one I really like a lot..
http://angular-file-upload.appspot.com/
Could someone bring more light into this for me.. I would really like to see a one input filed and one file upload with as simple as possible angular and php code if such thing exists somewhere.
I would be happy to implement this http://twilson63.github.io/ngUpload/ or http://angular-file-upload.appspot.com/
If this is my PHP
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
and this my basic html
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="fname" />
<input type="file" name="image" />
<input type="submit"/>
</form>
How could I approach this (cleanly)? What should my controller and adjusted html look like?
If you use ng-file-upload
You can do most of those pre-validation on the client side like checking the file size or type with ngf-max-size or ngf-pattern directives.
Upload.upload() will send a POST multipart/form-data request to the server so $_FILES['file'] should contain the uploaded file.
HTML
<div ng-controller="MyCtrl">
<input type="text" name="username" ng-model="username"/>
<input type="file" ngf-select="onFileSelect($file)" ngf-pattern="'image/*'" ngf-max-size="2M">
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function(file) {
if (!file) return;
Upload.upload({
url: '/upload.php',
data: {file: file, username: $scope.username}
}).then(function(resp) {
// file is uploaded successfully
console.log(resp.data);
});
};
}];
upload.php
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
//The error validation could be done on the javascript client side.
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
I was also battling with $files being undefined - I'll take a wild guess that you are writing the html code from php and haven't escaped the $ in $files. That was my problem anyway - should be \$files.
Dan