php file_put_contents giving me permission errors - php

The site I am working on- http://24.236.131.128/
This is a site using the snapchat API. I can log into my snapchat account and SHOULD see the snaps I have that are unopened.
I can log in just fine, and view my friends or list of snaps. I can NOT, however, get the image to display or save to the path.
I get a Warning:
file_put_contents(media/download/from_lolnope47_to_lolnope47_id_959644398384684466r.jpg): failed to open stream: Permission denied in C:\inetpub\wwwroot\index.php on line 114 View pic...
the C:\inetpub\wwwroot\media\download\ folder has full permissions set to the IUSR account for IIS, not too sure if that's the problem?
Any suggestions?
EDIT:
Here is the function to download the snap:
if ($id == 'download')
{
echo '<title>Download picture</title>';
$snapchat = new Snapchat($_SESSION['name'],$_SESSION['pass']);
$snapid = $_GET['snapid'];
$sender = $_GET['sender'];
$recipient = $_GET['recipient'];
$data = $snapchat->getMedia($snapid);
$prePath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.'.jpg';
if (file_exists($prePath))
{
$finalPath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
else
{
$finalPath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.'.jpg';
}
//echo "<img src='$data'></img>";
file_put_contents($finalPath, $data);
echo 'View pic...';
}

Try saving the image to the same folder where your php script is, you also need to set permissions all to the same user that php.exe is running, in last case scenario set permissions all to user everyone ( this is dangerous!).
Try using the full path C:/inetpub/wwwroot/media/download/... instead of the relative path media/download

Related

Show Google Drive video on a website using service account

I'm trying to get a video from my google drive account and publish it on my website.
The idea is to authorize the access to the file using a service account, so the video will be "public" accessible without the user using his google credentials.
Right now for the images I download them and the show it from my server, but due to storage space I would prefer not doing the same for videos
Here's my code:
$client = getGoogleClient(); // Specify the CLIENT_ID of the app that accesses the backend
$service = new Google_Service_Drive($client);
switch ($type) {
case 1: //video
$startPos=strrpos($url['URL'], "file/d")+7;
if($startPos>7)
{
$endPos=strrpos($url['URL'],"/");
$url=substr($url['URL'],$startPos,$endPos-$startPos); //its the file id
}
// Get files from our request
$file = $service->files->get($url,array("fields"=>"webContentLink"));
$customData=$file->webContentLink;
$customclass="hasVideo";
break;
case 3: //img
if(is_null($img))
{
//we have to donwload the file and store it temporaly
//find img id
$startPos=strrpos($url['URL'], "file/d")+7;
if($startPos>7)
{
$endPos=strrpos($url['URL'],"/");
$url=substr($url['URL'],$startPos,$endPos-$startPos);
$content = $service->files->get($url, array("alt" => "media"));
// Open file handle for output.
$filePath="./cachedFiles/".uniqid().".jpg";
$outHandle = fopen($filePath, "w+");
// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.
while (!$content->getBody()->eof())
fwrite($outHandle, $content->getBody()->read(1024));
// Close output file handle.
fclose($outHandle);
$connection->runQuery("UPDATE File_Elemento SET cachedFile='".$filePath."', lastCached='".date('Y-m-d H:m:s')."' WHERE ID=".$ID);
}
else
$type=0;
}
else
$filePath=$img;
require_once('./ImageCache/ImageCache.php');
$imagecache = new ImageCache\ImageCache();
$imagecache->cached_image_directory = dirname(__FILE__) . '/cachedImg';
$filePath = $imagecache->cache( $filePath );
break;
default:
break;
}
echo '<a onclick="showDetail(this,\''.$customData.'\')" class="grid-item '.($subject ? $subject : "Generico").' '.($customclass!="" ? $customclass : "").'"><div class="card newsCard">'.($type==3 ? '<img class="lazy-load imgPrev" data-src="'.$filePath.'">' : "").'<h3>'.$school.'</h3><h1>'.$name.'</h1>';
echo '<div class="prev">'.$subject.'</div><span class="goin mainColor">Visualizza</span></div></a>';
right now I tried to get the webContentLink and then put the url I get as source for a video tag, but I get a 403 error, so still I didn't authorize the access using the service account
Any help would be appreciated
Embedding the webContentLink to your website won't make this publicly available. The webContentLink is as restricted as the file itself: it can only be accessed by users with which the file has been shared.
So you should do one of these:
Make this video public (via Permissions: create, or through the UI itself) (role: reader and type: anyone).
Download it serve it from your server, as with your images.
Related:
Generating a downloadable link for a private file uploaded in the Google drive

Restrict access of an uploaded file to only the original author in a web application

Ex: a user login to a website and uploads a profile pic. I want to restrict the access to only allow the user that uploads the pic gets to have access.
So, if a second person somehow gets the URL to the pic, he or she still can not access it because she or he doesn't have the right permission(https://example.com/profile_pic_mike_1). Right now i have it so that the user can upload a profile pic but then anyone that has the URL are able to type in the browser and see the pic. I dont want that.
This is a project for fun so all suggestions are welcome.
Create a script that's only accessible to logged in users. Have that script fetch the image and display on screen.
Your users access the following url:
example.com/image.php?name=image
You then have image.php fetch the file from disk/database, and return it to the user. A quick example assuming you're working with jpeg images (excluding error checking):
<?php
if(!logged_in())
die('Unauthorized');
$filename = '/path/to/images/' . $_GET['name'];
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
header('content-type: ' . image_type_to_mime_type(IMAGETYPE_JPEG));
echo $contents;
Other image mime types can be found here: image_type_to_mime_type
You can code a PHP file that will check if user is logged in, or if users have the permission to access the file.
I'll assume your public directory is public_html.
For the storage of images, you'll need to store them outside of the public directory (public_html).
Example Code (e.g. image.php?file=profile_pic_mike_1). image.php is in public_html and profile_pic_mike_1 will be in the directory that is not accessible to the public.
<?php
// checking for $_SESSION, change accordingly to your method
session_start();
if(!$_SESSION['logged_in']){
session_destroy();
header("Location:index.php");
}
// $_GET['file'] will be profile_pic_mike_1
if(isset($_GET['file'])){
$file_dir = "../";
$file = $file_dir . $_GET["file"];
// get if user has the permission
// if yes, assign `true` to $permission ($permission = true;)
if (!file_exists($file)) {
echo "File not found.";
} else if (!$permission) {
echo "You do not have the permission to view this image.";
} else {
// You'll need to change the Content-type accordingly
header("Content-type: image/png");
readfile($file);
exit;
}
}
?>
List of Content-type for images: http://php.net/manual/en/function.image-type-to-mime-type.php.
You'll need to check if the user has the permission to view the file, one way to do it by saving the permissions in a MySQL DB.
You'll have to write the functions and flesh out a bit, but it gives you an idea:
<?php
$username = get_username_from_url();
$user = get_logged_in_user();
if(!$user || ($username !== $user->name)) {
// access denied, send appropriate header and exit.
}
// keep your images outside your web root (not public).
// e.g. /path/to/app/data/uploads/unique_id.jpg
$avatar_path = get_avatar_file_path_by_user($user);
// send image file
header("Content-type: image/jpeg"); // or appropriate content type.
readfile($avatar_path);

Drupal 7 failed to open stream: Permission denied in image_gd_save()

I am trying to generate and scaled image for thumbnails, scaling image has no problem and when use
image_save($_image) // Works Fine
(using the same folder an replacing) this code has not problem, the problem starts when I tried to save images in another destination folder using destination parameter:
image_save($_image, $destination) //throws errors
then the error occurs:
Warning: imagejpeg(C:\xampp\htdocs\drupal-devel\sites\default\files): failed to open stream: Permission denied in image_gd_save() (line 284 of C:\xampp\htdocs\drupal-devel\modules\system\image.gd.inc).
I'm working into a Windows xampp and using the function is_write of PHP, return true, no problem with permissions.
I had been trying for a time and I don't know what's happening, no problem with permissions.
This is my code:
$destination = 'public://gallery/thumbs/';
$filepath = drupal_get_path('module', 'gallery_blueprint') . '/img/large/1.jpg'
// Someplace before function
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
_generate_thumb($filepath,$destionation,300,NULL);
// Function code
function _generate_thumb($filepath, $destination_path, $width = NULL, $height = NULL) {
$_img = image_load($filepath);
$scaled = image_scale($_img, $width, $height); // Return true
$result = image_save($_img, $destination_path); //Error occurs whit destination path
return $result;
}
Is an stupid answer but will be written.
the function image_save() when you pass throw the $destination folder, it doesn't write the name by default, finally you need to write a final absolute name path, the name of file is required or throws.
Warning: imagejpeg(C:\xampp\htdocs\drupal-devel\sites\default\files): failed to open stream: Permission denied in image_gd_save() (line 284 of C:\xampp\htdocs\drupal-devel\modules\system\image.gd.inc).
//finally you need to write whole filepath
image_save($_img, $finalname_path) //$filname_path = public://gallery/thumbs/1.jpg

PHP permission Denied using unlink and rmdir

i've been trying to figure out why my Php code is giving me a annoying error. I've tried countless functions from previous post but the error its been giving is "Permission Denied". From my understanding either i have to have special privledges to delete files, etc.. I've tried multiple solutions but I'm still getting this error. If anyone can point me in the right direction, that'll be great. Ive post a snippet of my code below.. Thanksss
$first_sub = "my_dir";
if(is_dir($first_sub)){
$read_sub1 = opendir($first_sub);
while(false !== ($files = readdir($read_sub1))){
if($files!="." && $files!=".."){
unlink($first_sub ."/". $files);
}
}
closedir($read_sub1);
You should set proper permission to your server directories:
Visit: http://bd1.php.net/chmod
<?php
// Read and write for owner, nothing for everybody else
chmod($first_sub ."/". $files, 0600);
// Read and write for owner, read for everybody else
chmod($first_sub ."/". $files, 0644);
// Everything for owner, read and execute for others
chmod($first_sub ."/". $files, 0755);
// Everything for owner, read and execute for owner's group
chmod($first_sub ."/". $files, 0750);
?>
just before unlink you can call this function.
I got that an error from unlink permission denied.
But I fix it. The error displays like this unlink(../foldername/) Permission denied.
My wrong code is like this:
$image = select_table('webpage', 'wp_name', '$id');
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image_dir) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
now i fix it
my correct code is like this:
$image = select_table('webpage', 'wp_name', $id);
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image['wp_image']) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
For those who land on this page, it may be as simple as not setting $files to an existing file.
It is unfortunate, but I found that the message: Warning: move_uploaded_file(): Unable to move can also mean file not found.
Not likely the cause of this OP's problem, but certainly worth verifying the file represented by the variable you pass actually exists in the directory.

can someone help me fix my code?

I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}
Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.
Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.

Categories