How to get Browser-Sync to serve PHP-Files in Gulp 4 - php

I am working on a gulpfile which already works fine when its processing html/scss/js. Now I want to have my site on PHP-basis and need Browser-Sync to serve my PHP instead of showing "Cannot GET /" in the browser. I know that implies some path issue as it all works, when there is an index.html instead of an index.php in the build folder.
const {src,dest,series,parallel,watch} = require('gulp');
const del = require('del');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const origin = './src/';
const destination = './build/';
sass.compiler = require('node-sass');
async function clean(cb) {
await del(destination);
cb();
}
function html(cb) {
src(origin + '*.html').pipe(dest(destination));
cb();
}
function php(cb) {
src(origin + '*.php').pipe(dest(destination));
cb();
}
function css(cb) {
src(origin + 'css/*.scss')
.pipe(sourcemaps.init())
.pipe(
sass({
sourcemap: true,
outputStyle: 'compressed'
})
)
.pipe(dest(destination + 'css'));
cb();
}
function js(cb) {
src(
origin + 'js/lib/jquery.min.js'
).pipe(dest(destination + 'js/lib'));
src(
origin + 'js/*.js',
).pipe(dest(destination + 'js'));
cb();
}
function watcher(cb) {
watch(origin + '**/*.html').on('change',series(html,browserSync.reload));
watch(origin + '**/*.php').on('change',series(php,browserSync.reload));
watch(origin + '**/*.scss').on('change',series(css,browserSync.reload));
watch(origin + '**/*.js').on('change',series(js,browserSync.reload));
cb();
}
function server(cb) {
browserSync.init({
notify: false,
//open: false,
server: {
baseDir: destination
}
})
cb();
}
exports.default = series(clean, parallel(html,php,css,js), server, watcher);
I looked at some solutions which almost all are based on Gulp 3 + gulp-connect-php which seems not to be amongst the Gulp-Plugins anymore. Am I missing that Gulp4 + Node can handle that PHP out of the box? And if yes how?
This is the closest I think I (as a nube) came to a solution: (These are only the changes/additions to the script above)
const phpConnect = require('gulp-connect-php');
function php(cb) {
src(origin + '*.php').pipe(dest(destination));
cb();
}
function watcher(cb) {
watch(origin + '**/*.html').on('change',series(html,browserSync.reload));
watch(origin + '**/*.php').on('change',series(php,browserSync.reload));
watch(origin + '**/*.scss').on('change',series(css,browserSync.reload));
watch(origin + '**/*.js').on('change',series(js,browserSync.reload));
cb();
}
function connectsync(cb) {
phpConnect.server({
port: 8000,
keepalive: true,
base: destination
},
function() {
browsersync({
proxy: '127.0.0.1:8000'
});
});
cb();
}
function server(cb) {
browserSync.init({
notify: false,
open: true,
server: {
baseDir: destination
}
})
cb();
}
exports.default = series(clean, parallel(html,php,css,js), connectsync, server, watcher);
but this seems to get stuck at the browsersync function which - I totally agree - is undefined.
Any help is appreciated very much !!!

After looking into the details of gulp-connect-php it turned out it supports only PHP 5.4 anyway so its not an option. Instead I utilized my XAMPP (while locally installed PHP + Apache might have been a liitle more elegant) and setup browser-sync to proxy to it:
function sync(cb) {
browserSync.init({
proxy: 'http://localhost/malte-podolski.de/build',
port: 3000,
})
cb();
}

Related

Socket.io Error on server

I am tried to use socket io on the live server and I got this error.
polling-xhr.js:264 GET http://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5 net::ERR_TIMED_OUT
But on my local server, the files worked perfectly. I am working with socket.io and PHP.
Here are my codes:
server.js
var socket = require('./node_modules/socket.io');
var express = require('./node_modules/express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = process.env.PORT || 3000;
// server active console view
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// show new added online user
socket.on('now_online', function (data) {
io.sockets.emit('now_online',{
id: data.id,
name: data.name
});
});
});
main.js
var socket = io.connect('http://'+window.location.hostname+':3000');
socket.on('new_online_user', function (data) {
if (login_id != data.online_user) {
$('#contacts-list .contact[data-chat='+data.online_user+']'+' .contact-status').addClass('online');
}
});
package.json
{
"private": true,
"dependencies": {
"gulp": "^3.9.1",
"express": "^4.16.2",
"socket.io": "^2.0.4"
}
}
I was searching in google and StackOverflow about this issue but those solved didn't work for me.
Thanks so much.
Try connecting using only domain without http like:
var socket = io.connect(window.location.hostname+':3000', {transports: ["websocket", "xhr-polling", "htmlfile", "jsonp-polling"]});
It will automatically become ws://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5. I'm using similar to this and working fine.

