php,api,google-drive-sdk , Newbie Google Drive API (PHP) confusion - what guide/library to use?


Newbie Google Drive API (PHP) confusion - what guide/library to use?

Question:

Tag: php,api,google-drive-sdk

I have a mobile site m.example.com - from a phone I want visitors to choose a file from Google Drive, and send it to the server that hosts m.example.com. Essentially emulating a simple <input type="file"> file upload as on a desktop.

From what I understand the workflow is as follows:

1) User picks file with Picker which sends meta data of the chosen file to my website client (i.e. the HTML/Javascript running on the phone/tablet)

2) I send that to my server via ajax or just a form hidden field

3) my server makes a request to the Google API to get the file and then stores it in the server's file system

So I need help on:

a) is the above steps correct, and is there any other way to do this, or even a service I can use that will allow my site users to pick their files from one of several cloud storage providors?

a) assuming my steps are correct and this is the only way, I am stuck on the 3) part - server talking to the API.

So far I've ceated the picker as per here - Google picker auth popup is being blocked and got the file URL. I've not done 2) yet, I'm just manually putting the file URL into my downlaod script for now.

I'm using PHP and the file I'll want to downlaod to my server could be public or private, that depends on the end user.

I'm lost in the API docs (as in man pages, not a google doc) and am confused with https://developers.google.com/api-client-library/php/start/get_started (call this API docs)and https://developers.google.com/drive/web/quickstart/quickstart-php (call this Drive docs) - are these two different APIs?

I followed the links from the API docs and installed the client from here : https://github.com/google/google-api-php-client, but when trying "Step 3: Set up the sample" on the Drive docs I get many errors such as files not found, class not fount etc, so that makes me think therr is two different APIs/Clients being documented here - can someone please point me in the right direction to get started?

UPDATE

I've re installed the PHP client vis the github linked from this https://developers.google.com/api-client-library/php/start/get_started

This is that it looks like:

enter image description here

I ran the simplefileupload.php in the examples directory - worked first time, only had to put in my project details

So went to https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample and created drive_rest_api_step_3.php in root of google-api (as shown in screen grab)

Got Fatal error: require_once(): Failed opening required 'src/Google_Client.php' (include_path='.:/usr/local/lib/php') in /path/to/google-api/drive_rest_api_step_3.php on line 5

There is no Google_Client.php in the library, but there is src/Google/Client.php so I edit the require_once to use that.

Now get Failed opening required 'src/contrib/Google_DriveService.php' - again a search for that file yeilds no results, but there is a src/Google/Service/Drive.php, so edit example to use that:

Requires (on https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample) was:

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

Now:

require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Drive.php';

Now getting Fatal error: Class 'Google_Service' not found in /path/to/google-api/src/Google/Service/Drive.php on line 32

So this is why I think there is an issues with the two sets of guides, either they use different libraries, or https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample is out of date, even though is says Last updated March 30, 2015.


Answer:

You are right in that the drive quickstart guide is outdated, it refers to the old version of Google's PHP Client API Library that is on Google Code, rather than the newer one on GitHub. Hence the quickstart guide doesn't work with the PHP Client Library you downloaded. In addition, the quickstart guide code is intended to be executed in PHP command-line mode rather than on the server.

To answer the question, I've put in a few sub-answers:

  1. How to use the PHP Client Library
  2. How to pick a file with the Google Picker and get the file onto the server

Using the Google PHP Client Library with the Google Drive API

Try this page instead: https://developers.google.com/api-client-library/php/auth/web-app which has an example showing how to list files on a user's Google Drive using the new PHP library, including the whole OAuth procedure.

