cookies on localhost and hosting - ssl

My code is running smoothly on localhost. But it doesn't work on the web server; cookies are not saved.
if (isset($_POST['user-login-form'])) {
$user_mail = strip_tags(trim($_POST['l_email']));
$user_password = strip_tags(sha1(md5($_POST['l_password'])));
$usercontrol=$db->prepare("SELECT * FROM users where user_mail=:user_mail and user_password=:user_password");
$usercontrol->execute(array( 'user_mail' => $user_mail, 'user_password' => $user_password ));
$userresult=$usercontrol->rowCount();
if ($userresult==1) {
$_SESSION['user_mail']=$user_mail;
$_SESSION['user_password']=$user_password;
if(isset($_POST['checkremember'])){
setcookie("user_remember",$user_mail,strtotime("+10 week"));
} else {
setcookie("user_remember",$user_mail,strtotime("-10 week"));
}
echo "2";
exit;
} else {
echo "1";
exit;
}
}
Previously it worked without problems. I installed an SSL certificate and made several changes to the .htaccess file.
But when you type this on a blank page, the cookie is registered.
Code:
setcookie("user_remember", "deneme", time() + (86400 * 30), "/");
echo $_COOKIE["user_remember"];

my problem is solved.
the problem is that the php file is utf-8 BOM.

Related

refreshTokenWithAssertion Permission Denied

I am trying to use google-api-client in PHP for a project.
I got a "permission denied" response while at this statement:
$client->getAuth()->refreshTokenWithAssertion();
Google_IO_Exception, Message:Failed to connect to 74.125.193.84: Permission denied
File: /home/www/blah.com/restful/libs/Google/IO/Curl.php
Line:81
/home/www/blah.com/restful/libs/Google/IO/Abstract.php(125): Google_IO_Curl->executeRequest(Object(Google_Http_Request))
#1 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(326): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))
#2 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(306): Google_Auth_OAuth2->refreshTokenRequest(Array)
#3 /home/www/blah.com/restful/v2/index.php(122): Google_Auth_OAuth2->refreshTokenWithAssertion()
I checked all my credentials and they look correct, what could be the problem?
Thanks,
John
code:
$client_id = '1234blahblahblah.apps.googleusercontent.com'; //Client ID
$service_account_name = '1234blahblah#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'blahblah-1234.p12'; //key.p12
$client = new Google_Client();
$client->setApplicationName("test");
$service = new Google_Service_Calendar($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
print_r($cred);
$client->setAssertionCredentials($cred);
$client->setClientId($client_id);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
$_SESSION['service_token'] = $client->getAccessToken();
echo $_SESSION['service_token'];
}
Hi John I´ve the same problem and finally this works for me:
Before the lines:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
I put a try catch and that returns me that I had a writtin permissions problem:
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
I could do 2 things:
1) Go to Google/src/Config.php and change line 94: 'directory' => sys_get_temp_dir() . '/Google_Client'and change the directory to save cache temp files
2) or like me, made a echo sys_get_temp_dir(); before the try catch and give a chmod 777 permission to that dir
This solution works for me, I hope also for you. Anyway made an try/catch waiting for the exception message
See the service-account.php sample in the examples/ directory of the Google APIs Client Library for PHP on Github.com:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred); // set credentials there
}

google api v3 redirect_uri_mismatch Error

i am try to get google account authentication for my app, but when i choose the account to log in i get the error redirect_uri_mismatch,
at google console i create Client ID for web application
first i try to run the app on local host with the following settings
REDIRECT URIS : http://localhost/myapppath/
but get the same error
also i try to host my app at heroku with the following Client ID for web application settings
but get the same error, i search many times on stackoverflow with no success to find a solution
this is my code, it is a test code to get the uploaded videos of a user
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* Google Developers Console <https://console.developers.google.com/>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = '42965713xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxercontent.com';
$OAUTH2_CLIENT_SECRET = 'y9AWlbxxxxxxxDqdQwJ';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Call the channels.list method to retrieve information about the
// currently authenticated user's channel.
$channelsResponse = $youtube->channels->listChannels('contentDetails', array(
'mine' => 'true',
));
$htmlBody = '';
foreach ($channelsResponse['items'] as $channel) {
// Extract the unique playlist ID that identifies the list of videos
// uploaded to the channel, and then call the playlistItems.list method
// to retrieve that list.
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50
));
$htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
foreach ($playlistItemsResponse['items'] as $playlistItem) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
$playlistItem['snippet']['resourceId']['videoId']);
}
$htmlBody .= '</ul>';
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
What credentials type you choose depends on the application you want to build. 'Client ID for web application' should work fine for you.
The URIs you specify in Redirect URIs have to point to the actual script file, like http://example.com/index.php. I don't think http://example.com is supposed to work.
i found the solution after replacing this line
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
by this
$redirect = 'http://localhost/myappname';
i do not know why it is not working when it take the full path of the redirect class