Setting up Yeoman Webapp with PHP

Trying to set up yo webapp to use a PHP server instead of HTML.
I tried following this answer by example with no success.
Gulp-webapp running BrowserSync and PHP
I added gulp-connect-php to my project.
// Towards the top of my gulpfile, added:
const connect = require('gulp-connect-php');
// Added the following task below:
gulp.task('php-serve', ['styles', 'fonts'], function () {
connect.server({
port: 9001,
base: 'app',
open: false
});
var proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
port : 9000,
server: {
baseDir : ['.tmp', 'app'],
routes : {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
} else {
next();
}
}
}
});
// watch for changes
gulp.watch([
'app/*.html',
'app/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
Ran gulp php-serve
PHP 5.5.36 Development Server started [etc…]
Listening on http://127.0.0.1:9001
However, not without error:
ReferenceError: httpProxy is not defined
How can this be resolved? I wouldn't even mind using MAMP which I already have running on port 8888
It seems I missed a vital part of installing http-proxy, which I thought I had installed before.
Here's an idiot guide of getting PHP to work with the most popular yeoman generator, generator webapp, with big thanks to TobyG
Install http-proxy
npm install http-proxy --save
Install gulp-connect-php
npm install --save-dev gulp-connect-php
Add these two functions to the top of gulpfile.js
const connect = require('gulp-connect-php');
const httpProxy = require('http-proxy');
Add this additional task to gulpfile.js
gulp.task('php-serve', ['styles', 'fonts'], function () {
connect.server({
port: 9001,
base: 'app',
open: false
});
var proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
port : 9000,
server: {
baseDir : ['.tmp', 'app'],
routes : {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
} else {
next();
}
}
}
});
// watch for changes
gulp.watch([
'app/*.html',
'app/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});

Changing node.js server to Apache server

I was working with react-webpackage and running the project into node.js
Now due to demand , i have to add some php files in the project but i don't know how to add php file in my project and now transfer my project from node.js to Xampp and run my project with xampp... can you please guide me with that.
I am using this webpack "https://github.com/srn/react-webpack-boilerplate".
And my webpack index.js file looks like this.
'use strict';
var fs = require('fs');
var path = require('path');
var express = require('express');
var app = express();
var compress = require('compression');
var layouts = require('express-ejs-layouts');
app.set('layout');
app.set('view engine', 'ejs');
app.set('view options', {layout: 'layout'});
app.set('views', path.join(process.cwd(), '/server/views'));
app.use(compress());
app.use(layouts);
app.use('/client', express.static(path.join(process.cwd(), '/client')));
app.disable('x-powered-by');
var env = {
production: process.env.NODE_ENV === 'production'
};
if (env.production) {
Object.assign(env, {
assets: JSON.parse(fs.readFileSync(path.join(process.cwd(), 'assets.json')))
});
}
app.get('/*', function(req, res) {
res.render('layout', {
env: env
});
});
var port = Number(process.env.PORT || 3001);
app.listen(port, function () {
console.log('server running at localhost:3001, go refresh and see magic');
});
if (env.production === false) {
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackDevConfig = require('./webpack.config.development');
new WebpackDevServer(webpack(webpackDevConfig), {
publicPath: '/client/',
contentBase: './client/',
inline: true,
hot: true,
stats: false,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3001',
'Access-Control-Allow-Headers': 'X-Requested-With'
}
}).listen(3000, 'localhost', function (err) {
if (err) {
console.log(err);
}
console.log('webpack dev server listening on localhost:3000');
});
}
basically i want to declare some variables in php and fetch them to javascript.so just want to add one file in webpack(file named as index.php) and then all my project work normally
Thanks.
You can't run express on the same port of xampp, you have to use different ports (or different servers) to serve the php file.

Browser Sync - PHP and htaccess?

I'm currently using the Yeoman Generator Gulp-Webapp, which I modified slightly to make it work with PHP. I simply added gulp-connect-php & http-proxy then edited the gulpfile.babel.js browserSync task by adding the following code. Now I would need to find a way to make it work with htaccess. Any idea how this could be done?
gulp.task('serve-php', ['styles', 'fonts'], () => {
phpConnect.server({
port: 9001,
base: 'app',
open: false
});
const proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
open: true,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
}
else {
next();
}
}
}
});
gulp.watch([
'app/**/*.html',
'app/**/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
I was able to make it work with PHP and htaccess!
Instead of using gulp-connect-php to create the vhost, I used XAMPP. I then target the proxy to the XAMPP vhost. Here's how I did it:
gulp.task('serve-php', ['styles', 'fonts'], () => {
const proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
open: true,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://xamppvhost.dev' });
}
else {
next();
}
}
}
});
gulp.watch([
'app/**/*.html',
'app/**/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
I removed phpConnect.server() and changed the proxy.web() to target my XAMPP vhost.
Now everything's working!!
Perhaps this can still be usefull for those bumping into this.
If you're developing on Mac, you can use MAMP and gulp-mamp, by far the easiest way to get things working - PHP, htaccess and MySQL if need be.
https://www.npmjs.com/package/gulp-mamp
After installing, you can get things to work with just this code in your gulpfile:
var mamp = require('gulp-mamp');
gulp.task('mamp-start', function(cb){
mamp(options, 'start', cb);
});
And then adding the task to the default task, or via command gulp mamp-start.
Mamp + Browser sync
is also very easy, just copy the code from this gulpfile:
https://github.com/sdotson/gulp-mamp-browsersync/blob/master/gulpfile.js

Node.js server sends back EOF block the PHP server

I have a node.js server opening 8000 port. It is a chat server.
I have another PHP server and I use proxy + virtual host so when I go www.phpserver.com/chat It proxies to the node.js server. I did this so I can use ajax to call the node.js server.
Right now, everything works fine when i run the node.js server, however, after a while (a random time frame, not necessarily long or short), the PHP server will crush because it gets an EOF from the node.js server and it's just stuck there until I stop/restart the node.js server.
The error I get is(from php error log):
(70014)End of file found: proxy: error reading status line from remote
server nodeserver.com:8000, referer: https://www.phpserver.com
I asked some professionals and they said it's because of the PHP server sends the request to the node.js server successfully and receives an EOF or fails to receive any response. I don't understand how to fix it tho. What should I do so even the node.js server crushes, it won't crush the PHP server? Should I get rid of the proxy+ajax and starts to use socket.io?
Please advise.
Thank you!
Below is some node codes.
From middleware:
this.events.addListener('update', o_.bind(function(package) {
if(this.clear != 0){
delete this.sessions[this.clear];
}
var _package = package.toJSON();
if(package.type == 'status' && package.status == 'offline') {
var sids = Object.keys(this.sessions), sid, sess;
for(sid in this.sessions) {
sess = this.sessions[sid];
if(sess.data('username') == package.username) {
if(sess.listeners.length)
sess.send(200, {type: 'goodbye'});
delete this.sessions[sid];
break;
}
}
}
}, this));
};
Hub.prototype.destroy = function(sid, fn) {
this.set(sid, null, fn);
};
Hub.prototype.reap = function(ms) {
var threshold = +new Date - ms,
sids = Object.keys(this.sessions);
for(var i = 0, len = sids.length; i < len; ++i) {
var sid = sids[i], sess = this.sessions[sid];
if(sess.lastAccess < threshold) {
this.events.emit('update', new packages.Offline(sess.data('username')));
}
}
};
Hub.prototype.get = function(req, fn) {
if(this.sessions[req.sessionID]) {
fn(null, this.sessions[req.sessionID]);
} else {
this.auth.authenticate(req, o_.bind(function(data) {
if(data) {
var session = new User(req.sessionID, data);
this.set(req.sessionID, session);
this.auth.friends(req, data, o_.bind(function(friends) {
var friends_copy = friends.slice();
o_.values(this.sessions).filter(function(friend) {
return ~friends.indexOf(friend.data('username'));
}).forEach(function(friend) {
var username = friend.data('username');
friends_copy[friends_copy.indexOf(username)] =
[username, friend.status()];
}, this);
session._friends(friends_copy);
console.log("refreshed");
session.events.addListener('status',
o_.bind(function(value, message) {
this.events.emit(
'update',
new packages.Status(session.data('username'),
value,
message)
);
}, this));
this.events.addListener('update',
o_.bind(session.receivedUpdate, session));
this.set(req.sessionID, session);
fn(null, session);
}, this));
} else {
fn();
}
}, this));
}
};
From app.js
#!/usr/bin/env node
var sys = require('sys'),
express = require('express'),
packages = require('./libs/packages'),
fs = require('fs'),
o_ = require('./libs/utils'),
https = require('https');
o_.merge(global, require('./settings'));
try { o_.merge(global, require('./settings.local')); } catch(e) {}
try {
var daemon = require('./libs/daemon/daemon'),
start = function() {
daemon.init({
lock: PID_FILE,
stdin: '/dev/null',
stdout: LOG_FILE,
stderr: LOG_FILE,
umask: 0,
chroot: null,
chdir: '.'
});
},
stop = function() {
process.kill(parseInt(require('fs').readFileSync(PID_FILE)));
};
switch(process.argv[2]) {
case 'stop':
stop();
process.exit(0);
break;
case 'start':
if(process.argv[3])
process.env.EXPRESS_ENV = process.argv[3];
start();
break;
case 'restart':
stop();
start();
process.exit(0);
break;
case 'help':
sys.puts('Usage: node app.js [start|stop|restart]');
process.exit(0);
break;
}
} catch(e) {
sys.puts('Daemon library not found! Please compile ' +
'./libs/daemon/daemon.node if you would like to use it.');
}
var options = {
key: fs.readFileSync('/home/ec2-user/key.pem'),
cert: fs.readFileSync('/home/ec2-user/cert.pem'),
ca: fs.readFileSync('/home/ec2-user/ca.pem'),
};
var app = express();
//app.set('env', 'development');
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(require('./middleware/im')({
maxAge: 30 * 1000,
reapInterval: 20 * 1000,
authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));
app.set('root', __dirname);
if ('development' == app.get('env')) {
app.set('view engine', 'jade');
app.set('views', __dirname + '/dev/views');
app.stack.unshift({
route: '/dev',
handle: function(req, res, next) {
req.dev = true;
next();
}
});
app.use(express.logger());
require('./dev/app')('/dev', app);
app.use(express.static(
require('path').join(__dirname, '../client')));
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
}
//app.listen(APP_PORT, APP_HOST);
// Listener endpoint; handled in middleware
app.get('/listen', function(){});
app.post('/message', function(req, res) {
res.find(req.body['to'], function(user) {
if(!user)
return res.send(new packages.Error('not online'));
res.message(user, new packages.Message(
req.session.data('username'),
req.body.body
));
});
});
app.post('/message/typing', function(req, res) {
if(~packages.TYPING_STATES.indexOf('typing' + req.body['state'])) {
res.find(req.body['to'], function(user) {
if(user) {
res.message(user, new packages.Status(
req.session.data('username'),
'typing' + req.body.state
));
}
// Typing updates do not receive confirmations,
// as they are not important enough.
res.send('');
});
} else {
res.send(new packages.Error('invalid state'));
}
});
app.post('/status', function(req, res) {
if(~packages.STATUSES.indexOf(req.body['status'])) {
res.status(req.body.status, req.body.message);
res.send(new packages.Success('status updated'));
} else {
res.send(new packages.Error('invalid status'));
}
});
app.post('/online', function(req, res) {
var d = new Date();
var n = d.getTime() + 30;
req.sessionID.expires = n;
res.status(req.body.status, 'available');
});
app.post('/signoff', function(req, res) {
res.signOff();
res.send(new packages.Success('goodbye'));
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Error on the node/express server.');
});
https.createServer(options, app).listen(8000);
I can't help you answer your question but I can try to point you in a right direction.
I'm currently working on a Node JS server myself, and I found very useful to have a logger setup.
There are a few of them, but my favorite is Winston so far.
Reference: https://github.com/flatiron/winston
To install Winston for your Node JS server (seems you have already installed a few modules):
npm install winston
Then I have logger module setup as (logger.js):
/**
* Usage:
* - logger.info('sample text');
* - logger.warn('sample text');
* - logger.error('sample text');
*/
// Load modules
var winston = require('winston');
// Create custom logger
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
// Export logger
module.exports = logger;
Finally I load in Winston logger module into my server scripts by:
var logger = require('./logger');
It will automatically log any exceptions into exceptions.log on your Node JS server location. It helped me out a lot to catch exceptions I haven't noticed before within Node JS unrelated to PHP.
P.S. Also check out socket.io, that may simplify what you are trying to do.

Categories