Upload Photo from iPhone to PHP Using PhoneGap - php

I have a simple upload form working in PHP (works in web) and also am able to capture a photo from iPhone using PhoneGap (base64) and displaying it on the device.
But I can't figure out how to upload it to my server with PHP.
Here's the code running in PHP:
INDEX.PHP
<?
//print_r($_POST);
if($_POST["action"] == "Upload Image")
{
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['image_file']))
$error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['image_file']['name']);
//echo $imagename;
if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";
if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}
}
include("upload_form.php");
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>\n";
}
}
include("list_images.php");
?>
And here are the two includes...
UPLOAD_FORM.PHP
<form method="POST" enctype="multipart/form-data" name="image_upload_form" action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20" value="beautiful.jpg"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>
LIST_IMAGES.PHP
<?
$handle = #opendir("images");
if(!empty($handle))
{
while(false !== ($file = readdir($handle)))
{
if(is_file("images/" . $file))
echo '<img src="images/' . $file . '"><br><br>';
}
}
closedir($handle);
?>
Here's the code running on iPhone 4 (iOS 4.2) in PhoneGap
INDEX.HTML (running in WWW directory in PhoneGap)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=yes" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="style.css">
<!-- iPad/iPhone specific css below, add after your main css >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
-->
<!-- If you application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
// If you want to prevent dragging, uncomment this section
/*
function preventBehavior(e)
{
e.preventDefault();
};
document.addEventListener("touchmove", preventBehavior, false);
*/
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function getPicture(sourceType)
{
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData)
{
//alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()" marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<h1>Camera</h1>
<img style="width:80px;height:120px" id="test_img" src="" />
<p>
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<p>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
</html>
Incidentally, while I can grab a fresh picture from the device camera, I've been completely unable to get images from the Library... if anyone knows how to do that, I'd appreciate feedback there too.
Had anyone been able to upload photos from PhoneGap/iPhone to PHP? Any source code on both sides of this would be GREATLY appreciated.

The Base64 option is really just for ease of displaying on the webpage. if it's not needed then don't use it.
i'd say your best option is to use FILE_URI instead of DATA_URL for Camera.DestinationType
check out http://docs.phonegap.com/phonegap_camera_camera.md.html for more info

Use options PHOTOLIBRARY or SAVEDPHOTOALBUM to get existing pictures from your phone. See more at http://docs.phonegap.com/en/1.4.0/phonegap_camera_camera.md.html#Camera.

In phonegap:
$.post(URLReport,{
pic1: document.getElementById("image1").src.slice(23),
}, function(xml) {
//stuff to do on success
});
On server:
if (isset($_POST['pic1'])) {
$pic = base64_decode( $_POST['pic1']);
if (strlen($pic) > 9 ) {
$fh = fopen(yourfilename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
Easy peasy.

Related

Is there a way to automatically use another image as a temporary placeholder for missing images sitewide?

I am working on building a site, but right now it has several images that I don't have actual images for yet. As this site has thousands of images or places where images should be, I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Update: Since I am still a bit confused as to where to even place this function, I am going to add the code for one of the pages that I need this for then maybe someone can help me figure out how to place it.
Here is the code for one of the pages:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do { ?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
Since this is as simple as a foreach loop, and not tons of images scattered across your webpage, you can use something like:
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
Full code:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do {
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="<?php echo $image; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Such a function might be written as:
function im($imgName) {
$pathToImgs = "images/";
if (file_exists( $pathToImgs . $imgName )) {
echo $pathToImgs . $imgName;
}
else {
echo $pathToImgs . "placeholder.jpg";
}
}
Then in your html:
<img src="<?php im("product1.jpg"); ?>">
<img src="<?php im("product2.jpg"); ?>">
<img src="<?php im("product3.jpg"); ?>">
As a start.
***Edit 1:
Given your code where it says:
<img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
You might modify it with a conditional that inserts the placeholder image in the event that the target image simply doesn't exist, yet.
<img class="thumb" src="<?php
if (file_exists("img/" . $row_master['img'])) {
echo "img/" . $row_master['img'];
}
else {
echo 'img/placeholder.jpg';
}
?>">
You could reuse this functionality by turning the conditional into a php function, so described as a starter above.
Using jQuery, you can accomplish something easy enough using a global $('img') handler when errors occur. Simply swap them out with your placeholder image afterwards.
$('img').on('error', function() {
const oldSrc = encodeURIComponent($(this).attr('src'));
$(this).attr('src', `https://via.placeholder.com/300/000000/FFFFFF/?text=${oldSrc}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="imagethatdoesntexist.jpg"><br />
<img src="anotherimage.jpg">
Here I use placeholder.com (A convenient site for placeholder images such as this), and inject the old image source into the query string, which the site will render in the image itself.

How to show user the URL once image uploaded

I am looking for a way where when a user uploads a image in PHP it shows them the URL to the file.
My current upload.php is the following:
<?php
if(!empty($_FILES)){
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'codexworld';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$targetDir = "http://wotm8.net/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
}
}
?>
Ignore the database. I don't use that
if you need the index file or anything else then ask.
HTML PAGE
<!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=gb18030">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="google-site-verification" content="_wLD3KO_vuO5czv-n-j9YrXxO3OtQuGc6C51vOaRHMU" />
<title>wotm8.net 路 File Hosting</title>
<link rel="stylesheet" type="text/css" href="css/dropzone.css" />
<script type="text/javascript" src="js/dropzone.js"></script>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="build.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1 id="logo">wotm8.net</h1>
<p class="lead">Max upload size is 75MiB, read the FAQ</p>
<noscript>
<p class="alert alert-error"><strong>Enable JavaScript</strong> you autist neckbeard, it's not gonna hurt you</p>
</noscript>
<p id="no-file-api" class="alert alert-error"><strong>Your browser is shit.</strong> Install the latestFirefox or Botnet and come back <3</p>
<div class="fileUpload btn btn-primary">
<form action="upload.php" class="dropzone" data-max-size="75MiB">
</div>
</form>
<ul id="upload-filelist"></ul>
<audio id="sickerMeme" src="meme.mp3" />
<script>
var i = 0, text;
var str = "Dude, that's a sick meme.";
function start(){
// document.getElementById("sickerMeme").play();type();
}
/* Credits: https://jsfiddle.net/creed88/VG8MJ/1/ */
function type(){
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('logo').innerHTML = text;
setTimeout(type, 80);
}
</script>
</div>
<!-- Leo5gg lol -->
<nav>
<ul>
<li>Index</li>
<li>FAQ</li>
<li>Contact</li>
</ul>
</nav>
<script src="main.js"></script>
</div>
</body>
</html>
I think your upload directory is $targetFile
You can echo it out or return it in any way you think is safe
Like after insert into database
echo $targetFile;
EDIT
Your target dir should be a absolute path, not a website link, should be something like /var/www/folder/
I doubt your upload is working in the example you posted.
after you manage to make the upload successful, just echo your domain + relative folder ( if any) + filename.

Bootstrap fileinput plugin json error

By the click of the delete button, I receive this error. SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Can someone help me resolve it as all efforts to resolve it have proved futile.
Here's a screenshot of the error.
json error
And here's the screenshot of my directory structure.
directory structure
Here's the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Bootstrap File Upload</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/fileinput.min.js" type="text/javascript"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<input id="files" name="images[]" type="file" multiple=true class="file-loading">
</body>
<?php
$directory = "images_/";
$images = glob($directory . "*.*");
?>
<script>
$("#files").fileinput({
uploadUrl: "upload.php",
uploadAsync: false,
minFileCount: 1,
maxFileCount: 20,
showUpload: false,
showRemove: false,
initialPreview: [
<?php foreach($images as $image){?>
"<img src='<?php echo $image; ?>' height='120px' class='file-preview-image'>",
<?php } ?>],
initialPreviewConfig: [<?php foreach($images as $image){ $infoImages=explode("/",$image);?>
{caption: "<?php echo $infoImages[1];?>", height: "120px", url: "delete.php", key:"<?php echo $infoImages[1];?>"},
<?php } ?>]
}).on("filebatchselected", function(event, files) {
$("#files").fileinput("upload");
});
</script>
</html>
Here's my upload.php
<?php
$enclosedFolder="images_/";
// Count sent by plugin
$Images =count(isset($_FILES['images']['name'])?$_FILES['images']['name']:0);
$infoImagesUploaded = array();
for($i = 0; $i < $Images; $i++) {
// The name and the temporary file name we're gonna attach
$nameFile=isset($_FILES['images']['name'][$i])?$_FILES['images']['name'][$i]:null;
$nameTemp=isset($_FILES['images']['tmp_name'][$i])?$_FILES['images']['tmp_name'][$i]:null;
$pathFile=$enclosedFolder.$nameFile;
move_uploaded_file($nameTemp,$pathFile);
$infoImagesUploaded[$i]=array("caption"=>"$nameFile","height"=>"120px","url"=>"delete.php","key"=>$nameFile);
$ImagesUploaded[$i]="<img height='120px' src='$pathFile' class='file-preview-image'>";
}
$arr = array("file_id"=>0,"overwriteInitial"=>true,"initialPreviewConfig"=>$infoImagesUploaded,
"initialPreview"=>$ImagesUploaded);
echo json_encode($arr);
?>
And here's my delete.php
<?php
$enclosedFolder="images_/";
if($_SERVER['REQUEST_METHOD']=="DELETE"){
parse_str(file_get_contents("php://input"),$dataDELETE);
$key= $dataDELETE['key'];
unlink($enclosedFolder.$key);
echo 0;
}
?>
As seen on Github:
Its an error on your server code returning an invalid json format for
your upload response. Debug it with firebug or javascript console and
resolve to return a right JSON format. You must return a RIGHT JSON
response from your AJAX (even if you do not have anything... you must
at least return an empty JSON object like {}).
In PHP file, I'm feedback empty JSON to Ajax
return "{}";
or
echo "{}";

Rotate images from auto rotate using jquery cycle for Photo Slideshow

I'm using some slideshow code I found. I got it up an running and shows the pictures great. The TV I'm running the slideshow on is turned 90 degrees. But it's only physically turned. It's not turned in the OS. So I need to rotate all the images 90 degrees
I can't seem to get the code right to flip it. I've tried PHP but my limited knowledge is preventing me from getting it right.
Here's the code I'm using
<!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>Slideshow</title><!-- -->
<script src="scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery.cycle.lite.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myslides').cycle({
fit: 1, pause: 1, timeout: 4000
});
});
</script>
<link rel="stylesheet" href="styles/dynamicslides.css" type="text/css" media="screen" />
</head>
<body>
<?php
$directory = 'images/slideshow';
try {
// Styling for images
echo '<div id="myslides">';
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . '/' . $item;
echo '<img src="' . $path . '"/>';
}
}
echo '</div>';
}
catch(Exception $e) {
echo 'No images found for this slideshow.<br />';
}
?>
</body>
</html>
there are mutiple kind of "rotation", but I think the one you want is simply "dislpay the image at 90 degrees".
In that case, I'd suggest CSS over PHP. Make sure the rotation doesn't truncate any of you image.
#90Image
{
/* Firefox */
-moz-transform:rotate(90deg);
/* Safari and Chrome */
-webkit-transform:rotate(90deg);
/* Opera */
-o-transform:rotate(90deg);
/* IE9 */
-ms-transform:rotate(90deg);
}
and modify you code to:
echo '<img id="90Image" src="' . $path . '"/>';

jquery php image upload using http://valums.com/ajax-upload/

Iam looking for jquery php image upload exactly given in http://valums.com/ajax-upload/.
i tried code given in the above site. but its not working . as iam newbie.. i tried below code.
<?php
$uploaddir = 'c:\xampp\htdocs\ajax-upload\server\uploads\';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "success";
} else {
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
// Otherwise onSubmit event will not be fired
echo "error";
}
?>
this is my html code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="fileuploader.css" rel="stylesheet" type="text/css">
<style>
body {font-size:13px; font-family:arial, sans-serif; width:700px; margin:100px auto;}
</style>
</head>
<body>
<p>Back to project page</p>
<p>To upload a file, click on the button below. Drag-and-drop is supported in FF, Chrome.</p>
<p>Progress-bar is supported in FF3.6+, Chrome6+, Safari4+</p>
<div id="file-uploader-demo1">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script src="fileuploader.js" type="text/javascript"></script>
<script>
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: '../server/upload.php',
debug: true
});
}
// in your app create uploader as soon as the DOM is ready
// don't wait for the window to load
window.onload = createUploader;
</script>
</body>
</html>
in php change:
$uploaddir = 'c:\xampp\htdocs\ajax-upload\server\uploads\';
to
$uploaddir = 'server/uploads';
in javascript change:
action: 'http://localhost/ajax-upload/server/upload.php',
to
action: 'server/upload.php',
if the php file you are running is in the ajax-upload folder.

Categories