Laravel bootstrap autoload php

Laravel 4 на виртуальном хостинге

Порою вам просто необходимо воспрользоваться виртуальным хостингом. Причины могут быть в клиенте или в политике компании. Несмотря на это Laravel структурирован особым образом и мы рассмотрим несколько способов, которые помогут нам разместить проект на хостинге с минимальными требованиями.

Я хотел бы начать с того , что существуют много решений способных удовлетворить ваши потребности — готовые решения для размещения проектов на таких PHP фреймворках, как Laravel. Fortrabbit — одно из таких решений, но безусловно не единственное.

Помните, что абсолютный минимум требований включает в себя расширение PHP Mcrypt. Мы будем использовать следующую структуру папок в качестве базовой для этого урока — www папка является нашим DoceumntRoot. Ваша структура папок на вашем хостинге может отличаться.

Спасибо следующим ресурсам и людям:

Нет доступа к DocumentRoot

DocumentRoot — это папка куда смотрит ваш домен на хостинге. Laravel требует смотреть в папку public, чтобы ваше основное приложение было недоступно извне. Но что, если вы не можите сопоствить свой домен с папкой public Laravel? Сам виртуальный хостинг не предоставляет такой возможности. Есть несколько способов решить эту проблему и один лучше другого:

Читайте также:  Отступ от шапки css

1. Переименовать папку public

Если ваш хостинг позволяет управлять фаловой системой на уровень выше DocumentRoot, но должно быть специфическое название папки, то можно использовать эту фозможность для получения желаемого результата.

Для начала созданим папку с именем laravel на нашем хостинге и выложим туда структуру приложения.

Затем загрузим содержимое папки public в папку www.

Теперь, когда мы изменили местоположение и имя папки public, мы должны отразить это в файле bootstrap/paths.php .

Мы также должны изменить пути в файле www/index.php , чтобы найти новую папук laravel .

Вот мы и переместили успешно папку public и наше laravel приложение. Вы можете конечно загрузить приложение laravel в корневую папку, но в отдельной папке это выглядит более практично.

Еще один способ — создать символическую ссылку к папке public в папке www, но мало вероятно, что у вас есть доступ к этой функции на виртуальном хостинге.

2. Использовать .htaccess и mod_rewrite

Прежде чем мы продолжим, хотелось бы отметить, что следующий способ очень не рекомендуется использовать. Перемещая все приложение в DocementRoot вы подвергаете свое приложение опасности, которая оставляет уязвимость для атак злоумышленников. В этот момент вы должны серьезно задуматься над сменой хостинга, который больше подходит для размещения PHP фреймворков как Laravel.

Порою вы ползуетесь определенным хостинго из-за клиентов или других причин. В отличие от предыдущего метода, мы собираемся загрузить фреймворк в папку DocementRoot. Мы собираемся использовать .htaccess в нашу прользу, чтобы перенаправить все запросы в общую папку.

Для начала переместим все приложение в папку www.

Теперь в папки www, разместите файл .htaccess со следующим содержимым.

Это должно перенаправить все запросы к вашемей папке public. Запросы к вашей папке public, например файлы статики, будут по-прежнему приниматься.

3. Переместить все в DocumentRoot

Так же, как в предыдущем методе мы переместим все приложение в папку DocumentRoot. Но на этот раз мы также и сожержимое папки public в DocumentRoot

Во-первых, давайте перестим все приложение в папку www (DocumentRoot).

Теперь переместим содержимое папки public в DocumentRoot и удалим её.

Придется изменить путь в файле bootstrap/paths.php.

И наконец мы должны также изменить пути в файле index.php.

Теперь ваше Laravel приложение должно работать.

Деградация до PHP 5.3.2

Laravel 4 требует по крайней мере PHP 5.3.7 из-за Bcrypt, но есть способ дергадировать до PHP 5.3.2, если вы застряли с этим. Роб Клэнси ( Rob Clancy ) написал подробную инструкцию о том, как понизить до абсолютного минимума требования к версии PHP.

Нет доступа к SSH

Сам виртуальный хостинг не предлагает поддержку системы контроля версий, так что ваши варианты развертывания ограничены FTP. Очевидно, что это проблема, потому что размертывание настроятельно не рекомендуется через FTP. Какие файлы были отредактированы, какие должны быть загружены? Что делать, если я случайно перезаписал важные данные?

К счастью есть несколько средств развертывания, которые могут вам помочь в этом. Приведу некоторые из них.

Отсутствие доступа к SSH также означает отсутствие доступа к composer, artisan и другим инструментам командной строки. И снова FTP, вероятно, твой единственный друг. Если вы решили не использовать средства развертывания, то я рекомендую делать по крайней мере слудующее.

Запускайте composer install с аргументом —no-dev перед заргузкой файлов. Это оптимизирует ваши зависимости для продакшена без ненужных зависимостей предназначенных для разработки. И перезаписывайте папку vendor с обновленными зависимостями, когда вы загружаете файлы через FTP.

Вывод

Я надеюсь, что некоторые из описанных советом помогут вам в установке приолжения на Laravel 4 на вашем виртуальном хостинге. Если у вас есть дополнительные советы, то пожалуйста делитись или в комментариях и я дополню ими пост.

Источник

[SOLVED] Laravel Error: Failed to open stream: No such file or directory bootstrap/autoload.php

You might get the following error while trying to run Laravel for the first time.

