frankenphp.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. // Package frankenphp embeds PHP in Go projects and provides a SAPI for net/http.
  2. //
  3. // This is the core of the [FrankenPHP app server], and can be used in any Go program.
  4. //
  5. // [FrankenPHP app server]: https://frankenphp.dev
  6. package frankenphp
  7. //go:generate rm -Rf C-Thread-Pool/
  8. //go:generate git clone --depth=1 git@github.com:Pithikos/C-Thread-Pool.git
  9. //go:generate rm -Rf C-Thread-Pool/.git C-Thread-Pool/.github C-Thread-Pool/docs C-Thread-Pool/tests C-Thread-Pool/example.c
  10. // Use PHP includes corresponding to your PHP installation by running:
  11. //
  12. // export CGO_CFLAGS=$(php-config --includes)
  13. // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)"
  14. //
  15. // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59
  16. // #cgo darwin pkg-config: libxml-2.0
  17. // #cgo CFLAGS: -Wall -Werror -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  18. // #cgo CFLAGS: -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib
  19. // #cgo CFLAGS: -DTHREAD_NAME=frankenphp
  20. // #cgo linux CFLAGS: -D_GNU_SOURCE
  21. // #cgo CPPFLAGS: -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
  22. // #cgo darwin LDFLAGS: -L/opt/homebrew/opt/libiconv/lib -liconv
  23. // #cgo linux LDFLAGS: -Wl,-O1 -lresolv
  24. // #cgo LDFLAGS: -pie -L/usr/local/lib -L/usr/lib -lphp -ldl -lm -lutil
  25. // #include <stdlib.h>
  26. // #include <stdint.h>
  27. // #include <php_variables.h>
  28. // #include <zend_llist.h>
  29. // #include <SAPI.h>
  30. // #include "frankenphp.h"
  31. import "C"
  32. import (
  33. "bytes"
  34. "context"
  35. "errors"
  36. "fmt"
  37. "io"
  38. "net/http"
  39. "os"
  40. "runtime"
  41. "runtime/cgo"
  42. "strconv"
  43. "strings"
  44. "sync"
  45. "unsafe"
  46. "go.uber.org/zap"
  47. // debug on Linux
  48. //_ "github.com/ianlancetaylor/cgosymbolizer"
  49. )
  50. type key int
  51. var contextKey key
  52. var (
  53. InvalidRequestError = errors.New("not a FrankenPHP request")
  54. AlreaydStartedError = errors.New("FrankenPHP is already started")
  55. InvalidPHPVersionError = errors.New("FrankenPHP is only compatible with PHP 8.2+")
  56. ZendSignalsError = errors.New("Zend Signals are enabled, recompile PHP with --disable-zend-signals")
  57. NotEnoughThreads = errors.New("the number of threads must be superior to the number of workers")
  58. MainThreadCreationError = errors.New("error creating the main thread")
  59. RequestContextCreationError = errors.New("error during request context creation")
  60. RequestStartupError = errors.New("error during PHP request startup")
  61. ScriptExecutionError = errors.New("error during PHP script execution")
  62. requestChan chan *http.Request
  63. done chan struct{}
  64. shutdownWG sync.WaitGroup
  65. loggerMu sync.RWMutex
  66. logger *zap.Logger
  67. )
  68. type syslogLevel int
  69. const (
  70. emerg syslogLevel = iota // system is unusable
  71. alert // action must be taken immediately
  72. crit // critical conditions
  73. err // error conditions
  74. warning // warning conditions
  75. notice // normal but significant condition
  76. info // informational
  77. debug // debug-level messages
  78. )
  79. func (l syslogLevel) String() string {
  80. switch l {
  81. case emerg:
  82. return "emerg"
  83. case alert:
  84. return "alert"
  85. case crit:
  86. return "crit"
  87. case err:
  88. return "err"
  89. case warning:
  90. return "warning"
  91. case notice:
  92. return "notice"
  93. case debug:
  94. return "debug"
  95. default:
  96. return "info"
  97. }
  98. }
  99. // FrankenPHPContext provides contextual information about the Request to handle.
  100. type FrankenPHPContext struct {
  101. documentRoot string
  102. splitPath []string
  103. env map[string]string
  104. logger *zap.Logger
  105. docURI string
  106. pathInfo string
  107. scriptName string
  108. scriptFilename string
  109. // Whether the request is already closed by us
  110. closed sync.Once
  111. responseWriter http.ResponseWriter
  112. exitStatus C.int
  113. done chan interface{}
  114. currentWorkerRequest cgo.Handle
  115. }
  116. func clientHasClosed(r *http.Request) bool {
  117. select {
  118. case <-r.Context().Done():
  119. return true
  120. default:
  121. return false
  122. }
  123. }
  124. // NewRequestWithContext creates a new FrankenPHP request context.
  125. func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
  126. fc := &FrankenPHPContext{
  127. done: make(chan interface{}),
  128. }
  129. for _, o := range opts {
  130. if err := o(fc); err != nil {
  131. return nil, err
  132. }
  133. }
  134. if fc.documentRoot == "" {
  135. if EmbeddedAppPath != "" {
  136. fc.documentRoot = EmbeddedAppPath
  137. } else {
  138. var err error
  139. if fc.documentRoot, err = os.Getwd(); err != nil {
  140. return nil, err
  141. }
  142. }
  143. }
  144. if fc.splitPath == nil {
  145. fc.splitPath = []string{".php"}
  146. }
  147. if fc.env == nil {
  148. fc.env = make(map[string]string)
  149. }
  150. if fc.logger == nil {
  151. fc.logger = getLogger()
  152. }
  153. if splitPos := splitPos(fc, r.URL.Path); splitPos > -1 {
  154. fc.docURI = r.URL.Path[:splitPos]
  155. fc.pathInfo = r.URL.Path[splitPos:]
  156. // Strip PATH_INFO from SCRIPT_NAME
  157. fc.scriptName = strings.TrimSuffix(r.URL.Path, fc.pathInfo)
  158. // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
  159. // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
  160. if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") {
  161. fc.scriptName = "/" + fc.scriptName
  162. }
  163. }
  164. // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
  165. fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
  166. return r.WithContext(context.WithValue(r.Context(), contextKey, fc)), nil
  167. }
  168. // FromContext extracts the FrankenPHPContext from a context.
  169. func FromContext(ctx context.Context) (fctx *FrankenPHPContext, ok bool) {
  170. fctx, ok = ctx.Value(contextKey).(*FrankenPHPContext)
  171. return
  172. }
  173. type PHPVersion struct {
  174. MajorVersion int
  175. MinorVersion int
  176. ReleaseVersion int
  177. ExtraVersion string
  178. Version string
  179. VersionID int
  180. }
  181. type PHPConfig struct {
  182. Version PHPVersion
  183. ZTS bool
  184. ZendSignals bool
  185. ZendMaxExecutionTimers bool
  186. }
  187. // Version returns infos about the PHP version.
  188. func Version() PHPVersion {
  189. cVersion := C.frankenphp_get_version()
  190. return PHPVersion{
  191. int(cVersion.major_version),
  192. int(cVersion.minor_version),
  193. int(cVersion.release_version),
  194. C.GoString(cVersion.extra_version),
  195. C.GoString(cVersion.version),
  196. int(cVersion.version_id),
  197. }
  198. }
  199. func Config() PHPConfig {
  200. cConfig := C.frankenphp_get_config()
  201. return PHPConfig{
  202. Version: Version(),
  203. ZTS: bool(cConfig.zts),
  204. ZendSignals: bool(cConfig.zend_signals),
  205. ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers),
  206. }
  207. }
  208. // Init starts the PHP runtime and the configured workers.
  209. func Init(options ...Option) error {
  210. if requestChan != nil {
  211. return AlreaydStartedError
  212. }
  213. opt := &opt{}
  214. for _, o := range options {
  215. if err := o(opt); err != nil {
  216. return err
  217. }
  218. }
  219. if opt.logger == nil {
  220. l, err := zap.NewDevelopment()
  221. if err != nil {
  222. return err
  223. }
  224. loggerMu.Lock()
  225. logger = l
  226. loggerMu.Unlock()
  227. } else {
  228. loggerMu.Lock()
  229. logger = opt.logger
  230. loggerMu.Unlock()
  231. }
  232. maxProcs := runtime.GOMAXPROCS(0)
  233. var numWorkers int
  234. for i, w := range opt.workers {
  235. if w.num <= 0 {
  236. // https://github.com/dunglas/frankenphp/issues/126
  237. opt.workers[i].num = maxProcs * 2
  238. }
  239. numWorkers += opt.workers[i].num
  240. }
  241. if opt.numThreads <= 0 {
  242. if numWorkers >= maxProcs {
  243. // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode
  244. opt.numThreads = numWorkers + 1
  245. } else {
  246. opt.numThreads = maxProcs
  247. }
  248. } else if opt.numThreads <= numWorkers {
  249. return NotEnoughThreads
  250. }
  251. config := Config()
  252. if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) {
  253. return InvalidPHPVersionError
  254. }
  255. if config.ZTS {
  256. if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" {
  257. logger.Warn(`Zend Max Execution Timers are not enabled, timeouts (e.g. "max_execution_time") are disabled, recompile PHP with the "--enable-zend-max-execution-timers" configuration option to fix this issue`)
  258. }
  259. } else {
  260. opt.numThreads = 1
  261. logger.Warn(`ZTS is not enabled, only 1 thread will be available, recompile PHP using the "--enable-zts" configuration option or performance will be degraded`)
  262. }
  263. shutdownWG.Add(1)
  264. done = make(chan struct{})
  265. requestChan = make(chan *http.Request)
  266. if C.frankenphp_init(C.int(opt.numThreads)) != 0 {
  267. return MainThreadCreationError
  268. }
  269. if err := initWorkers(opt.workers); err != nil {
  270. return err
  271. }
  272. logger.Info("FrankenPHP started 🐘", zap.String("php_version", Version().Version))
  273. if EmbeddedAppPath != "" {
  274. logger.Info("embedded PHP app 📦", zap.String("path", EmbeddedAppPath))
  275. }
  276. return nil
  277. }
  278. // Shutdown stops the workers and the PHP runtime.
  279. func Shutdown() {
  280. stopWorkers()
  281. close(done)
  282. shutdownWG.Wait()
  283. requestChan = nil
  284. // Always reset the WaitGroup to ensure we're in a clean state
  285. workersReadyWG = sync.WaitGroup{}
  286. // Remove the installed app
  287. if EmbeddedAppPath != "" {
  288. os.RemoveAll(EmbeddedAppPath)
  289. }
  290. logger.Debug("FrankenPHP shut down")
  291. }
  292. //export go_shutdown
  293. func go_shutdown() {
  294. shutdownWG.Done()
  295. }
  296. func getLogger() *zap.Logger {
  297. loggerMu.RLock()
  298. defer loggerMu.RUnlock()
  299. return logger
  300. }
  301. func updateServerContext(request *http.Request, create bool, mrh C.uintptr_t) error {
  302. fc, ok := FromContext(request.Context())
  303. if !ok {
  304. return InvalidRequestError
  305. }
  306. authUser, authPassword, ok := request.BasicAuth()
  307. var cAuthUser, cAuthPassword *C.char
  308. if ok && authPassword != "" {
  309. cAuthPassword = C.CString(authPassword)
  310. }
  311. if ok && authUser != "" {
  312. cAuthUser = C.CString(authUser)
  313. }
  314. cMethod := C.CString(request.Method)
  315. cQueryString := C.CString(request.URL.RawQuery)
  316. contentLengthStr := request.Header.Get("Content-Length")
  317. contentLength := 0
  318. if contentLengthStr != "" {
  319. var err error
  320. contentLength, err = strconv.Atoi(contentLengthStr)
  321. if err != nil {
  322. return fmt.Errorf("invalid Content-Length header: %w", err)
  323. }
  324. }
  325. contentType := request.Header.Get("Content-Type")
  326. var cContentType *C.char
  327. if contentType != "" {
  328. cContentType = C.CString(contentType)
  329. }
  330. // compliance with the CGI specification requires that
  331. // PATH_TRANSLATED should only exist if PATH_INFO is defined.
  332. // Info: https://www.ietf.org/rfc/rfc3875 Page 14
  333. var cPathTranslated *C.char
  334. if fc.pathInfo != "" {
  335. cPathTranslated = C.CString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
  336. }
  337. cRequestUri := C.CString(request.URL.RequestURI())
  338. var rh cgo.Handle
  339. if fc.responseWriter == nil {
  340. mrh = C.uintptr_t(cgo.NewHandle(request))
  341. } else {
  342. rh = cgo.NewHandle(request)
  343. }
  344. ret := C.frankenphp_update_server_context(
  345. C.bool(create),
  346. C.uintptr_t(rh),
  347. mrh,
  348. cMethod,
  349. cQueryString,
  350. C.zend_long(contentLength),
  351. cPathTranslated,
  352. cRequestUri,
  353. cContentType,
  354. cAuthUser,
  355. cAuthPassword,
  356. C.int(request.ProtoMajor*1000+request.ProtoMinor),
  357. )
  358. if ret > 0 {
  359. return RequestContextCreationError
  360. }
  361. return nil
  362. }
  363. // ServeHTTP executes a PHP script according to the given context.
  364. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error {
  365. shutdownWG.Add(1)
  366. defer shutdownWG.Done()
  367. fc, ok := FromContext(request.Context())
  368. if !ok {
  369. return InvalidRequestError
  370. }
  371. fc.responseWriter = responseWriter
  372. rc := requestChan
  373. // Detect if a worker is available to handle this request
  374. if nil == fc.responseWriter {
  375. fc.env["FRANKENPHP_WORKER"] = "1"
  376. } else if v, ok := workersRequestChans.Load(fc.scriptFilename); ok {
  377. fc.env["FRANKENPHP_WORKER"] = "1"
  378. rc = v.(chan *http.Request)
  379. }
  380. select {
  381. case <-done:
  382. case rc <- request:
  383. <-fc.done
  384. }
  385. return nil
  386. }
  387. //export go_fetch_request
  388. func go_fetch_request() C.uintptr_t {
  389. select {
  390. case <-done:
  391. return 0
  392. case r := <-requestChan:
  393. return C.uintptr_t(cgo.NewHandle(r))
  394. }
  395. }
  396. func maybeCloseContext(fc *FrankenPHPContext) {
  397. fc.closed.Do(func() {
  398. close(fc.done)
  399. })
  400. }
  401. //export go_execute_script
  402. func go_execute_script(rh unsafe.Pointer) {
  403. handle := cgo.Handle(rh)
  404. defer handle.Delete()
  405. request := handle.Value().(*http.Request)
  406. fc, ok := FromContext(request.Context())
  407. if !ok {
  408. panic(InvalidRequestError)
  409. }
  410. defer maybeCloseContext(fc)
  411. if err := updateServerContext(request, true, 0); err != nil {
  412. panic(err)
  413. }
  414. // scriptFilename is freed in frankenphp_execute_script()
  415. fc.exitStatus = C.frankenphp_execute_script(C.CString(fc.scriptFilename))
  416. if fc.exitStatus < 0 {
  417. panic(ScriptExecutionError)
  418. }
  419. }
  420. //export go_ub_write
  421. func go_ub_write(rh C.uintptr_t, cBuf *C.char, length C.int) (C.size_t, C.bool) {
  422. r := cgo.Handle(rh).Value().(*http.Request)
  423. fc, _ := FromContext(r.Context())
  424. var writer io.Writer
  425. if fc.responseWriter == nil {
  426. var b bytes.Buffer
  427. // log the output of the worker
  428. writer = &b
  429. } else {
  430. writer = fc.responseWriter
  431. }
  432. i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length))
  433. if e != nil {
  434. fc.logger.Error("write error", zap.Error(e))
  435. }
  436. if fc.responseWriter == nil {
  437. fc.logger.Info(writer.(*bytes.Buffer).String())
  438. }
  439. return C.size_t(i), C.bool(clientHasClosed(r))
  440. }
  441. //export go_register_variables
  442. func go_register_variables(rh C.uintptr_t, trackVarsArray *C.zval) {
  443. r := cgo.Handle(rh).Value().(*http.Request)
  444. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  445. le := (len(fc.env) + len(r.Header)) * 2
  446. dynamicVariablesArr := (**C.char)(C.malloc(C.size_t(le) * C.size_t(unsafe.Sizeof((*C.char)(nil)))))
  447. dynamicVariables := unsafe.Slice(dynamicVariablesArr, le)
  448. var i int
  449. // Add all HTTP headers to env variables
  450. for field, val := range r.Header {
  451. k := "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(field))
  452. if _, ok := fc.env[k]; ok {
  453. continue
  454. }
  455. dynamicVariables[i] = C.CString(k)
  456. i++
  457. dynamicVariables[i] = C.CString(strings.Join(val, ", "))
  458. i++
  459. }
  460. for k, v := range fc.env {
  461. dynamicVariables[i] = C.CString(k)
  462. i++
  463. dynamicVariables[i] = C.CString(v)
  464. i++
  465. }
  466. knownVariables := computeKnownVariables(r)
  467. C.frankenphp_register_bulk_variables(&knownVariables[0], dynamicVariablesArr, C.size_t(le), trackVarsArray)
  468. fc.env = nil
  469. }
  470. func addHeader(fc *FrankenPHPContext, cString *C.char, length C.int) {
  471. parts := strings.SplitN(C.GoStringN(cString, length), ": ", 2)
  472. if len(parts) != 2 {
  473. fc.logger.Debug("invalid header", zap.String("header", parts[0]))
  474. return
  475. }
  476. fc.responseWriter.Header().Add(parts[0], parts[1])
  477. }
  478. //export go_write_headers
  479. func go_write_headers(rh C.uintptr_t, status C.int, headers *C.zend_llist) {
  480. r := cgo.Handle(rh).Value().(*http.Request)
  481. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  482. if fc.responseWriter == nil {
  483. return
  484. }
  485. current := headers.head
  486. for current != nil {
  487. h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data)))
  488. addHeader(fc, h.header, C.int(h.header_len))
  489. current = current.next
  490. }
  491. fc.responseWriter.WriteHeader(int(status))
  492. if status >= 100 && status < 200 {
  493. // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
  494. h := fc.responseWriter.Header()
  495. for k := range h {
  496. delete(h, k)
  497. }
  498. }
  499. }
  500. //export go_sapi_flush
  501. func go_sapi_flush(rh C.uintptr_t) bool {
  502. r := cgo.Handle(rh).Value().(*http.Request)
  503. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  504. if fc.responseWriter == nil || clientHasClosed(r) {
  505. return true
  506. }
  507. if r.ProtoMajor == 1 {
  508. if _, err := r.Body.Read(nil); err != nil {
  509. // Don't flush until the whole body has been read to prevent https://github.com/golang/go/issues/15527
  510. return false
  511. }
  512. }
  513. if err := http.NewResponseController(fc.responseWriter).Flush(); err != nil {
  514. fc.logger.Error("the current responseWriter is not a flusher", zap.Error(err))
  515. }
  516. return false
  517. }
  518. //export go_read_post
  519. func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
  520. r := cgo.Handle(rh).Value().(*http.Request)
  521. p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes)
  522. var err error
  523. for readBytes < countBytes && err == nil {
  524. var n int
  525. n, err = r.Body.Read(p[readBytes:])
  526. readBytes += C.size_t(n)
  527. }
  528. if err != nil && err != io.EOF {
  529. // invalid Read on closed Body may happen because of https://github.com/golang/go/issues/15527
  530. fc, _ := FromContext(r.Context())
  531. fc.logger.Error("error while reading the request body", zap.Error(err))
  532. }
  533. return
  534. }
  535. //export go_read_cookies
  536. func go_read_cookies(rh C.uintptr_t) *C.char {
  537. r := cgo.Handle(rh).Value().(*http.Request)
  538. cookies := r.Cookies()
  539. if len(cookies) == 0 {
  540. return nil
  541. }
  542. cookieString := make([]string, len(cookies))
  543. for _, cookie := range r.Cookies() {
  544. cookieString = append(cookieString, cookie.String())
  545. }
  546. // freed in frankenphp_request_shutdown()
  547. return C.CString(strings.Join(cookieString, "; "))
  548. }
  549. //export go_log
  550. func go_log(message *C.char, level C.int) {
  551. l := getLogger()
  552. m := C.GoString(message)
  553. var le syslogLevel
  554. if level < C.int(emerg) || level > C.int(debug) {
  555. le = info
  556. } else {
  557. le = syslogLevel(level)
  558. }
  559. switch le {
  560. case emerg, alert, crit, err:
  561. l.Error(m, zap.Stringer("syslog_level", syslogLevel(level)))
  562. case warning:
  563. l.Warn(m, zap.Stringer("syslog_level", syslogLevel(level)))
  564. case debug:
  565. l.Debug(m, zap.Stringer("syslog_level", syslogLevel(level)))
  566. default:
  567. l.Info(m, zap.Stringer("syslog_level", syslogLevel(level)))
  568. }
  569. }
  570. // ExecuteScriptCLI executes the PHP script passed as parameter.
  571. // It returns the exit status code of the script.
  572. func ExecuteScriptCLI(script string, args []string) int {
  573. cScript := C.CString(script)
  574. defer C.free(unsafe.Pointer(cScript))
  575. argc := C.int(len(args))
  576. argv := make([]*C.char, argc)
  577. for i, arg := range args {
  578. argv[i] = C.CString(arg)
  579. defer C.free(unsafe.Pointer(argv[i]))
  580. }
  581. return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))))
  582. }