Unfortunately, even that is a bit outdated (the include path is outdated and is now deprecated). As such (and for StackOverflow's completeness sake) here's some code. I used a subdirectory drivetest in my web server root; change the URLs as necessary.

Do note that you need to get the client ID for "Web applications" in Google's Developer Console, and download the JSON (replacing the client_secrets.json in the code as necessary).

drivetest/quickstart.php

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        $drive_service = new Google_Service_Drive($client);
        $files_list = $drive_service->files->listFiles(array())->getItems();
        echo json_encode($files_list);
    } else {
        $redirect_uri = 'http://localhost/drivetest/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }   

?>

drivetest/oauth2callback.php

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->setRedirectUri('http://localhost/drivetest/oauth2callback.php');
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

    if (! isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'http://localhost/drivetest/quickstart.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

?>

Use the Google File Picker to pick files

For your use case, you are probably better off using the Google Picker https://developers.google.com/picker/docs/ which implements the whole browse-and-select-file thing for you, and just gives an ID to the file. A summary of the steps required:

  1. Get access token (authentication)
  2. Use picker to let user pick file
  3. Use file ID returned from picker to get download URL
  4. Download file from download URL

We can do this in two ways (client-side or server-side):

Method 1: Client-side

Using this method, steps 1 - 3 are done in Javascript, and only step 4 is done in PHP. With this method we don't even need the PHP client library!

Here's an example (adapted from sample code in the above link and http://webdevrefinery.com/forums/topic/12931-dropbox-google-drive-file-pickers/):

picker.html

This file launches the filepicker upon page load and puts the URL into a form.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Picker Example</title>


        <script type="text/javascript">

            // The Browser API key obtained from the Google Developers Console.
            var developerKey = '';

            // The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
            var clientId = ""

            // Replace with your own App ID. (Its the first number in your Client ID)
            var appId = ""

            // Scope to use to access user's Drive items.
            var scope = ['https://www.googleapis.com/auth/drive'];

            var pickerApiLoaded = false;
            var oauthToken;

            // Use the Google API Loader script to load the google.picker script.
            function loadPicker() {
                gapi.load('auth', {'callback': onAuthApiLoad});
                gapi.load('picker', {'callback': onPickerApiLoad});
            }

            function onAuthApiLoad() {
                window.gapi.auth.authorize(
                {
                    'client_id': clientId,
                    'scope': scope,
                    'immediate': false
                },
                handleAuthResult);
            }

            function onPickerApiLoad() {
                pickerApiLoaded = true;
                createPicker();
            }

            function handleAuthResult(authResult) {
                if (authResult && !authResult.error) {
                    oauthToken = authResult.access_token;
                    createPicker();
                }
            }

            // Create and render a Picker object
            function createPicker() {
                if (pickerApiLoaded && oauthToken) {                
                    var view = new google.picker.DocsView();
                    view.setIncludeFolders(true);
                    //view.setMimeTypes("image/png,image/jpeg,image/jpg");

                    var picker = new google.picker.PickerBuilder()
                    //.enableFeature(google.picker.Feature.NAV_HIDDEN)
                    //.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                    .setAppId(appId)
                    .setOAuthToken(oauthToken)
                    .addView(view)
                    .setDeveloperKey(developerKey)
                    .setCallback(pickerCallback)
                    .build();
                    picker.setVisible(true);
                }
            }

            // A simple callback implementation.
            function pickerCallback(data) {
                if (data.action == google.picker.Action.PICKED) {
                    var fileId = data.docs[0].id;

                    gapi.client.load('drive', 'v2', function() {
                        var request = gapi.client.drive.files.get({
                            fileId: fileId
                        });
                        request.execute(processFile);           
                    });

                }
            }

            function processFile(file) {
                var token = gapi.auth.getToken();
                // console.log(file);
                // console.log(token);
                document.getElementById("fileurl").value = file.downloadUrl+"&access_token="+token.access_token;
            }
        </script>
    </head>
    <body>
        <form action="submit.php" method="post">
            <label for="fileurl">File Download URL</label><input type="text" name="fileurl" id="fileurl">
            <input type="submit">
        </form>

        <!-- The Google API Loader script. -->
        <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
        <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
    </body>
</html>

We then submit the form to a PHP script to download the file on the server. The trick here is that we also need to pass the access token from the client to the server, since the user is not authenticated on the server side. Surprisingly, you can simply append the access_token parameter to authenticate the download of the file, as shown above.

submit.php

Use file_get_contents or CURL, depending on what your server supports. HTTPS support is required for this to work though.

<?php

    $filename = 'temp.jpg';

    $ch = curl_init($_POST['fileurl']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Should verify in production!
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    //echo 'Curl error: ' . curl_error($ch);
    curl_close($ch);

    file_put_contents($filename, $data);

?>

A more official way (following https://developers.google.com/drive/web/manage-downloads#alternate_method_using_downloadurl) is to send the authorization token separately using the Authorization header. Modify the Javascript above to send the download URL and token separately, then use something like the code below instead. If you want to use file_get_contents, see PHP file_get_contents() and headers on how to send custom headers. Note that you need to have the Bearer word before the token!

<?php

    $filename = 'temp.jpg';

    $ch = curl_init($_POST['fileurl']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$_POST['authtoken']));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $data = curl_exec($ch);
    echo 'Curl error: ' . curl_error($ch);
    curl_close($ch);

    file_put_contents($filename, $data);

?>

Method 2: Server-side (using PHP)

Using this method, steps 1, 3 and 4 are done in PHP, and only step 2 is done in Javascript.

quickstart.php

This page checks if there is an access token in the session, if there is not it redirects the user for authentication. If there is, it shows the picker and a form. In the picker Javascript code, note that the oAuthToken used is obtained with PHP from the server! Source: Use Google Picker without logging in with Google account (with OAuth). The form then submits a POST request to this page and the file is downloaded.

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    // Ref: https://developers.google.com/drive/v2/reference/files/get
    function downloadFile($service, $file) {
        $downloadUrl = $file->getDownloadUrl();
        if ($downloadUrl) {
            $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
            $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
            if ($httpRequest->getResponseHttpCode() == 200) {
                return $httpRequest->getResponseBody();
                } else {
                // An error occurred.
                return null;
            }
            } else {
            // The file doesn't have any content stored on Drive.
            return null;
        }
    }

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->addScope(Google_Service_Drive::DRIVE_READONLY);

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        if (isset($_POST['fileid'])){           
            $drive_service = new Google_Service_Drive($client);
            $file = $drive_service->files->get($_POST['fileid']);
            $data = downloadFile($drive_service, $file);
            file_put_contents('temp.jpg', $data);

            echo "file uploaded";
            exit();
        }
    } else {
        $redirect_uri = 'http://localhost/drivepicker-php/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        exit();
    }   

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Picker Example</title>


        <script type="text/javascript">

            // The Browser API key obtained from the Google Developers Console.
            var developerKey = '';

            // Replace with your own App ID. (Its the first number in your Client ID)
            var appId = ""

            var pickerApiLoaded = false;

            // Use the Google API Loader script to load the google.picker script.
            function loadPicker() {
                gapi.load('picker', {'callback': onPickerApiLoad});
            }

            function onPickerApiLoad() {
                pickerApiLoaded = true;
                createPicker();
            }

            // Create and render a Picker object
            function createPicker() {
                if (pickerApiLoaded) {              
                    var view = new google.picker.DocsView();
                    view.setIncludeFolders(true);
                    //view.setMimeTypes("image/png,image/jpeg,image/jpg");

                    var picker = new google.picker.PickerBuilder()
                    //.enableFeature(google.picker.Feature.NAV_HIDDEN)
                    //.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                    .setAppId(appId)
                    .setOAuthToken('<?= json_decode($client->getAccessToken())->access_token; ?>')
                    .addView(view)
                    .setDeveloperKey(developerKey)
                    .setCallback(pickerCallback)
                    .build();
                    picker.setVisible(true);
                }
            }

            // A simple callback implementation.
            function pickerCallback(data) {
                if (data.action == google.picker.Action.PICKED) {
                    var fileId = data.docs[0].id;
                    document.getElementById("fileid").value = fileId;

                }
            }
        </script>
    </head>
    <body>
        <form action="quickstart.php" method="post">
            <label for="fileid">File ID</label><input type="text" name="fileid" id="fileid">
            <input type="submit">
        </form>

        <!-- The Google API Loader script. -->
        <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
        <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
    </body>
</html>

oauth2callback.php

Helper file for the OAuth callback.

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->setRedirectUri('http://localhost/drivepicker-php/oauth2callback.php');
    $client->addScope(Google_Service_Drive::DRIVE_READONLY);

    if (!isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'http://localhost/drivepicker-php/quickstart.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

?>

Related:


Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

Is it a good practise store the checkout steps fields in php $_SESSION?


php,session,e-commerce,checkout
I have my e-commerce site with three checkout steps, each button to continue is a POST action and redirect to the next step: if the user navigates by the checkout steps (click on the previous button for example), the form fields don´t show the data posted previously. This form fields...

How can we validate multiple fields with one validation in cakePHP 2.0?


php,cakephp
how can we check firstname and last name is unique validation in cakePHP ? record1: first name :raj last name: kumar if we enter same name in input field , it should show validation message "Record alredy Exists". i know how to validate single field validation. how to validate that...

Cant submit form


javascript,php
Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did. <input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/> a querystring is required...

Mixing


php
This question already has an answer here: <? ?> tags not working in php 5.3.1 5 answers I had to made some changes to an old PHP-Project (with very poor code quality...) which runs on an PHP 5.3 server. So I've downloaded the project and tried to run it...

How to secure configuration file containing database username and password


php,security
Issue In order to connect my PHP code with MySQL database I use PDO way, creating variable, assigning it with new PDO object where arguments contain settings such as server, database, login and password. So in resulting code it could look like this: $DAcess=new PDO("mysql:host=server;dbname=database","login","password"); I don't feel comfortable having...

What are correct permissions for Linux Apache2 PHP 5.3 log file?


php,linux,apache,logging,permissions
I discovered the reason why I was not getting entries into my php_errors.log file related to permissions. Right now, I have set it to 666 (rw-rw-rw-) but surely this is a security weakness? Thus, my question. php.ini file: error_log /var/log/httpd/php_errors.log log_errors On # ls -ld /var/log /var/log/httpd /var/log/httpd/php_errors.log drwxr-xr-x 6...

How to pass a value from a page to another page in PHP


php
Im trying to pass a variable value from a page to another page. Im using to go to the next page and I use Session to get the value, the link variable does working but the price variable doesn't work Here's the code: index.php <?php require('connect.php'); if(!isset($_SESSION)){ session_start(); } $query...

How to Match a string with the format: “20959WC-01” in php?


php,regex
i want to restrict a user to enter a value which is similar to the value "20959WC-01", means it must contains 5 integers followed by two character, a '-' and two integers, can anyone please give me a solution to sort out this problem. Thanks in advance :) ...

compare today's date with unix timestamp value in database


php,mysql
In database I am storing date value unix timestamp value for e.g.'1434952110' using time() now I am trying to compare todays value with this value as below $jobpostdate = date("Y-m-d");//today's date passing in database to compare query $sql = "SELECT jsp_title, jsp_subtitle, jsp_desc, jsp_location, jsp_date "; $sql .= "FROM js_projects...

WooCommerce seems to only orderby date and not price


php,ajax,wordpress,woocommerce
I am loading in variable products via a custom WP_Query $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'date', 'order' => 'desc' ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="product-node cat-beast-balls">...

mysql_real_escape_string creates \ in server only not in local


php,sql
When I use mysql_real_escape_string in my localhost and I output the result of html in a table I have no problem. But when I use it on my server it outputs even the \ This is how I use it: $_GETVARS['txtEmpNum'] = mysql_real_escape_string($_GETVARS['txtEmpNum']); $_GETVARS['txtLName'] = mysql_real_escape_string($_GETVARS['txtLName']); $_GETVARS['txtFName'] = mysql_real_escape_string($_GETVARS['txtFName']); $varSQL...

Rewrite url not working in htaccess


php,apache,.htaccess,mod-rewrite,url-rewriting
I have website. I just want to rewrite url using .htaccess Here is the code which I want to rewrite: RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} /search_data.php\?keywords=([^&]+)&f=([^\s&]+) [NC] RewriteRule ^/search_data.php/?$ /search/%1/%2? [R=301,L,NC] this the current url http://localhost/mywbsite/search_data.php?keywords=one+piece&f=149 I want to convert this to this http://localhost/mywbsite/search/one-piece/149 I tried above code but...

Time format conversion with PHP


php,time
If have the duration for a recipe in the format 1H10M (1 hour, 10 minutes) or 20M (20 minutes). I want to use the format as described in the parentheses. I've tried using strtotime() without luck. Any help would be greatly appreciated....

array and function php


php,arrays
I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. If you could help me, I'd be much obliged. I'm having trouble understanding why the following code doesn't work. <?php function sum($x, $y) { $z = $x + $y;...

How to register global variable for my Laravel application?


php,laravel,laravel-5
I have started with Laravel a few days ago, and today I just installed the vespakoen/menu that seems to be very nice, and probably will work for what I need it. Currently I have installed Laravel 5.1 on my system. The problem I currently have, is where to register my...

REST API with token based authentication


angularjs,codeigniter,api,rest,token
I want to develop a web site with AngularJS. On the backend side I will use Codeigniter REST framework. I have some security issues and I don't want to start developing without fixing them on my mind. I don't want to use something like api key because it will be...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)