How do I make better httpd down checker?

I have apache down checker script (remote server), but I think it doesn't work if httpd has a timeout issue or something similar.
For example, site was offline, but the server was online status.
Should I put timeout stuff or something else? How??
<?php
function GetServerStatus($site, $port)
{
$status = array("OFFLINE", "ONLINE");
$fp = #fsockopen($site, $port, $errno, $errstr, 2);
if (!$fp) {
return $status[0];
} else
{ return $status[1];}
}
?>
<?php
$status = GetServerStatus('xxx.xxx.xxx.xxx',80);
if($status == 'OFFLINE') {
$message = "Server is down now!!";
}
?>
I don't see how this can possibly report incorrectly. You could consider sending a GET / request and timing it out.
You could also consider closing the socket in the success case.

Facebook PHP SDK auth between main domain and multiple subdomains

I really don't manage to make this work. I've tried already all the steps I've found on SO or other websites, but my cross-domain fb authentication doesn't work..
How my auth script looks like:
session_set_cookie_params(0,"/",".my-domain.com");
session_start();
// include facebook class
try {
$fb = new Facebook(array(
'appId' => $facebook_app_id,
'secret' => $facebook_app_secret,
'cookie' => true
));
} catch(FacebookAPIException $e) {
// no active fb session
}
// other content here
try {
$uid = $fb->getUser();
if($uid) {
$user = $fb->api('/me','GET');
}
} catch(FacebookApiException $e) {
// not logged in
}
Now the problem is that this code works perfect on my-domain.com but not on subdomain.my-domain.com.
Even if I successfully authenticate on the main domain my-domain.com, when I'm visiting subdomain.my-domain.com the session of the main domain is replaced and the connection is lost.
Note that in the case of subdomain.my-domain.com there is no API Exception thrown but the $uid is 0.
I've already set the domain on FB APP Settings page as my-domain.com.
Which is the problem here?

Symfony and uploadify

I want to use uploadify with Symfony 1.4, but so far I couldn't.
Uploadify loads correctly, I choose my files, it says that the files were successfully uploaded, but the are nowhere.
(I'm doing this on localhost)
Is there anybody who met this problem before?
Thanks, Tom
$file = $request->getParameter('file');
$filename = sha1($file->getOriginalName()).$file->getExtension($file->getOriginalExtension());
$file->save(sfConfig::get('sf_upload_dir').'/'.$filename);
in my project session stored in cookies so I found solution by create extra session storage class
class MySessionStorage extends sfSessionStorage
{
public function initialize($options = null)
{
$request = sfContext::getInstance()->getRequest();
// work-around for uploadify
if ($request->getParameter('uploadify') == "onUpload")
{
$sessionName = $options["session_name"];
if($value = $request->getParameter($sessionName))
{
session_name($sessionName);
session_id($value);
}
}
parent::initialize($options);
}
}
then changed factories.yml to
all:
storage:
class: MySessionStorage
and then "uploader" param will like this
uploader : '<?php echo url_for("attachments/upload?uploadify=onUpload&" . session_name() . "=" . session_id(), true)?>',
I can only guess that it's because you're trying to upload while logged into a system, but flash does not inherit session data from the browser, this means you will always be denied permission to whatever function you are trying to access since symfony thinks you're not logged in.
So you need to manually set variables in order for flash to use the same login session as the browser:
jQuery Code (needs to be in a php file, will not work in a js file):
$('#file_upload').uploadify({
.... config here
'scriptData': { '<?php echo session_name() ?>': '<?php echo session_id() ?>' }
});