I've created a website with html and javascript that gets access to your webcam and when users press take photo button a photo is captured. How would I go about directly uploading this to some cloud folder where it is stored?
Thanks
On the page where the button is,:
Create the button which snaps the photo(I don't kbnow how that is done)
<button>Snap photo!</button>
Create a form (invisible form) with the value of anything....anything can be the value just make sure it isn't empty
Use javascript so that when the button is clicked,the form is submitted to a php page
Mke the target of the form be an iframe that you have created so that when they snap the photo,it leads to the same page,without reloading the page]
Here's the code for what I just said:
Snap
</form>
<script>
function rad(){
document.getElementById("crap").submit();
</div>
Make the file handler with this code:
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 1000000000) {
$errors[] = "This file is more than 1GB. Sorry, it has to be less than or equal to 1GB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo basename($fileName) ;
} else {
echo "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
The only thing is that this uploads the image to your server not a 'cloud folder' ...but it is a folder just place the cloud folder in your webserver then specify the name of the cloud folder in the$uploadDirectory = "/uploads/"; ie change 'uploads' to the name of your cloud folder....
Hopes this helps
Related
i am using filedrop.js fo an Image Upload Script.
I fund a script here : https://tutorialzine.com/2011/09/html5-file-upload-jquery-php
In the Prject is a file_post.php which i wanted to change to save some informations (like the Filename) into a Database.
This is my post_file.php :
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
//My added code
include('/var/www/html/board/SSI.php');
$userName = $context['user']['name'];
$content_id = $_COOKIE["contentid"];
$pic_name = $pic['name'];
$pic_code = $content_id;
$pic_path = $pic_name;
$db_host = "******";
$db_name = "******";
$db_user = "******";
$db_pass = "******";
$db = mysqli_connect("$db_host","$db_user","$db_pass","$db_name") or die("Error " . mysqli_error($db));
$stmt = $db->prepare("INSERT INTO `User_pics` (content_id, path, user_id, user_name) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $pic_code,
$pic_path,
$context['user']['id'],
$context['user']['name']);
$stmt->execute();
$stmt->close();
//end of my added code
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
After i added the mysqli part the Success message is not shown anymore.
On the Image Upload the Progressbar stops at about 50%. The files are Uploaded and the informations are ssaved into the DB, but i got no success respons and this i need to handle the next steps. pleas help!
Thanks.
thanks for interrests,
two days i worked fo a soulution, after i asked here i found the Answer ;)
The Problem was the Include of the SSI.php which is encoded in UTF-8.
This was the reason for an Error in the Json encoded Response.
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My soulution was:
I created a cookie for User ID and User name so i was able to remove the Include. After this every thing works great. If someone has the Same Error simply create a cookie where you are showing your Upload Form, after Upload delet them.
Thanks to the Community and have a nice Day ;)
I need that code to upload only picture file and when you upload file extension like .pdf the code to be reject that file
if((isset($_FILES['file'])) && ($_FILES['file']['name']!='"')) { echo 'isset'.$_FILES['file']['name'];
$folder = 'upload/';
$file = basename($_FILES['file']['name']);
$size_maxi = 2000000;
$size = filesize($_FILES['file']['tmp_name']);
$extensions = array('.png', '.gif', '.jpg', '.jpeg');
$extension = strrchr($_FILES['file']['name'], '.');
//Start the file type verification
//If the extension is not in table
if(!in_array($extension, $extensions)){
$error = 'You must make use of file in the following forma type png, gif, jpg, jpeg'; }
elseif($size>$size_maxi)
{
$error = 'File size is above allowed limitations...';
}
//If no error detected, proceed to upload
else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
//Writes the information to the database
mysql_query("INSERT INTO picture (P_file,P_type,P_size)
VALUES ('$file', '$extension','$size')");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
I have some problem with a variable in my script I need to "send" the variable through some different files
The variable comes from the link:
index.php?email=emailname#emailname.com
The script is a file upload script. It's using 3 files in the process, please here:
/public_html/upload/index.php
/public_html/upload/content/index.php
/public_html/upload/content/UploadHandler.php
/public_html/upload/index.php is that runs the script and where the variable is received from the link:
index.php?email=emailname#emailname.com
The file code of /public_html/upload/index.php looks like:
<?php
// change the name below for the folder you want
$dir = "content/".$_GET["email"];
$file_to_write = 'test.txt';
$content_to_write = "The content";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
// a different way to write content into
// fwrite($file,"Hello World.");
fwrite($file, $content_to_write);
// closes the file
fclose($file);
// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;
$_SESSION['tmem']= $_GET["email"];
?>
I know that $_GET["email"] works since I can the code: <?=$_GET["email"]?> on the index.php file to see if it receive the variable.
The code:
$_SESSION['tmem']= $_GET["email"];
should forward the variable to the next file:
/public_html/upload/content/index.php
that looks like this:
session_start();
$dir = "content/" . $_GET["email"];
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler( array ('upload_url' =>$dir) );
And that code should forward the variable to the codes of the script where the upload patch is. Codes on the file: /public_html/upload/content/UploadHandler.php looks like:
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/'.$_GET['email'].'/',
'upload_url' => $this->get_full_url().'/'.$_GET['email'].'/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
Can somebody see where in the process I lose the variable?
I think, in this part of code:
session_start();
$dir = "content/" . $_GET["email"];
you try to get your "email" from URI instead of getting it from session (tmem).
I have a "contact us" form and everything is working but my error callback in the ajax runs instead of the success. I ajax is called, the PHP file runs, and I get an email to my localhost (using Mercury).
So why is my success callback not running? I have no idea how to find out what is causing the error especially since everything works.
The only thing I suspect is the file folders. The current structure is this. My html file and php file are in the root directory. The JS file is in a folder.
Here is a screenshot of the network tab in chrome debugger after I press submit
http://i.imgur.com/HfRYjj0.png
My Ajax:
$(document).ready(function(e) {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
$('#sendingemail').fadeIn();
$.ajax({
url : "../sendemail.php",
type : "POST",
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('#sendingemail').fadeOut();
$('#emailsent').fadeIn();
},
error : function() {
alert("Error");
}
});
}));
});
My PHP:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
/*$status = array(
'type'=>'Error',
'message'=>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement'=>'Couldn\'t attach the uploaded File to the Email.'
);*/
//Added to deal with Files
require_once ('PHPMailer/class.phpmailer.php');
if (isset($_FILES['uploaded_file'])) {
//require_once('/PHPMailer/class.smtp.php');
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"] / 1024;
//size in KBs
//Settings
$max_allowed_file_size = 10240;
// size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
//Validations
if ($size_of_uploaded_file > $max_allowed_file_size) {
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for ($i = 0; $i < sizeof($allowed_extensions); $i++) {
if (strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) {
$allowed_ext = true;
}
}
if (!$allowed_ext) {
$errors .= "\n The uploaded file is not supported file type. " . " Only the following file types are supported: " . implode(',', $allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if (is_uploaded_file($tmp_path)) {
if (!copy($tmp_path, $path_of_uploaded_file)) {
$errors .= '\n error while copying the uploaded file';
}
}
}
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email -> From = $clientemail;
$email -> FromName = $name;
$email -> Subject = $subject;
$email -> Body = $body;
$email -> AddAddress('root#localhost.com');
//Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email -> isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if (isset($_FILES['uploaded_file'])) {
if ($email -> AddAttachment($path_of_uploaded_file, $name_of_uploaded_file)) {
//$status[] = 'The Uploaded File was successfully attached to the Email.';
}
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try {
$success = $email -> send();
//$status['type'] = 'success';
$status[] = 'Thank you for contacting us. We will reply as soon as possible.';
} catch(Exception $e) {
//$status['type'] ='Error';
$status[] = 'Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die(json_encode($status));
I have a multi-step form. What I want to achieve here is to allow user to upload a file (with some validation using jquery.validate plugin) and store the file to mySQL database.
Previously, I wasnt using multi-step form design (a one-page per step design instead) and therefore when user clicked the "submit" button, I would have if(isset($_POST['submit'])) and $_FILES to validate the file through PHP. Below is the PHP code that will be triggered when user clicked "submit" button .
if(isset($_POST['submit']))
{
$allowedExts = array("mov", "mp4", "mpeg", "wmv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "video/quicktime") || ($_FILES["file"]["type"] == "video/mp4") || ($_FILES["file"]["type"] == "video/mpeg") || ($_FILES["file"]["type"] == "video/x-ms-wmv")) && in_array($extension, $allowedExts) && (!empty($_POST["title"])) && (!empty($_POST["description"])))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// check if the file already exist in Uploaded folder
if (file_exists("uploaded/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"]." already exists. ";
}
else
{
echo "<br />".$_FILES["file"]["name"]." has been uploaded! <br /><br />";
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type: ".$_FILES["file"]["type"]."<br />";
echo "Size: ".($_FILES["file"]["size"] / 1024)." kB<br />";
echo "Stored in: "."uploaded/".$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded/".$_FILES["file"]["name"]);
$name = $_FILES["file"]["name"];
$url = ""; //some URL
mysql_query("INSERT INTO video (name, title, description, url) VALUES ('$name', '$title', '$description', '$url')") or die(mysql_error());
}
}
}
else
{
if (!empty($_POST["description"]) && (!empty($_POST["title"])))
{
echo "Invalid file";
}
}
}
But now, since I have change my design to multi-step form, this logic seems not working anymore. This is my fiddle.
I was thinking to change the "Upload" button type from type="button" to type="submit"so that I can use my old PHP logic to process the file and upload to database, however this causes my multi-step form to stop going to the next step.
Any brilliant ideas or suggestions?
If you want to avoid page reloads, you could try posting the form through a hidden iframe and then reading the response on load. As far as I know this should work in all browsers
<iframe name="target_iframe">..</iframe>
<form target="target_iframe">..</form>
Check out How do you post to an iframe?
If you're happy dropping support for older browsers you can post files using ajax. Maybe check out using html5 for file upload with ajax and jquery