php,mysql,mysqli,sql-injection,sql-insert
I am new to PHP and hope someone can help me with this. I would like to store two values (an email and a password) in a MySQL db using PHP. The input is passed to the PHP page via Ajax in jQuery (through an onclick event on a website)....

Error connecting to MSSQL using PHP


php,sql-server,pdo,odbc,sqlsrv
I am receiving an error as below: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87]. ' My codes are as follow: $this->link = new PDO( "sqlsrv:server=$this->serverName:$this->port;Database=$this->db", "$this->uid", "$this->pwd" ); I wish someone can enlighten...

When I click to the next page on pagination,it goes to 404 error in codeigniter


php,codeigniter,pagination
In my News.phpcontroller,i'm having the below code: public function index() { $data['title'] = 'Database Details'; $config = array(); $config['base_url'] = base_url("news/index"); $config['total_rows'] = $this->news_model->record_count(); $config['per_page'] = 5; $config['uri_segment'] = 3; //$config['use_page_numbers'] = TRUE; // $config['page_query_string'] = TRUE; $choice = $config["total_rows"] / $config["per_page"]; $config["num_links"] = round($choice); $this->pagination->initialize($config); $page =...

How do I display my mysql table column headers in my php/html output?


php,html,mysql,table,data
2 Questions... Scenario: I would like to query my database table via a form and then display the results that occur(if there are results) and my current situation is that it does work but it clears the form completely and leaves my to an empty page with just the results...

