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.
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'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... :)
I want to show JavaScript alert after successful data insertion in MySQL. How to do this? I have written this code but it shows JavaScript alert everytime I open this page and as soon as i click on OK of JavaScript alert it redirects me to finalmem.php, without the action of taking values from users!
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
Thanks in advance.
Use is set isset($_POST['submit']) to check whether user submits the form or not
<?php
include 'SQLIDB.php';
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$ybr=$_POST['ybr'];
$ach=$_POST['ach'];
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
<form action="" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="ybr">
<input type="text" name="ach">
<input type="submit" name="submit" value="Submit">
</form>
You need to know two things, one of them it's to confirm if your data it's saved succefully.
For this you can play with
mysql_affected_rows()
and this function will return the number of rows affected by your query. If zero, it was not inserted. If >= 1, it was.
So:
if ( mysql_affected_rows() >= 1 ){ /* inserted! now do something... */ }
If you are using an auto-incrementing column for row ID, you can use mysql_insert_id() as well:
if ( mysql_insert_id() > 0 ) { /* inserted! now do something... */ }
Then you can work with jQuery UI for show a dialog like this:
[https://jqueryui.com/dialog/][1]
You need tot load the .css and .js files to run jQuery and inside your code put this:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
And this in your view:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
Normally this it's super ugly to do for me, because the best way it's doing this by AJAX.
You can try like this
<?php session_start();
//Include database detail here
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($_POST["name"]);
$ybr = mysqli_real_escape_string($_POST["ybr"]);
email = mysqli_real_escape_string($_POST["email"]);
$ach = mysqli_real_escape_string($_POST["ach"]);
//Do your data validation here
$_SESSION['sname'] = $name;
$_SESSION['sybr'] = $ybr;
$_SESSION['semail'] = email;
$_SESSION['sach']= $ach;
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
This is form i am sending image file to the upload.php script file and image file should display in the 'onsuccessmsg' div
<form action="upload.php" method="POST" id="uploadform">
<input type="file" file="file" id="file_to_send"/>
<input type="submit" value="Upload"/><br/><br/>
Message :
<div id="onsuccessmsg" style="border:5px solid #CCC;padding:15px;"></div>
</form>
This is the JavaScript code:
<script>
$(document).ready(function(){
$("#uploadform").on('submit',function(){
$("#onsuccessmsg").load("upload.php",{},function(res){
});
});
});
</script>
This is the upload.php file:
<?php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, "./uploads/".$imgn))
{
echo "File Name : ".$_FILES['file']['name'];
echo "<br/>File Temporary Location : ".$_FILES['file']['tmp_name'];
echo "<br/>File Size : ".$_FILES['file']['size'];
echo "<br/>File Type : ".$_FILES['file']['type'];
echo "<br/>Image : <img style='margin-left:10px;' src='uploads/".$imgn."'>";
}
}
?>
Onsubmit the form how to send the name and id values to the upload.php file and echoing the image file in the onsuccessmsg div,
I am confused, please help me.
You will get the image name through this code
$('#submit').click(function()
{
var str=$("#image").val();
var arr=str.split("\\");
var image=arr[2];
alert(image);
});
You can use iframe for such upload of image with jquery...
$(document).ready(function()
{
$("#input_for_image_upload").change(function()
{
$("#img_upload").submit();
});
});
I have a php file and I have created 2 buttons get and set in the file.
I want to access Get.php file when I click get
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
and Set.php file when I select set button.
<?php
$file = "xxx.json";
include 'Set.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
My file visual.php file contents are:
<!DOCTYPE html>
<meta charset="utf-8">
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
<style>
right {
display:table-cell;
vertical-align:top;
width:300px;
padding:0 5px;
}
<?php
$color=include('Color.php');
echo $color;
?>
</style>
<body>
<div id=tt>
<button type="submit" onclick="get()"> <b>get</b></button>
<button type="submit" onclick="set()"> <b>set</b></button>
</div>
<div id=graph>
<script src="ll.js"></script>
<script src="visual.js"></script>
<script type="text/javascript">
window.onload = function(){
}
<?php
$link=include('Link.php');
echo $link;
?>
</script>
</div>
<body>
I am not sure how can I get the contents for Get.php file and Set.php file. I know that I can call ajax calls. But in that case only I can get the contents of the Get.php or Set.php files.
But how can I also make other data shown below execute in sequential order.
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
I am new to php. Thanks for all your help.
Bes way, is using standard html methods: name-value for form elements
<body>
<form method="GET">
<button type="submit" name="event" value="get"> <b>get</b></button>
<button type="submit" name="event" value="set"> <b>set</b></button>
</form>
<body>
And the php code:
$file = "xxx.json";
switch ($_GET['event'])
{
case 'get': include 'Get.php'; break;
case 'set': include 'Set.php'; break;
}
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
Dmitriy's answer is pretty easy, and clean looking. I like.
Ive made a little longer example, utilizing a class aswell, and commented it throughoutly for you to perhaps learn a little or two. Hope it helps!
<?php
class HandleFile {
protected $file;
//The construct is called, when the object is created. We request the file here.
public function __construct($file = null) {
//Lets check if the file variable is set or not.
if( !is_null($file) ) {
//Lets check if the file actually exists
if( file_exists($file) ) {
//If the file exists, set the class variable.
$this->file = $file;
} else {
//If the file does not exist. Throw an exception
throw new Exception("Construct:: The file " . $file . ", does not exist.");
}
} else {
//If the file variable is not set, throw an exception.
throw new Exception("Construct:: No file specified.");
}
}
//This function will do our actual logic.
public function doAction($fileToInclude) {
//First, check if the file to include exists.
if( file_exists($fileToInclude) ) {
//Include it
include($fileToInclude);
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($this->file,$output);
} else {
//If it does not exist. Throw exception.
throw new Exception("doAction:: File " . $fileToInclude . ", does not exist.");
}
}
}
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler = new HandleFile("xxx.json");
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
//Define a helper variable
$action = null;
//If the GET parameter "get" is set, do a get action
if( isset( $_GET['get'] ) ) {
$action = "Get.php";
//If the GET parameter "post" is set, do a post action.
} elseif( isset( $_GET['post'] ) ) {
$action = "Post.php";
}
//If our helper variable has changed, there must be an action to do.
if( !is_null($action) ) {
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler->doAction($action);
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
}
?>
<body>
<form action="" method="GET">
<button type="submit" name="get" value="yes"> <b>get</b></button>
<button type="submit" name="post" value="yes"> <b>set</b></button>
</form>
<body>
You're calling a function which isn't set...
why don't you use $_POST
to with 2 different forms
1 hidden input contains the id type
if the type is get then include the get
if the type is set then include the set
this is just an example tho'