I use a google api in PHP provided by google (google-api-php-client).
However, I face a problem that the api asks twice for the login. When I click on "Log In To Your Google Account" link for the first time, it redirects me to the google login page (which is correct). Then, after logging in, it redirects me back the page at the url I have given the api, but it asks me again to click on "Log In To Your Google Account" link instead of showing the result of the login action.
When I click on the login link again, it doesn't go to the login page again, but it gives me the result of the login action (after checking of the login status I guess) which should have been done in the first click.
My Code Below:
<?php
/************************************************************************
* Plugin Name: Google Drive Plugin *
* Plugin URI: http://www.picpixa.com/ *
* Version: 1.0 *
* Author: Ashish Shah *
* Description: Plugin To Import Images From User's Google Drive Account *
************************************************************************/
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
session_start();
ini_set("display_errors",1);
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google Drive Images</title>
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
});
</script>
<script>
function loader(){
$('#load').show();
}
function loadExistingImages(){
window.opener.$('#loader_img').show();
result=null;
window.opener.$('#fileupload').each(function () {
var that = this;
window.opener.$.getJSON(this.action, function (result) {
if (result && result.length) {
window.opener.$(that).fileupload('option', 'done')
.call(that, null, {result: result});
//console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
if(window.opener.$('.table-striped .files').find('.btn-danger').length>0){
window.opener.$('.coo-images-other-buttons').show();
}else{
window.opener.$('.coo-images-other-buttons').hide();
}
}
window.opener.$('#loader_img').hide();
if (window.opener.$('.table-striped.files').children().length > 0)
{
window.opener.$('.table_tagline').show();
}
});
});
}
</script>
<script type="text/javascript">$('#load').hide();</script>
</head>
<body>
<div id="load" class="loader"></div>
<?php
include_once "templates/base.php";
//ini_set("display_errors",0);
include_once '/home/picpixa/wp-config.php';
set_include_path("src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Http/MediaFileDownload.php';
require_once 'Google/Service/Drive.php';
if(isset($_POST['copy']) && $_POST['gDrive'])
{
$imgArray = $_POST['gDrive'];
$current_user = wp_get_current_user();
if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
$extraSessionStr = 'usr-'.md5($current_user->ID).'/';
$user = $current_user->ID;
}else{
$sesstionId = session_id();
$user = $sesstionId;
$extraSessionStr = $sesstionId.'/';
}
foreach ($imgArray as $img)
{
$getName = explode ("(OR)",$img);
$imgInfo = pathinfo($getName[1]); //This will become an array with keys ('dirname','basename','extension','filename')
$oriFileName=$imgInfo['filename'];//Getting a file name without extension
$fileName = (string) $oriFileName.".".$imgInfo['extension'];//Creating a file name with extension
//Check weather the file is exists or not rename the file if exists
$i=1;
if(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
while(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
$fileName = (string) $oriFileName."(".$i.").".$imgInfo['extension'];
$i++;
}
}
// Read file content
$file_content = file_get_contents($getName[0]);
//Putting the main file into the directory
file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
//Putting the thumbnail in the directory
//Get the image size
$imgsize=get_headers($getName[0],1);
$imgsize = number_format(($imgsize["Content-Length"]/1024),2);
/* To create thumbnail */
// Max vert or horiz resolution
$maxsize=80;
// create new Imagick object
$image = new Imagick($getName[0]); //"input_image_filename_and_location"
// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
/*Problem is in above line ($image->writeImage) otherwise all is working fine because of it Networkerror 500 occurs
* Need to find solution
*/
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
?>
<script type="text/javascript">
//window.opener.$("#fileupload").append(div);
window.opener.$('tbody.files').find('tr').remove();
loadExistingImages();
</script>
<?php
echo "<h2>The selected images have been uploaded successfully.</h2>";
//echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
//echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-google-drive/index.php";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
</div>
<?php
die();
}
elseif (isset($_POST['copy']))
{
echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
//echo "<h3>Please click on \"Close\" button to Close the window OR ";
//echo "Click on the \"Upload Images\" Button to upload images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-google-drive/index.php";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
</div>
<?php
die();
}
?>
<?php
/************************************************
ATTENTION: Fill in these values!
************************************************/
$client_id = 'YOUR_APP_ID';
$client_secret = 'YOUR_API_SECRET';
$redirect_uri = 'YOUR_REDIRECT_URI';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
/*echo "Client:<pre>";
print_r($client);
echo "</pre>Client End.<br>Service:<pre>";
print_r($service);
echo "</pre>Service End.<br>";
*/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['download_token']);
echo "You are logged out.";
echo "<br>";
}
if (isset($_GET['code'])) {
//echo "Entered get_code<br>";
$client->authenticate($_GET['code']);
$_SESSION['download_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//It never gets into this section
//echo "Redirect: $redirect<br>";
//echo "Header: ".filter_var($redirect, FILTER_SANITIZE_URL)."<br>";
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/*echo "Session:<pre>";
print_r($_SESSION);
echo "</pre>Session End.<br>";
*/
if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
//echo "Entered Session download token<br>";
$client->setAccessToken($_SESSION['download_token']);
if ($client->isAccessTokenExpired()) {
//echo "Entered Session download token expire<br>";
unset($_SESSION['download_token']);
}
} else {
//echo "Not Entered Session download token. Entered else part.<br>";
$authUrl = $client->createAuthUrl();
//echo "Auth url: $authUrl<br>";
}
/*echo "Session 2:<pre>";
print_r($_SESSION);
echo "</pre>Session 2 End.<br>";
*/
/********************************************************
If we're signed in then lets try to download our file.
********************************************************/
if ($client->getAccessToken()) {
//echo "Entered getAccessToken<br>";
// This is downloading a file directly, with no metadata associated.
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->listFiles(
$file,
array('downloadType' => 'media')
);
/*echo "File:<pre>";
print_r($file);
echo "</pre>File End.<br>";
echo "Result:<pre>";
print_r($result);
echo "</pre>Result End.<br>";
*/
}
/*echo "File 1:<pre>";
print_r($file);
echo "</pre>File 1 End.<br>";
echo "Result 1:<pre>";
print_r($result);
echo "</pre>Result 1 End.<br>";
*/
?>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php
if (isset($authUrl)){ ?>
<a class='login' href='<?php echo $authUrl; ?>'>Log In To Your Google Account!</a>
<?php }else{ ?>
<a class='logout' href='?logout'>Log Out</a>
<?php } ?>
<?php
if (isset($result)){
$i=0;
$temp=0;
$showBtn=False;
?>
<form method='post' action='index.php'>
<div class='modal-body'>
<?php
/*echo "Result:<pre>";
print_r($result);
echo "</pre>Result End.<br>";
die;*/
foreach ($result as $key => $value){
if(strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpeg') == 0
|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpg') == 0
|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/png') == 0)
{
if(isset($result['modelData']['items'][$i]['thumbnailLink'])){
//echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title']."<br>";
?>
<div class="baby_img">
<input type="checkbox" id="gDrive_<?=$temp;?>" name="gDrive[]" value="<?php echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title'];?>" class="styled" />
<input type="hidden" id="fileName_<?=$temp;?>" name="fileName[]" value="<?php echo $result['modelData']['items'][$i]['title'];?>" class="styled" />
<img src="<?php echo $result['modelData']['items'][$i]['thumbnailLink'];?>" class="img-responsive" style="width:100px !important; height:100px !important;"/>
</div>
<?php
}
$temp++;
}
$i++;
$showBtn=True;
}
?>
</div>
<div class="clearfix"></div>
<div class="modal-footer">
<?php
if($showBtn){
?>
<input type='submit' name='copy' value='Copy Selected Files' class="btn btn-primary" onclick="loader()">
<?php
}
?>
<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary' onClick="window.close();">
</div>
</form>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Note: I have put echo and print_r to understand better the code behavior. You can freely remove them.
I found the solution.
It was the stupid problem. I have added header() in the index.php and it was redirecting to the same file (index.php). So I removed the header() and now it is working perfectly.
I solved this by placing my php at the very top of the page before everything...
if (isset($_POST['login'])) {
//whatever you got
}
if (isset($_POST['register'])) {
//whatever you got
}
Related
I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.
I am trying to make youtube clone website in php. I am stuck at a stage where i want to insert video that i am trying to upload into mysql database but it says error code 1. My project structure is as follows in below image
Screenshot of my website when i upload the entry as below
When click on upload button, i get the error as below image
Here is my upto date code that i have tried.
index.php File:
<?php require_once("includes/header.php"); ?>
<?php require_once("includes/footer.php"); ?>
header.php file:
<?php require_once("includes/config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>VideoTube</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="assets/js/commonActions.js"></script>
</head>
<body>
<div id="pageContainer">
<!-- Master Head Container -->
<div id="mastHeadContainer">
<!-- Hamburger Menu Button -->
<button class="navShowHide">
<img src="assets/images/icons/menu.png">
</button> <!--End of Hamburger Menu Button -->
<!-- Site Logo -->
<a class="logoContainer" href="index.php">
<img src="assets/images/icons/VideoTubeLogo.png" title="logo" alt="Site logo">
</a> <!-- End of Site Logo -->
<!-- Search Bar -->
<div class="searchBarContainer">
<form action="search.php" method="GET">
<input type="text" class="searchBar" name="term" placeholder="Search...">
<button class="searchButton">
<img src="assets/images/icons/search.png">
</button>
</form>
</div> <!-- End of Search Bar -->
<!-- Right Icons Area -->
<div class="rightIcons">
<a href="upload.php">
<img class="upload" src="assets/images/icons/upload.png">
</a>
<a href="#">
<img class="upload" src="assets/images/profilePictures/default.png">
</a>
</div> <!-- End of Right Icons Area -->
</div> <!-- End of Master Head Container -->
<div id="sideNavContainer" style="display:none;">
</div>
<div id="mainSectionContainer">
<div id="mainContentContainer">
footer.php file:
</div>
</div>
</div>
</body>
</html>
config.php file:
<?php
ob_start(); // turns on output buffering
date_default_timezone_set("Asia/Calcutta");
try {
$con = new PDO("mysql:dbname=VideoTube;host=localhost", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
VideoDetailsFormProvider.php file:
<?php
class VideoDetailsFormProvider {
private $con;
public function __construct($con) {
$this->con = $con;
}
public function createUploadForm() {
$fileInput = $this->createFileInput();
$titleInput = $this->createTitleInput();
$descriptionInput = $this->createDescriptionInput();
$privacyInput = $this->createPrivacyInput();
$categoriesInput = $this->createCategoriesInput();
$uploadButton = $this->createUploadButton();
return "<form action='processing.php' method='POST' enctype='multipart/form-data'>
$fileInput
$titleInput
$descriptionInput
$privacyInput
$categoriesInput
$uploadButton
</form>";
}
private function createFileInput() {
return "<div class='form-group'>
<input type='file' class='form-control-file' id='exampleFormControlFile1' name='fileInput' required>
</div>";
}
private function createTitleInput() {
return "<div class='form-group'>
<input class='form-control' type='text' placeholder='Title' name='titleInput'>
</div>";
}
private function createDescriptionInput() {
return "<div class='form-group'>
<textarea class='form-control' placeholder='Description' name='descriptionInput' rows='3'></textarea>
</div>";
}
private function createPrivacyInput() {
return "<div class='form-group'>
<select class='form-control' name='privacyInput'>
<option value='0'>Private</option>
<option value='1'>Public</option>
</select>
</div>";
}
private function createCategoriesInput() {
$query = $this->con->prepare("SELECT * FROM categories");
$query->execute();
$html = "<div class='form-group'>
<select class='form-control' name='categoryInput'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row["id"];
$name = $row["name"];
$html .= "<option value='$id'>$name</option>";
}
$html .= "</select>
</div>";
return $html;
}
private function createUploadButton() {
return "<button type='submit' class='btn btn-primary' name='uploadButton'>Upload</button>";
}
}
?>
VideoProcessor.php file:
<?php
class VideoProcessor {
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
//uploads/videos/5aa3e9343c9ffdogs_playing.flv
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if(!$isValidData) {
return false;
}
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".mp4";
if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed";
return false;
}
}
}
private function processData($videoData, $filePath) {
$videoType = pathInfo($filePath, PATHINFO_EXTENSION);
if(!$this->isValidSize($videoData)) {
echo "File too large. Can't be more than " . $this->sizeLimit . " bytes";
return false;
}
else if(!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
private function insertVideoData($uploadData, $filePath) {
$query = $this->con->prepare("INSERT INTO videos(title, uploadedBy, description, privacy, category, filePath)
VALUES(:title, :uploadedBy, :description, :privacy, :category, :filePath)");
$query->bindParam(":title", $uploadData->title);
$query->bindParam(":uploadedBy", $uploadData->uploadedBy);
$query->bindParam(":description", $uploadData->description);
$query->bindParam(":privacy", $uploadData->privacy);
$query->bindParam(":category", $uploadData->category);
$query->bindParam(":filePath", $filePath);
return $query->execute();
}
}
?>
VideoUploadData.php File:
<?php
class VideoUploadData {
public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;
public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
$this->videoDataArray = $videoDataArray;
$this->title = $title;
$this->description = $description;
$this->privacy = $privacy;
$this->category = $category;
$this->uploadedBy = $uploadedBy;
}
}
?>
processing.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoUploadData.php");
require_once("includes/classes/VideoProcessor.php");
if(!isset($_POST["uploadButton"])) {
echo "No file sent to page.";
exit();
}
// 1) create file upload data
$videoUploadData = new VideoUploadData(
$_FILES["fileInput"],
$_POST["titleInput"],
$_POST["descriptionInput"],
$_POST["privacyInput"],
$_POST["categoryInput"],
"REPLACE-THIS"
);
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);
// 3) Check if upload was successful
?>
upload.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoDetailsFormProvider.php");
?>
<div class="column">
<?php
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>
<?php require_once("includes/footer.php"); ?>
Per https://www.php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
You should be able to increase upload_max_filesize in php.ini to resolve the issue.
I have created a HTML page and it uses PHP to take data from a database and store it into the table created. How can I get it so when the user clicks a button it will preform a certain task according to the row in the table using php?
I am wanting to take information from a database and create new rows in a HTML table. In those rows will be data from the database, there's also a button on each row. When the user clicks that button I want it to call a function using the specified 'name' which is represented by the variable $nam.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$deny = array("222.222.222", "333.333.333");
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
header("location: http://www.google.com/");
exit();
}
$res=mysqli_query($con,"SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<?php header("Access-Control-Allow-Origin: http://www.py69.esy.es"); ?>
<head>
<title>ServiceCoin</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="scripts/home/index.css" />
</head>
<body>
<center>
<h3>Welcome, <?php echo $userRow['userName']; ?>. You Currently Have <span id="services"><?php echo $userRow['userServices']; ?></span> Services</h3>
<p id="error"></p>
<button onclick="send_coins()" class="button">Send Coins</button>
<button onclick="create_service()" class="button">Create A Service</button>
<button onclick="send_coins()" class="button">My Services</button>
<h3>View Services</h3>
<span><?php
$users = 1;
$num = 1;
echo "<center><table width=1000><th>Buy</th><th>Service Name</th><th>Service Cost</th><th>Service Description</th><th>Service Provider Name</th>";
while($users < 100 && $num < 100){
$res=mysqli_query($con,"SELECT * FROM users WHERE userId=".$users);
$userRow=mysqli_fetch_array($res);
$id = 0;
while($id != 10){
$id = $id + 1;
if($userRow['userService'.$id] === 'null'){
}else if(!empty($userRow['userService'.$id])){
echo "<tr><td name=$num ><input type=submit value=buy ></td><td class=services width=250 align=center>".$userRow['userService'.$id]."</td><td class=services width=250 align=center>".$userRow['userServiceCost'.$id]."</td><td class=services class=services width=500 align=center>".$userRow['userServiceDes'.$id]."<td class=services width=500 align=center>".$userRow['userServiceName'.$id]."</tr>";
//echo $id."Error: ".$con->error;
$num = $num + 1;
$id = $id + 1;
}
}
$users = $users + 1;
}
echo "All Services Loaded";
echo "</table></center>";
?></span>
<span class="text-danger"><?php echo $msg; ?></span>
</center>
</body>
<script lang="text/javascript" src="scripts/home/index.js"></script>
</html>
<?php ob_end_flush(); ?>
Firstly, you cannot call PHP functions on a user action without using something called Ajax. This is because once the HTML code is supplied to the user's web browser it is client side and clicking buttons won't allow you to request info from the server (unless it's new pages) unless you call the php file containing the function code through Javascript (using Ajax).
For example, create a "functions.js" file and insert the following code:
function FuncName(NameOfRow){
$.post('phpfunctionfile.php', {NameOfRow: NameOfRow}, function(data) {
if(data==1){
//Some sort of code, maybe display a modal with some sort of control panel to do something.
}
}
}
Then in the php file code your function and echo back whatever you want as the variable "data" (echo $data;). Of course you can redirect to new pages etc in this file (I have never tried it before though it should work).
Now in the originaly code assuming you are calling each function depending on userServiceName'.$id if that's unique key in your table you want to call your Javascript function using this value as the parameter. I haven't tested the following code and I'm not sure if it's actually what you want, but you should get the idea from the following code and then be able to adapt it for what you are creating.
echo "<tr><td name=$num onClick="FuncName('".$userRow['userServiceName'.$id]."' ><input type=submit value=buy ></td><td class=services width=250 align=center>".$userRow['userService'.$id]."</td><td class=services width=250 align=center>".$userRow['userServiceCost'.$id]."</td><td class=services class=services width=500 align=center>".$userRow['userServiceDes'.$id]."<td class=services width=500 align=center>".$userRow['userServiceName'.$id]."</tr>";
If this isn't a clear enough explanation please say so. I'll happily provide you some of my code that will better show how I've done it before.
I am using php sdk provided by dropbox to fetch user's images.
All is working fine. When user comes to my website and clicks on the dropbox button, it is asking for the authentication first and then imports the user's images. Because of this process user automatically logs in the dropbox.com as well. It is expected behavior.
But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication but it does not ask for the authentication but provides the images from the user dropbox account.
Please ask for more details If I was not clear.
Thank you in advance.
Edit:
index.php
<?php
/***********************************************************************
* Plugin Name: Dropbox Plugin
* Plugin URI: http://www.picpixa.com/
* Version: 1.0
* Author: Ashish Shah
* Description: Plugin To Import Images From User's Dropbox Account
**********************************************************************/
session_start();
include_once '/home/picpixa/wp-config.php';
//ini_set("display_errors",1);
?>
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
<style>
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
});
//creating dynamic back button
//var docRef = document.referrer;
//$('#backBtn').html('Go Back');
//alert('Go Back');
/* Not in use
//This function will call on the click event of <div class='row'>
function loadBackBtn()
{
$('#backBtn').html('<a class="btn btn-primary" href="' + document.referrer + '">Back</a>');
}
//document.write('<a class='btn btn-primary' href="' + document.referrer + '">Back</a>');*/
</script>
<script>
function loader(){
$('#load').show();
}
/*function loadExistingImages(){
window.opener.$('#loader_img').show();
result=null;
window.opener.$('#fileupload').each(function () {
var that = this;
window.opener.$.getJSON(this.action, function (result) {
if (result && result.length) {
window.opener.$(that).fileupload('option', 'done')
.call(that, null, {result: result});
//console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
if(window.opener.$('.table-striped .files').find('.btn-danger').length>0){
window.opener.$('.coo-images-other-buttons').show();
}else{
window.opener.$('.coo-images-other-buttons').hide();
}
}
window.opener.$('#loader_img').hide();
if (window.opener.$('.table-striped.files').children().length > 0)
{
window.opener.$('.table_tagline').show();
}
});
});
}*/
</script>
<!-- Adding this block to allow to see the login page like other social media -->
<!-- Login Block Start -->
<?php /*
if(isset($_SESSION['comingFirstTime']) && $_SESSION['comingFirstTime']==true)
{
?>
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="<?php echo $loginUrl ?>" onclick="loader()">Login</a><br><br>
<button class="btn btn-primary close_window" type="button" onClick="window.close();">Close</button>
</div>
<div class="cl"></div>
</div>
</div>
<?php
$_SESSION['comingFirstTime'] = false;
die;
}*/
?>
<!-- Login Block End -->
<script type="text/javascript">$('#load').hide();</script>
<?php
if(isset($_POST['copy']) && $_POST['dropbox'])
{
$imgArray = $_POST['dropbox'];
$current_user = wp_get_current_user();
if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
$extraSessionStr = 'usr-'.md5($current_user->ID).'/';
$user = $current_user->ID;
}else{
$sesstionId = session_id();
$user = $sesstionId;
$extraSessionStr = $sesstionId.'/';
}
foreach ($imgArray as $img)
{
//Getting a file name
$imgInfo = pathinfo($img); //This will become an array with keys ('dirname','basename','extension','filename')
$oriFileName=$imgInfo['filename'];//Getting a file name without extension
$fileName = (string) $oriFileName.".".$imgInfo['extension'];//Creating a file name with extension
//Check weather the file is exists or not rename the file if exists
$i=1;
if(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
while(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
$fileName = (string) $oriFileName."(".$i.").".$imgInfo['extension'];
$i++;
}
}
// Read file content
$file_content = file_get_contents($img);
file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
//file_put_contents('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName, $file_content);
/* To create thumbnail */
// Max vert or horiz resolution
$maxsize=80;
// create new Imagick object
$image = new Imagick($img); //"input_image_filename_and_location"
// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
?>
<script type="text/javascript">
window.opener.$('tbody.files').find('tr').remove();
//loadExistingImages();
var myVar;
if (/(MSIE\ [0-9]{1})/i.test(navigator.userAgent)) {
window.opener.$(window.opener.loadExistingFiles());
myVar = setTimeout(function(){
window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
},1000);
}
else{
window.opener.$.when(window.opener.loadExistingFiles()).done(function(){
myVar = setTimeout(function(){
window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
},1000);
});
}
</script>
<?php
echo "<h2>The selected images have been uploaded successfully.</h2>";
//echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
//echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
<!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
</div>
<?php
die();
}
elseif (isset($_POST['copy']))
{
echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
//echo "<h3>Please click on \"Close\" button to Close the window OR ";
//echo "Click on the \"Upload Images\" Button to upload images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
<!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
</div>
<?php
die();
}
require_once __DIR__.'/dropbox-sdk/Dropbox/strict.php';
$appInfoFile = __DIR__."/AppInfo.json";
// NOTE: You should be using Composer's global autoloader. But just so these examples
// work for people who don't have Composer, we'll use the library's "autoload.php".
require_once __DIR__.'/dropbox-sdk/Dropbox/autoload.php';
use \Dropbox as dbx;
$requestPath = init();
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
$loginUrl = getPath("dropbox-auth-start");
/*$loginPage = <<<login
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
<p>Display Your Photo Stream</p>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
<button class="btn btn-primary close_window" type="button" onClick="window.close();">Close</button>
</div>
<div class="cl"></div>
</div>
</div>
login;*/
$loginPage = <<<login
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
<p>Display Your Photo Stream</p>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
</div>
<div class="cl"></div>
</div>
</div>
login;
echo $loginPage;
//header("Location: ".getPath("dropbox-auth-start"));
exit;
}
$path = "/";
if (isset($_GET['path'])) $path = $_GET['path'];
$entry = $dbxClient->getMetadataWithChildren($path);
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
else if ($requestPath == "/download") {
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
if (!isset($_GET['path'])) {
header("Location: ".getPath(""));
exit;
}
$path = $_GET['path'];
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
}
else if ($requestPath === "/upload") {
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}
else if ($requestPath === "/dropbox-auth-start") {
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($requestPath === "/dropbox-auth-finish") {
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
// We didn't pass in $urlState to finish, and we're assuming the session can't be
// tampered with, so this should be null.
assert($urlState === null);
}
catch (dbx\WebAuthException_BadRequest $ex) {
respondWithError(400, "Bad Request");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it could contain
// sensitive information.
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
respondWithError(403, "Unauthorized", "CSRF mismatch");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it contains
// sensitive information that could be used to bypass the CSRF check.
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!",
"Authorization complete, <a href='".htmlspecialchars(getPath(""))."' onclick='loader()'>click here</a> to browse.");
}
else if ($requestPath === "/dropbox-auth-unlink") {
// "Forget" the access token.
unset($_SESSION['access-token']);
//$_SESSION = array();
/*echo renderHtmlPage("Logged Out",
"<div class='modal-footer'>
You have been logged out.<br>
<input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick='window.close();'>
</div>"
);*/
echo renderHtmlPage("Logged Out",
"<div class='modal-footer'>
You have been logged out.<br>
<input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
</div>"
);
}
else {
echo renderHtmlPage("Bad URL", "No handler for $requestPath");
exit;
}
function renderFolder($entry)
{
/*echo "entry:<pre>";
print_r($entry);
echo "</pre>entry end.<br>Session:<pre>";
print_r($_SESSION);
echo "</pre>Session end.";
die;*/
$dbxClient = getClient();//Using to use the createTemporaryDirectLink() function
// TODO: Add a token to counter CSRF attacks.
// $upload_path = htmlspecialchars(getPath('upload'));
//$path = htmlspecialchars($entry['path']);
//$form = <<<HTML <form action='$upload_path' method='post' enctype='multipart/form-data'> <label for='file'>Upload file:</label> <input name='file' type='file'/> <input type='submit' value='Upload'/> <input name='folder' type='hidden' value='$path'/> </form> HTML;
//$form = <<<HTML HTML;
$listing_folder = '';
$listing_folder .= "<div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<div style='clear: both;'></div>
<div class='modal-body'>";
$listing = "<div id='load' class='loader'></div>
<div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<div style='clear: both;'></div>";
/*//This section is to display logout button
if(isset($entry['contents']) && $entry['contents']){
$listing .= "<div class='modal-footer'>
<script>
function goDirect(){
window.location.href='dropbox-auth-unlink';
}
</script>
<input type='button' name='logout' value='Logout' class='btn btn-primary' onclick='goDirect()'>
</div>";
}*/
$listing .= "<form method='POST' action=''>
<div class='modal-body imgAlignment'>";
$i=0;
$showBtn=False;
foreach($entry['contents'] as $child) {
$type='Folder';
$cp = $child['path'];
$cn = basename($cp);
if (!$child['is_dir']){
$type=$child['mime_type'];
}
$cp = htmlspecialchars($cp);
$link = getPath("?path=".htmlspecialchars($cp));
if ($child['is_dir']){
$listing_folder .= "<div class='baby_img'>
<a style='text-decoration: none' href='$link'>
<img src='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/folder.jpeg' style='margin: 0px 5px 0 10px !important; width:100px !important; height:100px !important; padding: 0 5px 10px 10px !important;display: block !important;clear: left !important;float: left !important;'>
<div style='clear: both;'></div>
<p style='margin: 0px 5px 0 10px !important; padding: 0 0 0 0 !important;'>$cn</p>
</a>
</div>";
$cn .= '/';
}
else{
if(strcmp($type,'image/*')==1){
$img = $dbxClient->createTemporaryDirectLink($cp);
$listing .= "<div class='baby_img'>
<input type='checkbox' id='dropbox_".$i."' name='dropbox[]' value='".$img[0]."' class='styled' />";
$listing .= "<img src='".$img[0]."' class='img-responsive' style='width:100px !important; height:100px !important;'/>";
$listing .= '</div>';
$i++;
$showBtn=true;
}
}
}
$listing .= '<div class="clearfix"></div>
<div class="modal-footer btnAlignment">';
if($showBtn){
$listing .= "<input type='submit' name='copy' value='Copy Selected Files' class='btn btn-primary' onclick='loader();'>";
}
//$listing .= "<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary pading' onClick='window.close();'>";
$listing .= '</div>
</div>';
$listing .= "</form>
</div>
</div>
</div>";
$listing_folder .= "</div>
</div>
</div>
</div>";
return renderHtmlPage("App/picpixa$entry[path]", $listing_folder.$listing);
}
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function renderFile($entry)
{
$metadataStr = htmlspecialchars(print_r($entry, true));
$downloadPath = getPath("download?path=".htmlspecialchars($entry['path']));
$body = <<<HTML
<pre>$metadataStr</pre>
Download this file
HTML;
return renderHtmlPage("File: ".$entry['path'], $body);
}
function renderHtmlPage($title, $body)
{
$output = <<<HTML
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>$title</title>
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
</head>
<body>
HTML;
$permLink = "https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";
if(isset($_GET) && $_GET['path'] && $_GET != "/")
{
$path = $_GET['path'];
$filename = substr(strrchr($path, "/"), 1);
$newPath = $permLink."?path=".str_replace('/'.$filename,'',$path);
if($newPath == $permLink."?path="){
//Setting the newPath to the root path if there there is first folder
$newPath = $permLink;
}
$output .= "<br><div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<a href = '".$newPath."' class='btn btn-primary pading'>Back</a>
</div>
</div>
</div>";
}
$output .= <<<HTML
$body
</body>
</html>
HTML;
return $output;
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")<br>".
"doesn't have a built-in web server. You need PHP 5.4 or newer.<br>".
"<br>".
"You can still run this example if you have a web server that supports PHP 5.3.<br>".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.<br>");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.<br>".
"Usage: php $argv[0] [server-port]<br>");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:<br>".
" $cmd<br>");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
?>
"But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication".
Your website is remembering the user because you're using a session to do so. If you don't want to remember the user, stop doing it. :-)
In general, a user logging out of one website has no impact on their sessions at other websites. So a user logging out of dropbox.com has no effect on their logged in status on your website. Perhaps you want to set an expiration time on the session so the user is forced to reauthenticate after a while? Or you could not use a session at all (i.e. not store the access token), in which case the user would have to reauthenticate on every page load?
EDIT
Here's the code you shared that remembers the user:
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
$loginUrl = getPath("dropbox-auth-start");
...
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}
I have created an api to import photos from facebook and google+. But I am facing a problem in displaying the list of photos. Can you please resolve this?
My Code Below:
File Name: index.php (Google)
<?php
include_once "google-plus-access.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Google+ API To Fetch Photos</title>
<link rel='stylesheet' href='style.css' />
</head>
<body>
<div id="bar">
<div class="top-area" >
<div class="login" >
<?php if(isset($me) && isset($activities)) { ?>
<a href="?logout" ><h5>Logout</h5></a>
<?php } else { ?>
<a href="<?php echo($authUrl); ?>" ><h5>Login</h5></a>
<?php } ?>
</div>
</div>
</div>
<?php if(isset($me) && isset($activities)) {?>
<div class="big-container" >
<div class="profile" >
<div class="profile-pic" ><a href="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>" ><img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" /></a>
</div>
<div class="profile-info" >
<div class="name" ><a href="<?php echo($me['url']) ; ?>" ><?php if(isset($me['displayName'])) echo(strtoupper($me['displayName'])); else echo "Not set or private"; ?></a></div>
<div class="details" >
<ul>
<li><b>GENDER : </b><?php if(isset($me['gender'])) echo($me['gender']); else echo "Not set or private"; ?></li>
<li><b>ORGANISATION : </b><?php if(isset($me['organizations']['0']['name'])) echo($me['organizations']['0']['name']); else echo "Not set or private"; ?></li>
<li><b>PLACE : </b><?php if(isset($me['placesLived']['0']['value'])) echo($me['placesLived']['0']['value']); else echo "Not set or private"; ?></li>
</ul>
</div>
</div>
</div>
</div>
<?php foreach($activities['items'] as $activity): ?>
<div class="activity" >
<div class="title" ><a href="<?php echo($activity['object']['url']) ; ?>" ><?php echo($activity['object']['content']); ?></a></div>
<p>Published at <?php echo($activity['published']); ?></p>
<p>
<?php echo($activity['object']['replies']['totalItems']); ?> Replies .
<?php echo($activity['object']['plusoners']['totalItems']); ?> Plusoners .
<?php echo($activity['object']['resharers']['totalItems']); ?> Reshares
</p>
</div>
<?php endforeach ?>
<br><br>
<div class="photos">
<?php
if(isset($me['url']))
{
$photos = "https://plus.google.com/photos/";//.$me['id']."/albums";
echo $photos;
}
?>
</div>
<?php } else {?>
<div class="login-box">
<div id="connect-button"><a href="<?php echo($authUrl); ?>" ><img src="connect-button.png" alt="Connect to your Google+ Account"/></a>
<div>This API is purely read-only. It will <b>NOT</b> post anything to your profile.
</div>
</div>
</div>
<?php } ?>
</body>
</html>
File Name: google-plus-access.php
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("picpixa");
//*********** Replace with Your API Credentials **************
$client->setClientId('***********************');
$client->setClientSecret('************************');
$client->setRedirectUri('http://localhost/MyApi/Google-Plus/');
$client->setDeveloperKey('*********************************');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/photos'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
File Name: index.php (Facebook)
<?php
include_once "fbmain.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Fetch Image From Facebook</title>
<script type="text/javascript">
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui({method: 'feed',
message: userPrompt,
link: hrefLink,
caption: hrefTitle,
picture: 'http://thinkdiff.net/ithinkdiff.png'
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
function publishStream() {
streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
}
function newInvite() {
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Come on checkout Personalized Products. visit http://www.picpixa.com',
},
function(receiverUserIds) {
console.log("IDS : " + receiverUserIds.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
</script>
</head>
<body>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: '<?= $fbconfig['appid'] ?>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</script>
<?php if (!$user) { ?>
You have to login using Facebook Login Button to see api calling result.
<img src="Images/login.png">
<?php } else { ?>
<img src="Images/logout.png">
<?php } ?>
<!-- all time check if user session is valid or not -->
<?php if ($user) { ?>
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>
<!-- Data retrived from user profile are shown here -->
<div class="box">
<b>User Photos using Graph API</b>
<?php d($user_photos); ?>
</div>
</td>
</tr>
</table>
<?php }?>
</body>
</html>
File Name: fbmain.php
<?php
$fbconfig['appid'] = "Your App Id";
$fbconfig['secret'] = "Your App Secret";
$fbconfig['baseurl'] = "localhost/MyApi/Facebook/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
try {
include_once "facebook.php";
} catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => false,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_photos',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//Retriving photos of user using graph api
try {
$user_photos = $facebook->api("/$user/photos");
} catch (Exception $o) {
d($o);
}
}
function d($d) {
echo 'This function is called <br><br><pre>';
print_r($d);
echo '</pre>';
}
?>
I am not sure what you expected on the Google+ side. All you are doing for photos, apparently, is printing the URL based on the Google ID. (Assuming the portion that was commented out.)
There is no way using the Google+ API to get the user's photos. You need to look into using the Picasa Web Albums Data API, but this is using Google's older GData protocol. There are a couple of resources that may help, for example, there is a PHP library which uses an older version of the protocol and a more modern example code snippet which may guide you in doing this.
You should star https://code.google.com/p/google-plus-platform/issues/detail?id=670 to indicate you want a more modern API for photos in Google+.