how to multiply two column names using codeigniter validation rule


php,codeigniter,validation
I have three columns.The product of two columns get into third column name income_amount using codeigniter validation rule.the first column is crop_quantity and the second is per_rate controller $this->form_validation->set_rules('crop_quantity', 'Crop Quantity', 'required|numeric'); $this->form_validation->set_rules('per_rate', 'Per Rate', 'required|numeric|callback_get_product'); $this->form_validation->set_rules('income_amount', 'Income Amount', 'required|numeric');...

Click on link next link should be display on same page


javascript,php,jquery,html,css3
I have a single page website and need to link the navigation to IDs in the page. I have three links: "About us", "Our Project", "contact". So if user clicks on "About ", the About section will be displayed, same with other links. Inside Our project there is Two buttons...

Laravel Interfaces


php,laravel,interface,namespaces
I used the following tutorial to get an idea about interfaces: http://vegibit.com/what-is-a-laravel-interface/ But I wanted to change the directory of where I am putting my interfaces to "App/Models/Interfaces". And so I did. But now I cannot get it to work anymore. Here is my code: Routes.php App::bind('CarInterface', 'Subaru'); Route::get('subaru', function()...

Composer dump-autoload gives preg_match error


php,composer-php,autoload
I have Composer in my PHP project installed, and want to use the autoloader. On this page I read how the composer.json file should look like and that I should run the command dump-autoload. My composer.json file looks as follows { "require-dev":{ "phpunit/phpunit":"4.5.*", "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } }...

how to escape php code in echo with javascript


javascript,php
how can i escape this : var tab_mois_nb_match = <?php ".json_encode($tab_mois_nb_match)." ;?> ; I have an code error, but the arrays are generate with sussess in the conle.log, it's totally crazy. foreach($tab_bases2 as $key => $univers){ $tab_nb_match_par_user = users_nb_match($univers); $tab_mois_nb_match = mois_nb_match($univers); echo "<div id='".$univers."' ></div>"; echo "<script type='text/JavaScript'> var...

Dynamically select from a dynamically generated dropdown


php,html,select,drop-down-menu
I have a dynamically generated dropdown list - list of course identifiers and names. On the basis of a variable, “assigned_course_id”, I would like to preselect the appropriate value from the dropdown list. My best attempt is as follows. Thanks in advance for your assistance. <select name="course_id" id="course_id"> <?php $assigned_course_id...

Why am getting this error?: Unknown column 'firstname' in 'field list'


php,database,mysqli
if(isset($_POST["submit"])) { // Details for inserting into the database $id = htmlentities($_POST["id"]); $firstname = htmlspecialchars($_POST["firstname"]); $lastname = htmlspecialchars($_POST["lastname"]); $username = htmlspecialchars($_POST["username"]); $password = htmlspecialchars($_POST["password"]); // Dealing with inserting $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; $result = mysqli_query($connection,$query);...

How to search images by name inside a folder?


php,mysql,image
I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside. I use this PHP code to display the photos from...

Jquery parsley validate not working


javascript,php,jquery,ajax,parsley.js
if($("#dataform").parsley().isValid()){ $.ajax({ url : '<?php echo base_url();?>index.php/company/final_review?id=<?php echo $this->input->get('id'); ?>', type : 'POST', data : $("#dataform").serialize(), dataType:"json", beforeSend: function(){ $('#remarks').parsley( 'addConstraint', { minlength: 5 }); }, success : function(data){ console.log(data); } }); } This is my ajax part. The plugin is not validating the field it's submitting the form. The...

How to modify CodeIgniter calendar to handle multiple events per day?


php,codeigniter,calendar
I am creating a calendar without jquery calendar plugin. I could retrieve the data which is in the database to the calendar. But when there are multiple data per day only one data comes to the calendar view. I want it to be like this when there is multiple data....

Removing Alert When Using DeleteFile API


vb.net,vba,api,delete
I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

Pull information from SQL database and getting login errors


php,sql,database
I am creating a very small, simple CRM for a company, they require the function to be able to view the last 25 orders via the dashboard. The orders are added via a Order-add form within the CRM. When adding the following code to the CRM I get an error:...

MySQL Query returning strange values


php,mysql
The query is supposed to do the following: Obtain the question and associated answers based on the identification number of the question. (In this case the identification number is called account_id. Order them so that each question (and it's appropriate answers) are lined up in order. The query: SELECT *...

access the json encoded object returned by php in jquery


php,jquery,ajax,json
I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

PHP Regular Expressions Counting starting consonants in a string


php,regex
I need to find out how many starting consonants a word has. The number is used later in the program. The code below does work, I am wondering if it is possible to do this with a regular expression. $mystring ="SomeStringExample"; $mystring2 =("bcdfghjklmnpqrstvwxyzABCDFGHJKLMNPQRSTWVXYZ"); $var = strspn($mystring, $mystring2); Using a regular...

RecursiveIteratorIterator to fetch subdirectories


php
Currently I am working with directories through php. I am able to list subdirectories for any given directory. However, the results are not 100% what I am looking for. The below code returns subdirectories but in addition it also returns the main directory in the array. How can I only...

Wordpress log out using URL and redirect to specify page


javascript,php,wordpress
I have one Wordpress installation . i need to log out the user without any indication user is coming from particular URL.Is it possible? My code: <?php if($_GET['logout'] == 1) { $redirect_to = current_page_url(); ?> <script> window.location.href="<?php echo wp_logout_url( $redirect_to ); ?>"; </script> <?php } ?> I am using above...

php include capitalization on files


php
This example works fine on my localhost (both files are included), but on my server only the second one is: <?php include('Test.php'); echo '<br/>'; include('test.php'); ?> The only difference is the caps on the second include, so I was trying to figure out how to make the caps not matter....

WooCommerce: How to display Category Name in single-product.php


php,wordpress,woocommerce
How can I display the category name in single-product.php? In archive-product.php the code is: <?php woocommerce_page_title(); ?> but what could I use to show the category name in the single-product.php that belong to the category?...

How can I replace the white rectangle within an image using ImageMagick?


php,image-processing,imagemagick
Overview: The first picture is my original image. Here I want to replace the white rectangle shown with another image. My approach: I have created a mask image using floodfill and it looks as: Problem: Now I would like to get the distance or co-ordinates of the rectangle in the...

Codeigniter PHP Mailer, Sender Info


php,email,codeigniter-2,phpmailer,contact-form
I'm using Codeigniter PHP Mailer which is hosted here: https://github.com/ivantcholakov/codeigniter-phpmailer/ and with gmail smtp it works flawless. However,using it for a standard contact form, when visitors use that contact form and send us an email, they basically send mails from our mail address to our another mail addess. When they...

Php Mysql Query not working properly


php,mysql
I have a table name tblnetworkstatus and I have 11 columns Id issue_name affected_server affected_service issue_type priority duration status start_date end_date description I am getting id in affected_server and affected_service which I am storing in my DB, now I have three situations Either both affected_server and affected_service has been selected...

Laravel 4.2 Sending email error


php,email,laravel,laravel-4
Hello everyone I have an error in laravel when I am sending an email. I have a form with a select tag and when I select the user and click submit I need to send him a mail after I select it. Here is my Controller method: public function store()...

php redirection working in chorme but not on firefox


php,google-chrome,mozilla
Below is my php code that caries out the redirection Code Snippet :- echo "<form action='exp_yogesh.php?id=$id' method='post'>"; echo "<td> <input type='image' name='putonline' value='$id' src='images/on_button.png' no-repeat; border:none;' alt='submit'> </td> "; echo "<td> <input type='image' name='putoffline' value='$id' src='images/off_botton.png' no-repeat; border:none;' alt='submit'> </td> "; echo "</form>"; Here's the exp_yogesh.php file <?php include 'includes/connection.php';...

Include both local and server at the same time


php
I have an include statement in my program: include_once("C:/apache2.2/htdocs/AdminTool/includes/functions.php"); //include_once("/var/www/AdminTool/includes/functions.php"); I only use one at a time. In the code above I am using it for my localhost. But if I will run it on server, I have to comment the local one. Because it will cause error. Is there...

$http.get returns actual php script instead of running it (yeoman, grunt)


php,angularjs,pdo,gruntjs
I'm building a "simple" AngularJS app with an articles newsfeed. My articles are stored in a mysql database, and I extract them using php PDO. I used to do this using AJAX with a simple LAMP configuration (php5, mysql, apache2), and everything worked as intended. Now I'm trying to rebuild...

Trying to rewrite mysql_* to pdo


php,mysql,pdo
First of all I should say that I started to learn PDO and trying to rewrite some old mine codes. Here is one that I found on tutorial for a jquery/ajax/pdo/mysql comment system which is working. This is the mysql_* part which I'm trying to rewrite -> file submit.php which...

Using Graph API Explorer gets friends list but my own app doesn't . (Graph API Explorer token v.s App Token)


facebook,api,facebook-graph-api
I am trying to get my friends list in my app. If I use the access token in my Graph API Explorer console and hit the url. https://graph.facebook.com/v2.3/me?access_token='GraphAPIToken'. I am able to get the complete friends list. If I try using the SDK or any library like fbgraph for nodejs...

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...