создать символическую ссылку php
Создать символическую ссылку php
Хотя в PHP нет такого понятия, как указатель, все же существует возможность создавать ссылки на другие переменные. Существует две разновидности ссылок: жесткие и символические (переменные переменные) (первые часто называют просто ссылками). Жесткие ссылки появились в PHP версии 4 (в третьей версии существовали лишь символические ссылки).
Жесткие ссылки в PHP
Жесткая ссылка представляет собой просто переменную, которая является синонимом другой переменной. Многоуровневые ссылки (то есть, ссылка на ссылку на переменную, как это можно делать, например, в Perl) не поддерживаются. Так что не стоит воспринимать жесткие ссылки серьезнее, чем синонимы.
Чтобы создать жесткую ссылку, нужно использовать оператор & (амперсанд). Например:
Ссылаться можно не только на переменные, но и на элементы массива (этим жесткие ссылки выгодно отличаются от символических). Например:
Впрочем, элемент массива, для которого планируется создать символическую ссылку, может и не существовать. Как в следующем случае:
В результате выполнения рассмотренного скрипта, хотя ссылке $b и не было ничего присвоено, в массиве $A создастся новый элемент с ключом c и значением — пустой строкой (мы можем это определить по результату работы echo). То есть, жесткая ссылка на самом деле не может ссылаться на несуществующий объект, а если делается такая попытка, то объект создается.
: Если убрать строку, в которой создается жесткая ссылка, то будет выведено сообщение о том, что элемент с ключом c не определен в массиве $A.
Жесткие ссылки удобно применять при передаче параметров пользовательской функции и возврате значения из нее.
Символические ссылки (переменные переменные)
— это всего лишь строковая переменная, хранящая имя другой переменной (переменная переменная). Чтобы добраться до значения переменной, на которую ссылается символическая ссылка, необходимо применить дополнительный знак $ перед именем ссылки. Рассмотрим пример:
Мы видим, что для того, чтобы использовать обычную строковую переменную как ссылку, нужно перед ней поставить еще один символ $.Это говорит интерпретатору, что надо взять не значение самой $p, а значение переменной, имя которой хранится в переменной $p.
Символические ссылки (переменные переменные) используюся достаточно редко.
Жесткие ссылки и пользовательские функции
Передача значений по ссылке
Вы можете передавать переменные в пользовательскую функцию по ссылке, если вы хотите разрешить функции модифицировать свои аргументы. В таком случае, пользовательския функция сможет изменять аргументы. Синтаксис таков:
Еще один интересный пример:
По ссылке можно передавать:
Переменные, например foo($a)
Оператор new, например foo(new foobar())
Ссылки, возвращаемые функцией, например:
Любое другое выражение не должно передаваться по ссылке, так как результат не определён. Например, следующая передача по ссылке является неправильной:
Возврат значений по ссылке
Возвращение по ссылке используется в тех случаях, когда вы хотите использовать функцию для выбора переменной, с которой должна быть связана данная ссылка. При возвращении по ссылке используйте такой синтаксис:
Еще один пример возврата значений пользовательской функции по ссылке:
Удаление ссылок (сброс ссылок)
При удалении ссылки, просто разрывается связь имени и содержимого переменной. Это не означает, что содержимое переменной будет разрушено. Например:
Этот код не сбросит $b, а только $a.
И все же, жесткая ссылка — не абсолютно точный синоним объекта, на который она ссылается. Дело в том, что оператор Unset(), выполненный для жесткой ссылки, не удаляет объект, на который она ссылается, а всего лишь разрывает связь между ссылкой и объектом.
Итак, жесткая ссылка и переменная (объект), на которую она ссылается, совершенно равноправны, но изменение одной влечет изменение другой. Оператор Unset() разрывает связь между объектом и ссылкой, но объект удаляется только тогда, когда на него никто уже не ссылается.
Опять же, можно провести аналогию с вызовом unlink (в Unix).
symlink
symlink — Создаёт символическую ссылку
Описание
Список параметров
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
5.3.0 | Эта функция теперь доступна на Windows платформах (Vista, Server 2008 и выше). |
Примеры
Пример #1 Создание символической ссылки
Примечания
Замечание: Пользователи Windows должны учитывать, что эта функция будет работать только на Windows Vista/Windows Server 2008 и новее. Более ранние версии Windows не поддерживают символические ссылки.
Смотрите также
Коментарии
Here is a simple way to control who downloads your files.
The code also deletes any past symbolic links created by any past users before creating one for itself. This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script. There appears to be no problem if a symbolic link is deleted while another person is downloading from that link.
This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file.
Olszewski’s method of creating downloadable links on the fly is pretty good.
I use a different technique under Apache where if you want a file, you might use a url like:
But in fact Apache redirects this to a script with a url like:
(The browser address bar will still show the first url).
The script downloadfile.php can then handle all the mucky stuff like checking session variables to see if someone is logged on, whether they have access to mysecretfile.doc, and if you want to encrypt before download.
Olszewski_marek makes a good suggestion, but the readfile() function can also be used to obscure file downloads from end users.
/* Setup the file that will be sent */
$downloadDir = «some/secret/directory/»;
$file = «theFileName.dat»;
/* Required for IE, otherwise Content-disposition is ignored */
if(ini_get(‘zlib.output_compression’)) ini_set(‘zlib.output_compression’, ‘Off’);
/* Output HTTP headers that force «Save As» dialog */
header(«Pragma: public»);
header(«Expires: 0»);
header(«Cache-Control: must-revalidate, post-check=0, pre-check=0»);
header(«Cache-Control: private»,false);
header(«Content-Type: application/octet-stream»);
header(«Content-Disposition: attachment; filename=\\»$file\\»;»);
header(«Content-Transfer-Encoding: binary»);
header(«Content-Length: «.@filesize($downloadDir.$file));
/* Prevent the script from timing out for large files */
set_time_limit(0);
/* Send the entire file using @ to ignore all errors */
@readfile($downloadDir.$file);
/* Exit immediately so no garbage follows the file contents */
exit;
The one difference to using symlinks for controlled file access vs. readfile() is that the HTTP server will handle content-type of the symlink automatically.
If you always want it to be downloaded, this can be a negative point. However, if you want a file of non-predefined type to be viewable in the browser, this can be a real asset.
Of course, you can use fileinfo/mime-magic to do that, but those require a module which isn’t always available on shared hosting.
Um, duh. that’s all I gotta say about by previous note. Please delete it. 🙂
Windows Vista has its own symlink program now (mklink). Hopefully future versions of PHP for Windows will have this function put it?
Keep in mind when using a shared filesystem such as NFS, that you probably don’t want to create a symbolic link with absolute paths e.g.
On Server1 you are running a PHP script that needs to create a symbolic link called widget2 which links to widget1 inside an NFS share mounted on your localhost at /mnt/nfs/widgets
On Server2 this same NFS share is mounted under /usr/local/widgets
If you used absolute paths on Server1, then Server2 would try to reference /mnt/nfs/widgets/widget1 which it won’t be able to find.
On IIS (Internet Information Services), you need to set permissions to allow the creation of symbolic links.
Context: php cli on windows OS.
Do not forget to start the console with «Run as Administrator» else symlink will return ‘false’ and raise the following error :
Warning: symlink(): Cannot create symlink, error code(1314)
sym/hard linking i love to do it relative a lot but not that trivial when thinking wrong 🙂
manpage says: the target is the _linkname_ and from that point to create relative links successful is to start from the directory where the link should be created e.g.:
/myfiles/now/here/
/myfiles/links/
chdir( realpath(dirname($target)));
You need to create/find out the relativ path to the source, otherwise the absolut path will be used in a link.
Be warned that at least with php 5.3 on windows 2008 R2 the symlink function is effected by the statcache.
I got error 183 indicating the link existed. While the symlink was actually moved to a different location by another process and would certainly not exist anymore.
Calling clearstatcache with a filename does not work. Most probably as the filename is converted to a device path (e.g. «\Device\HarddiskVolume1\D-Drive\www\pp\#static\index.html») which is a requirement for the windows call.
easiest is to just call clearstatcache without a filename to resolve the issue.
If you use the suhosin extension, you must allow symlink with :
> suhosin.executor.allow_symlink = On
To remove symlinks you need to use:
— rmdir() on Windows
— unlink() elsewhere
symlink
symlink — Создаёт символическую ссылку
Описание
Список параметров
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
5.3.0 | Эта функция теперь доступна на Windows платформах (Vista, Server 2008 и выше). |
Примеры
Пример #1 Создание символической ссылки
Примечания
Замечание: Только для Windows: Эта функция будет работать только на Windows Vista/Windows Server 2008 и выше. Более ранние версии Windows не поддерживают символические ссылки.
Смотрите также
Коментарии
Here is a simple way to control who downloads your files.
The code also deletes any past symbolic links created by any past users before creating one for itself. This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script. There appears to be no problem if a symbolic link is deleted while another person is downloading from that link.
This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file.
Olszewski’s method of creating downloadable links on the fly is pretty good.
I use a different technique under Apache where if you want a file, you might use a url like:
But in fact Apache redirects this to a script with a url like:
(The browser address bar will still show the first url).
The script downloadfile.php can then handle all the mucky stuff like checking session variables to see if someone is logged on, whether they have access to mysecretfile.doc, and if you want to encrypt before download.
Olszewski_marek makes a good suggestion, but the readfile() function can also be used to obscure file downloads from end users.
/* Setup the file that will be sent */
$downloadDir = «some/secret/directory/»;
$file = «theFileName.dat»;
/* Required for IE, otherwise Content-disposition is ignored */
if(ini_get(‘zlib.output_compression’)) ini_set(‘zlib.output_compression’, ‘Off’);
/* Output HTTP headers that force «Save As» dialog */
header(«Pragma: public»);
header(«Expires: 0»);
header(«Cache-Control: must-revalidate, post-check=0, pre-check=0»);
header(«Cache-Control: private»,false);
header(«Content-Type: application/octet-stream»);
header(«Content-Disposition: attachment; filename=\\»$file\\»;»);
header(«Content-Transfer-Encoding: binary»);
header(«Content-Length: «.@filesize($downloadDir.$file));
/* Prevent the script from timing out for large files */
set_time_limit(0);
/* Send the entire file using @ to ignore all errors */
@readfile($downloadDir.$file);
/* Exit immediately so no garbage follows the file contents */
exit;
The one difference to using symlinks for controlled file access vs. readfile() is that the HTTP server will handle content-type of the symlink automatically.
If you always want it to be downloaded, this can be a negative point. However, if you want a file of non-predefined type to be viewable in the browser, this can be a real asset.
Of course, you can use fileinfo/mime-magic to do that, but those require a module which isn’t always available on shared hosting.
Um, duh. that’s all I gotta say about by previous note. Please delete it. 🙂
Windows Vista has its own symlink program now (mklink). Hopefully future versions of PHP for Windows will have this function put it?
Keep in mind when using a shared filesystem such as NFS, that you probably don’t want to create a symbolic link with absolute paths e.g.
On Server1 you are running a PHP script that needs to create a symbolic link called widget2 which links to widget1 inside an NFS share mounted on your localhost at /mnt/nfs/widgets
On Server2 this same NFS share is mounted under /usr/local/widgets
If you used absolute paths on Server1, then Server2 would try to reference /mnt/nfs/widgets/widget1 which it won’t be able to find.
On IIS (Internet Information Services), you need to set permissions to allow the creation of symbolic links.
Context: php cli on windows OS.
Do not forget to start the console with «Run as Administrator» else symlink will return ‘false’ and raise the following error :
Warning: symlink(): Cannot create symlink, error code(1314)
sym/hard linking i love to do it relative a lot but not that trivial when thinking wrong 🙂
manpage says: the target is the _linkname_ and from that point to create relative links successful is to start from the directory where the link should be created e.g.:
/myfiles/now/here/
/myfiles/links/
chdir( realpath(dirname($target)));
You need to create/find out the relativ path to the source, otherwise the absolut path will be used in a link.
Be warned that at least with php 5.3 on windows 2008 R2 the symlink function is effected by the statcache.
I got error 183 indicating the link existed. While the symlink was actually moved to a different location by another process and would certainly not exist anymore.
Calling clearstatcache with a filename does not work. Most probably as the filename is converted to a device path (e.g. «\Device\HarddiskVolume1\D-Drive\www\pp\#static\index.html») which is a requirement for the windows call.
easiest is to just call clearstatcache without a filename to resolve the issue.
If you use the suhosin extension, you must allow symlink with :
> suhosin.executor.allow_symlink = On
To remove symlinks you need to use:
— rmdir() on Windows
— unlink() elsewhere
Как сделать символическую ссылку на развернутом сайте
Я новичок в Laravel, как вы знаете, чтобы получить доступ к хранимым файлам, у вас должна быть символическая ссылка от storage / app / public до public / storage. В компьютере вы можете просто ввести в командной строке: php artisan storage: link. Но теперь я развернул свой сайт на хостинге и хочу создать символическую ссылку. Как мне это сделать?
Решение
Я боюсь, что на виртуальном хостинге это почти невозможно, так как вам потребуется доступ к оболочке для создания такой же символической ссылки, как на вашем компьютере.
В зависимости от ваших вариантов возможно Laravel Forge полезно для вас.
Другие решения
Может быть, если вы можете добавить в «скрипты«тег вашего композитора при вызове для создания ссылки после развертывания вашего проекта:
Это приведет к тому, что ссылка будет создаваться каждый раз, когда **composer update** или же **composer install** звонок происходит.
Если папка хранилища не создана, вы получите:
Если он уже создан:
Смотрите также это обсуждение, которое может помочь вам: https://github.com/laravel/internals/issues/34
Работа Cron помогает мне на виртуальном хостинге.
Просто сконфигурируйте задание cron для запуска команды в следующую минуту (или в определенное время закрытия) и удалите ее после.
Например, команда выполнит команду в 9:30 и запишет все выходные данные в myjob.log
Просто создайте символическую ссылку в файле php и загрузите ее в общую папку, а затем перейдите к ней через браузер.
Ссылки должны быть абсолютным путем ….
Создать символическую ссылку php
Это означает, что мы можем использовать символические ссылки точно так же, как и обычные файлы. Однако иногда нужно бывает работать со ссылкой именно как со ссылкой, а не как с файлом. Для этого существуют специальные функции PHP.
Получает информацию о файле или символической ссылке (PHP 3 >= 3.0.4, PHP 4, PHP 5)
Собирает статистику на файл или символическую ссылку с именем filename. Эта функция идентична функции stat(), за исключением того, что если filename является символической ссылкой, возвращается статус символической ссылки, а не того файла, на который она указывает.
Обратитесь к странице руководства функции stat() для получения информации о структуре массива, который возвращает lstat().
Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache().
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми упаковщиками url.
Возвращает файл, на который указывает символическая ссылка (PHP 3, PHP 4, PHP 5)
Пример использования функции readlink()
Замечание: Для Windows-платформ эта функция не реализована.
Создаёт символическую ссылку (PHP 3, PHP 4, PHP 5)
symlink() создаёт символическую ссылку с именем link на существующий файл target.
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Замечание: Для Windows-платформ эта функция не реализована.