I want to develop an app in php that I can link with a particular photo album in my Facebook profile (or with all my photos) in order to know the direct url link of each photo.
The idea is to make an php script who shows in chronological order my facebook photos like a presentation. Im php programmer, but I know nothing about Facebook integration API. So guys if you can suggest me ways to do this it will be nice. Sorry for my English. Thanks!
here is a class for retriving specific user profile pictures (PHP), you'll get the idea from it to create what you want:
<?php
class FBPicture {
public $uid;
public $dir;
public $type = 'large';
public function setUId ($id) {
$this->uid = $id;
}
public function setDir ($dir) {
$this->dir = $dir;
}
public function fetch ($_uid=null, $_dir=null, $_type=null) {
if ($_uid === null)
throw new CHttpException ('Facebook User ID or Username is not set.');
if ($_dir === null)
$_dir = '/storage/';
if ($_type === null)
$_type = 'large';
$this->uid = $_uid;
$this->dir = $_dir;
$this->type = $_type;
$dir = getcwd () . $this->dir;
$type = $this->type;
// request URI
$host = 'http://graph.facebook.com/' . $_uid;
$request = '/picture';
$type = '?type=' . $type;
$contents = file_get_contents ($host.$request.$type);
// create the file (check existance);
$file = 'fb_' . $uid . '_' . rand (0, 9999);
$ext = '.jpg';
if (file_exists ($dir)) {
if (file_exists ($dir.$file.$ext)) {
$file .= $dir.$file.'2'.$ext;
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
} else {
$file = $dir.$file.$ext;
touch ($file);
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
}
} else {
// false is returned if directory doesn't exist
return false;
}
}
private function appendToFile ($file, $contents) {
$fp = fopen ($file, 'w');
$retVal = fwrite ($fp, $contents);
fclose ($fp);
return $retVal;
}
}
// sample usage:
// $pic will be the filename of the saved file...
$pic = FBPicture::fetch('zuck', 'uploads/', 'large'); // get a large photo of Mark Zuckerberg, and save it in the "uploads/" directory
// this will request the graph url: http://graph.facebook.com/zuck/picture?type=large
?>
Related
Hello there
Hope you will be doing well.I want to redirect to a route after file download but as we know that return only works once in a controller method how i can achieve this with laravel 5.7.I have to set a session and display it when data exported in txt file.I want this with post method.
Every thing is fine but redirect is not working;
Controller Method
public function exportTxtProcess(Request $request)
{
$table = $request->tblExportSelect;
$destinationPath = public_path('/');
$result;
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table . "-" . $today;
$fp = fopen($destinationPath . "$fileName.txt", "wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table, $output);
fwrite($fp, $netResult);
}
$result = fclose($fp);
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$redirect = redirect()->back();
$sess = Session::flash('success', 'Table exported successfully');
return response()->download($pathToFile)->deleteFileAfterSend(true);
}
}
Thank in advance
You can only have 1 response, so it's impossible to instruct a double
return. What you could do, is set the filename you wish to have
downloaded in a session variable, then redirect back to whatever page.
Within the redirected page, you could flash your message, along with
having an automatic download of the file.
Here is some threads on the topic:
How do I redirect after download in Laravel?
PHP generate file for download then redirect
I have made a form on the front end to upload some images. My idea is to automatically rename all files uploaded into unique id's.
I have looked at the SilverStripe API and I do not see anything about that. UploadField API
Is this possible?
Here is my solution bellow, in Silverstripe 3.X we must extend UploadField with another class. Then copy the ''saveTemporaryFile'' function into it.
Just before ''try'', just have to add :
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
Results :
class RandomNameUploadField extends UploadField {
protected function saveTemporaryFile($tmpFile, &$error = null) {
// Determine container object
$error = null;
$fileObject = null;
if (empty($tmpFile)) {
$error = _t('UploadField.FIELDNOTSET', 'File information not found');
return null;
}
if($tmpFile['error']) {
$error = $tmpFile['error'];
return null;
}
// Search for relations that can hold the uploaded files, but don't fallback
// to default if there is no automatic relation
if ($relationClass = $this->getRelationAutosetClass(null)) {
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
}
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
// Get the uploaded file into a new file object.
try {
$this->upload->loadIntoFile($tmpFile, $fileObject, $this->getFolderName());
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$error = $e->getMessage();
return null;
}
// Check if upload field has an error
if ($this->upload->isError()) {
$error = implode(' ' . PHP_EOL, $this->upload->getErrors());
return null;
}
// return file
return $this->upload->getFile();
}
}
Thanks #3dgoo to give me a part of the solution!
I don't now about a API but with some code I was able to do that.
You have two possibilities.
First using database.
Second using only code:
$directory = '/teste/www/fotos/';
$files = glob($directory . '*.jpg');
if ( $files !== false )
{
$filecount = count( $files );
$newid = $filecount+1;
$new_name = "foto_".$newid;
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
else
{
$new_name = "foto_1";
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
My example is for jpeg but you can look for hall types.
My website lets logged users to use CKeditor and CKFinder to create pages or blog and of course upload image from editor. I got problem for many users that will use the same images in a single folder. I have searching for the same problem on StackOverflow and I found this question:
KCFinder with CKEditor - setting up dynamic folders for upload files.
I think the solution was good, but rather than creating many folders, I am just thinking how to save every user images by using a prefix of their user ID. For example the user with ID 10 will save his images with prefix 10_xxxxx.jpg and so on.
How to do it. Any body could show me where part of the file script that could be modified? I am using KCFinder V.3.12. Sorry for my English.
$_SESSION['id'] = 10;
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) #unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($_GET['dir']) &&
(false !== ($gdir = $this->checkInputDir($_GET['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
#mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!#move_uploaded_file($file['tmp_name'], $target) &&
!#rename($file['tmp_name'], $target) &&
!#copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
#chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}
Laravel 4.2 upload file success but not found when I used it
The file uploaded succesfully on the directory I've been specified, but when I want to display it, it return not found, but if I change it to other file name in the same directory, it appears. What's wrong?
here is my code:
app/services/CommonProvider.php
<?php
class CommonProvider{
# simple class to provide static common functions
public static function uploadFiles($filename,$name,$location = 'img/'){
if(Input::hasFile($name)){
$filename .= '.'.Input::file($name)->getClientOriginalExtension();
$filename = $location . $filename;
if(Input::file($name)->move($location, $filename))
return $filename;
return false;
}
return false;
}
}
and here is the updateUser method (for example) from app/services/UserProvider.php
public function updateUser($input, $user_id) {
$validation_messages = $this->validateUser(Input::all(), false);
if ($validation_messages !== true) return $validation_messages;
try {
$insert = $this->user->find($user_id);
$insert->access_level = $input['access_level'];
$insert->email = $input['email'];
$insert->name = $input['name'];
$insert->mobile_no = $input['mobile_no'];
if ($input['password'] != '') $insert->password = Hash::make($input['password']);
if (!isset($input['active_status'])) $insert->active_status = 0;
$insert->save();
$filename = CommonProvider::uploadFiles($insert->id, 'user_image', 'img/user_images/');
if ($filename) {
$insert->user_image = $filename;
}
$insert->save();
return true;
}
catch(Exception $e) {
dd($e);
return false;
}
}
What do I miss?
You shouldn't add path to your filename when moving the file (you can add it when you want to retrieve the file).
$filename = $location . $filename; // remove this line
And I think you need to add absolute path so you will know exactly where the uploaded file is moved to.
In this code I added public_path()
$abslocation = public_path() . '/'. $location;
if(Input::file($name)->move($abslocation, $filename))
return $location . $filename;
I'm trying to write a script that will upload the entire contents of a directory stored on my server to other servers via ftp.
I've been reading through the documentation on www.php.net, but can't seem to find a way to upload more then one file at a time.
Is there a way to do this, or is there a script that will index that directory and create an array of files to upload?
Thanks in advance for your help!
Once you have a connection open, uploading the contents of a directory serially is simple:
foreach (glob("/directory/to/upload/*.*") as $filename)
ftp_put($ftp_stream, basename($filename) , $filename, FTP_BINARY);
Uploading all files in parallel would be more difficult.
So, I took #iYETER's code, and wrapped it as a class object.
You can call this code by these lines:
$ftp = new FtpNew("hostname");
$ftpSession = $ftp->login("username", "password");
if (!$ftpSession) die("Failed to connect.");
$errorList = $ftp->send_recursive_directory("/local/dir/", "/remote/dir/");
print_r($errorList);
$ftp->disconnect();
It recursively crawls local dir, and places it on remote dir relative. If it hits any errors, it creates a array hierarchy of every file and their exception code (I only capture 2 so far, if it's another error, it throws it default route for now)
The class this is wrapped into:
<?php
//Thanks for iYETER on http://stackoverflow.com/questions/927341/upload-entire-directory-via-php-ftp
class FtpNew {
private $connectionID;
private $ftpSession = false;
private $blackList = array('.', '..', 'Thumbs.db');
public function __construct($ftpHost = "") {
if ($ftpHost != "") $this->connectionID = ftp_connect($ftpHost);
}
public function __destruct() {
$this->disconnect();
}
public function connect($ftpHost) {
$this->disconnect();
$this->connectionID = ftp_connect($ftpHost);
return $this->connectionID;
}
public function login($ftpUser, $ftpPass) {
if (!$this->connectionID) throw new Exception("Connection not established.", -1);
$this->ftpSession = ftp_login($this->connectionID, $ftpUser, $ftpPass);
return $this->ftpSession;
}
public function disconnect() {
if (isset($this->connectionID)) {
ftp_close($this->connectionID);
unset($this->connectionID);
}
}
public function send_recursive_directory($localPath, $remotePath) {
return $this->recurse_directory($localPath, $localPath, $remotePath);
}
private function recurse_directory($rootPath, $localPath, $remotePath) {
$errorList = array();
if (!is_dir($localPath)) throw new Exception("Invalid directory: $localPath");
chdir($localPath);
$directory = opendir(".");
while ($file = readdir($directory)) {
if (in_array($file, $this->blackList)) continue;
if (is_dir($file)) {
$errorList["$remotePath/$file"] = $this->make_directory("$remotePath/$file");
$errorList[] = $this->recurse_directory($rootPath, "$localPath/$file", "$remotePath/$file");
chdir($localPath);
} else {
$errorList["$remotePath/$file"] = $this->put_file("$localPath/$file", "$remotePath/$file");
}
}
return $errorList;
}
public function make_directory($remotePath) {
$error = "";
try {
ftp_mkdir($this->connectionID, $remotePath);
} catch (Exception $e) {
if ($e->getCode() == 2) $error = $e->getMessage();
}
return $error;
}
public function put_file($localPath, $remotePath) {
$error = "";
try {
ftp_put($this->connectionID, $remotePath, $localPath, FTP_BINARY);
} catch (Exception $e) {
if ($e->getCode() == 2) $error = $e->getMessage();
}
return $error;
}
}
Do it in a loop, iterating through all the files in the folder
$servername = $GLOBALS["servername"];
$ftpUser = $GLOBALS["ftpUser"];
$ftpPass = $GLOBALS["ftpPass"];
$conn_id = ftp_connect($servername) or die("<p style=\"color:red\">Error connecting to $servername </p>");
if(ftp_login($conn_id, $ftpUser, $ftpPass))
{
$dir_handle = #opendir($path) or die("Error opening $path");
while ($file = readdir($dir_handle)) {
ftp_put($conn_id, PATH_TO_REMOTE_FILE, $file)
}
}
I coded it, the script uploads whole folder with it's subfolders and files.
I hope it will help you.
<?php
ob_start();
set_time_limit(0);
//r10.net fatal
$anadizin="uploadedeceginizdizin"; //this is the folder that you want to upload with all subfolder and files of it.
$ftpsunucu="domain.com"; //ftp domain name
$ftpusername="ftpuser"; //ftp user name
$ftppass="ftppass"; //ftp passowrd
$ftpdizin="/public_html"; //ftp main folder
$arkadaslarlabardaydik = ftp_connect($ftpsunucu);
$ictikguldukeglendik = ftp_login($arkadaslarlabardaydik, $ftpusername, $ftppass);
if((!$arkadaslarlabardaydik) || (!$ictikguldukeglendik))
{
echo "cant connect!";
die();
}
function klasoruoku($dizinadi)
{
global $nerdeyiz,$fulldizin,$ftpdizin,$arkadaslarlabardaydik,$ftpdizin;
chdir($dizinadi."\\");
$dizin = opendir(".");
while($bilgi=readdir($dizin))
{
if ($bilgi!='.' and $bilgi!='..' and $bilgi!="Thumbs.db")
{
$tamyol="$dizinadi\\$bilgi";
$lokalkla=str_replace("".$nerdeyiz."\\","",$dizinadi)."";
$lokaldosya="$lokalkla\\$bilgi";
$ftpyeyolla=str_replace(array("\\\\","\\"),array("/","/"),"$ftpdizin\\".str_replace("".$fulldizin."","",$dizinadi)."\\$bilgi");
if(!is_dir($bilgi))
{
$yükleme = ftp_put($arkadaslarlabardaydik, $ftpyeyolla, $tamyol, FTP_BINARY);
if (!$yükleme)
{
echo "$lokaldosya <font color=red>uploaded</font>"; echo "<br>"; fls();
}
else
{
echo "$lokaldosya <font color=green>not uploaded</font>"; echo "<br>"; fls();
}
}
else
{
ftp_mkdir($arkadaslarlabardaydik, $ftpyeyolla);
klasoruoku("$dizinadi\\$bilgi");
chdir($dizinadi."\\");
fls();
}
}
}
closedir ($dizin);
}
function fls()
{
ob_end_flush();
ob_flush();
flush();
ob_start();
}
$nerdeyiz=getcwd();
$fulldizin=$nerdeyiz."\\$anadizin";
klasoruoku($fulldizin);
ftp_close($arkadaslarlabardaydik);
?>
If you want to have multiple files uploaded at once, you'll need to use thread or fork.
I'm not sure of a Thread implentation in PHP, but you should take a look at the PHP SPL and/or PEAR
Edit: Thanks to Frank Farmer to let me know that there was a fork() function in PHP known as pcntl_fork()
You'll also have to get the whole content directory recursively to be able to upload all the file for a given directory.