Warning: require(/var/www/laravel/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/laravel/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required ‘/var/www/laravel/bootstrap/../vendor/autoload.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/laravel/bootstrap/autoload.php on line 17

Problem Scenario:

This error generally occurs when you download/clone Laravel from Github and then you put it in your web server. Then, you try to access it through your browser (e.g. http://localhost/laravel/public).

Though you have downloaded the Laravel code and put it in your server, there’s still missing dependencies (library files/codes) in the code. The missing dependencies should be installed in order to make Laravel run properly.

Once you have installed composer on your system/computer, then you need to follow the steps below to install the missing dependencies:

  • Open terminal or command prompt
  • Go to your Laravel directory
    • For example, in Ubuntu Linux the web root is /var/www/, in Windows if you install Wampp in C: Drive then the web root will be C://wampp/www
    • Suppose, you downloaded and copied the Laravel files in directory named ‘laravel’
    • Then, your Laravel directory on your web server in Ubuntu will be /var/www/laravel
    • You can go to that directory by running the following command on terminal: cd /var/www/laravel
    • This will install the required dependencies to run Laravel. It will take some time to install all the dependencies.
    • Now, you should be able to access Laravel properly without any error, e.g. http://localhost/laravel/public

    If you already have run composer install command and still getting the error, then you can try running the following command:

    Note: If you are on Linux then you should also set write permission to bootstrap/cache and storage directories.

    Here’s the command to do so:

    sudo chmod -R 777 bootstrap/cache storage

    Alternatively, the better way to create laravel project / install Laravel will be directly through composer. Instead of downloading/cloning Laravel from GitHub, you can run the following composer command in terminal/command-prompt:

    • Go to your web server root (in Ubuntu, it’s /var/www/)
    • Run the following command in terminal:
    composer create-project laravel/laravel name-of-your-project
    • This will create a directory with name-of-your-project and install Laravel files in it
    • This will also install all the required dependencies to run Laravel
    • Then, you can simply browse http://localhost/name-of-your-project/public to access Laravel

    Share this:

    1. Laravel: Simple/Easy Installation Guide
    2. Laravel: Enable Proper Error Display
    3. Joomla Error – “JFolder::create: Could not create directory” while installing extension
    4. Hyperledger Fabric: Error: error getting endorser client for channel: endorser client failed to connect to peer0.org1.example.com:7051: failed to create new connection: context deadline exceeded
    5. MySQL Installation Problem: Can’t create pid file – no such file or directory

    Источник

    Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

    to generate autoload.php file again in /vendor directory.,bootstrap/../vendor/autoload.php. Failed to open stream: No such file or directory. The «vendor» folder does not exist. ,the vendor folder is populated by composer binary which reads composer.json file or system requirements and installs packaged under vendor folder and create an autoload script that has all classed,I have recently installed Laravel 5 via composer. I tried creating a new controller using artisan and I get the following error:

    Run composer with —no-scripts

    composer update --no-scripts 

    Answer by Josephine Ware

    MySQL Installation Problem: Can’t create pid file – no such file or directory , Warning: require(/var/www/laravel/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/laravel/bootstrap/autoload.php on line 17,Fatal error: require(): Failed opening required ‘/var/www/laravel/bootstrap/../vendor/autoload.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/laravel/bootstrap/autoload.php on line 17,Joomla Error – “JFolder::create: Could not create directory” while installing extension

    – Open terminal or command prompt
    – Go to your Laravel directory
    – For example, in Ubuntu Linux the web root is /var/www/, in Windows if you install Wampp in C: Drive then the web root will be C://wampp/www
    – Suppose, you downloaded and copied the Laravel files in directory named ‘laravel’
    – Then, your Laravel directory on your web server in Ubuntu will be /var/www/laravel
    – You can go to that directory by running the following command on terminal: `cd /var/www/laravel`
    – Run the following command

    If you already have run `composer install` command and still getting the error, then you can try running the following command:

    Here’s the command to do so:

    sudo chmod -R 777 bootstrap/cache storage

    – Go to your web server root (in Ubuntu, it’s /var/www/)
    – Run the following command in terminal:

    composer create-project laravel/laravel name-of-your-project

    Answer by Wayne Moody

    I have recently installed Laravel 5 via composer. I tried creating a new controller using artisan and I get the following error:,Delete Vendor then composer install,Then type this command : composer install,Delete vendor folder and run composer install command. It is working 100%

    Run composer with —no-scripts

    composer update --no-scripts 

    Answer by Hope Gomez

    Fatal error: require(): Failed opening required ‘/var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/../vendor/autoload.php’ (include_path=’.:/opt/plesk/php/5.6/share/pear’) in /var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/autoload.php on line 17,’/var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/../vendor/autoload.php’,It looks like you have an extra level of nesting in there.. it should probably be /var/www/vhosts/mysite.ca/bootstrap, right?,No such file or directory in /var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/autoload.php on line 17 Warning: require(/var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/vhosts/mysite.ca/mysite.mysite.ca/bootstrap/autoload.php on line 17

    public should never be in your APP_URL.

    I’m not sure what the problem is, exactly, since it looks like composer ran without an issue. You can try deleting the contents of the bootstrap/cache directory, and try running composer dump-autoload to try to clear any cached files.

    public should never be in your APP_URL.

    I’m not sure what the problem is, exactly, since it looks like composer ran without an issue. You can try deleting the contents of the bootstrap/cache directory, and try running composer dump-autoload to try to clear any cached files.

    Answer by Jon Flores

    How to find if a variable contains certain character or not using php ? , get current path Laravel 5 , Laravel configuration error: The cipher and / or key length are invalid , Laravel 5 js is blocking by app.js

    composer update --no-scripts 

    Answer by Hendrix Rasmussen

    composer install --ignore-platform-reqs

    Источник

Оцените статью