Foros del Web » Programando para Internet » PHP »

Error unexpected T_STRING, expecting T_FUNCTION

Estas en el tema de Error unexpected T_STRING, expecting T_FUNCTION en el foro de PHP en Foros del Web. Hola Soy nuevo en PHP, estoy haciendo una aplicación móvil que envía un JSON a un programa PHP en el hostting para que inserte la ...
  #1 (permalink)  
Antiguo 28/07/2015, 11:01
 
Fecha de Ingreso: enero-2014
Mensajes: 17
Antigüedad: 10 años, 2 meses
Puntos: 0
Error unexpected T_STRING, expecting T_FUNCTION

Hola

Soy nuevo en PHP, estoy haciendo una aplicación móvil que envía un JSON a un programa PHP en el hostting para que inserte la información contenida en el JSON, obtengo como error lo escrito en el título de este tema, me puede ayudar de favor ? que tengo mal?

Código PHP:
Ver original
  1. <?php
  2. function getStatusCodeMessage($status)
  3. {
  4.  
  5.     $codes = Array(
  6.         100 => 'Continue',
  7.         101 => 'Switching Protocols',
  8.         200 => 'OK',
  9.         201 => 'Created',
  10.         202 => 'Accepted',
  11.         203 => 'Non-Authoritative Information',
  12.         204 => 'No Content',
  13.         205 => 'Reset Content',
  14.         206 => 'Partial Content',
  15.         300 => 'Multiple Choices',
  16.         301 => 'Moved Permanently',
  17.         302 => 'Found',
  18.         303 => 'See Other',
  19.         304 => 'Not Modified',
  20.         305 => 'Use Proxy',
  21.         306 => '(Unused)',
  22.         307 => 'Temporary Redirect',
  23.         400 => 'Bad Request',
  24.         401 => 'Unauthorized',
  25.         402 => 'Payment Required',
  26.         403 => 'Forbidden',
  27.         404 => 'Not Found',
  28.         405 => 'Method Not Allowed',
  29.         406 => 'Not Acceptable',
  30.         407 => 'Proxy Authentication Required',
  31.         408 => 'Request Timeout',
  32.         409 => 'Conflict',
  33.         410 => 'Gone',
  34.         411 => 'Length Required',
  35.         412 => 'Precondition Failed',
  36.         413 => 'Request Entity Too Large',
  37.         414 => 'Request-URI Too Long',
  38.         415 => 'Unsupported Media Type',
  39.         416 => 'Requested Range Not Satisfiable',
  40.         417 => 'Expectation Failed',
  41.         500 => 'Internal Server Error',
  42.         501 => 'Not Implemented',
  43.         502 => 'Bad Gateway',
  44.         503 => 'Service Unavailable',
  45.         504 => 'Gateway Timeout',
  46.         505 => 'HTTP Version Not Supported'
  47.     );
  48.  
  49.     return (isset($codes[$status])) ? $codes[$status] : '';
  50. }
  51.  
  52. // Helper method to send a HTTP response code/message
  53. function sendResponse($status = 200, $body = '', $content_type = 'text/html')
  54. {
  55.     $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
  56.     header($status_header);
  57.     header('Content-type: ' . $content_type);
  58.     echo $body;
  59. }
  60.  
  61. class RedeemAPI {
  62.     private $db;
  63.     // Constructor - open DB connection
  64.     function __construct() {
  65.         $this->db = new mysqli('localhost', 'futchoco_admin', 'Futcho190867', 'futchoco_futsoft');
  66.        /* verificar la conexión */
  67.        if (mysqli_connect_errno()) {
  68.         printf("Conexión fallida: %s\n", mysqli_connect_error());
  69.         exit();
  70.       }
  71.         $this->db->autocommit(FALSE);
  72.     }
  73.        
  74.     // Destructor - close DB connection
  75.     function __destruct() {
  76.         $this->db->close();
  77.     }
  78.     // Main method to redeem a code
  79.     function redeem() {
  80.     // Check for required parameters
  81.         $json = file_get_contents('php://input');
  82.         $obj = json_decode($json,true);
  83.         echo $obj;
  84.         $rows = array();
  85.         //foreach($array[] as $key => $value)
  86.         foreach($obj as $item)
  87.         {
  88.             $rows[] = "('" . $key . "', '" . $value . "')";
  89.             $stmt = $this->db->prepare('INSERT INTO prueba (id,nombre)
  90.                                         VALUES (%d,%s)',$item->id_cliente,$item->nombre) or die(mysqli_error($this->db));
  91.             $stmt->execute();
  92.         }
  93.     }
  94.     sendResponse(400, 'Invalid request');
  95.     return false;
  96.   }
  97. }
  98.  
  99.  
  100. // This is the first thing that gets called when this page is loaded
  101. // Creates a new instance of the RedeemAPI class and calls the redeem method
  102. $api = new RedeemAPI;
  103. $api->redeem();
  104.  
  105. ?>

Última edición por Triby; 29/07/2015 a las 01:37 Razón: Código en highlight
  #2 (permalink)  
Antiguo 28/07/2015, 12:47
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

¿Tenemos que adivinar el mensaje de error completo así como la linea donde se indica el error cierto? :pesando:
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 28/07/2015, 13:05
 
Fecha de Ingreso: enero-2014
Mensajes: 17
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

La línea donde marca el error es ...



sendResponse(400, 'Invalid request');
  #4 (permalink)  
Antiguo 28/07/2015, 13:25
Avatar de chronos682  
Fecha de Ingreso: febrero-2004
Ubicación: Tunja - Boyacá - Colombia
Mensajes: 627
Antigüedad: 20 años, 2 meses
Puntos: 69
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

Aquí faltan las comillas dobles de cierre:

Código PHP:
Ver original
  1. function sendResponse($status = 200, $body = '', $content_type = 'text/html'")

Puede ser ahí el error.

Aunque no me queda claro si son 2 parámetros ($status y $body) o son 3 ($status, $body y $content_type) porque si son 3 debería ser así:

function sendResponse($status = 200, $body = "", $content_type = "text/html")

Y la llamada a la función estaría mal porque solo estas psando 2 parámetros y no 3.

Corrijo: no hacen falta comillas de cierre, es que parecía que fuera una comilla doble pero en realidad son dos simples seguidas. Sigo mirando a ver dónde puede ser el error.


Tienes un error en las llaves de cierre. No sé si estas dos líneas van dentro de la clase o fuera de ella:

Código PHP:
Ver original
  1. sendResponse(400, "Invalid request");
  2. return false;

Si van fuera de la clase debería quedar así el código:

Código PHP:
Ver original
  1. <?php
  2.  
  3.  
  4. function getStatusCodeMessage($status)
  5. {
  6.  
  7. $codes = Array(
  8. 100 => "Continue",
  9. 101 => "Switching Protocols",
  10. 200 => "OK",
  11. 201 => "Created",
  12. 202 => "Accepted",
  13. 203 => "Non-Authoritative Information",
  14. 204 => "No Content",
  15. 205 => "Reset Content",
  16. 206 => "Partial Content",
  17. 300 => "Multiple Choices",
  18. 301 => "Moved Permanently",
  19. 302 => "Found",
  20. 303 => "See Other",
  21. 304 => "Not Modified",
  22. 305 => "Use Proxy",
  23. 306 => "(Unused)",
  24. 307 => "Temporary Redirect",
  25. 400 => "Bad Request",
  26. 401 => "Unauthorized",
  27. 402 => "Payment Required",
  28. 403 => "Forbidden",
  29. 404 => "Not Found",
  30. 405 => "Method Not Allowed",
  31. 406 => "Not Acceptable",
  32. 407 => "Proxy Authentication Required",
  33. 408 => "Request Timeout",
  34. 409 => "Conflict",
  35. 410 => "Gone",
  36. 411 => "Length Required",
  37. 412 => "Precondition Failed",
  38. 413 => "Request Entity Too Large",
  39. 414 => "Request-URI Too Long",
  40. 415 => "Unsupported Media Type",
  41. 416 => "Requested Range Not Satisfiable",
  42. 417 => "Expectation Failed",
  43. 500 => "Internal Server Error",
  44. 501 => "Not Implemented",
  45. 502 => "Bad Gateway",
  46. 503 => "Service Unavailable",
  47. 504 => "Gateway Timeout",
  48. 505 => "HTTP Version Not Supported"
  49. );
  50.  
  51. return (isset($codes[$status])) ? $codes[$status] : '';
  52. }
  53.  
  54. // Helper method to send a HTTP response code/message
  55. function sendResponse($status = 200, $body = "", $content_type = "text/html")
  56. {
  57. $status_header = "HTTP/1.1 " . $status . " " . getStatusCodeMessage($status);
  58. header($status_header);
  59. header("Content-type: " . $content_type);
  60. echo $body;
  61. }
  62.  
  63. class RedeemAPI {
  64.     private $db;
  65.     // Constructor - open DB connection
  66.     function __construct()
  67.     {
  68.         $this->db = new mysqli("localhost", "futchoco_admin", "Futcho190867", "futchoco_futsoft");
  69.         /* verificar la conexión */
  70.         if (mysqli_connect_errno())
  71.         {
  72.             printf("Conexión fallida: %s\n", mysqli_connect_error());
  73.             exit();
  74.         }
  75.         $this->db->autocommit(FALSE);
  76.     }
  77.  
  78.     // Destructor - close DB connection
  79.     function __destruct()
  80.     {
  81.         $this->db->close();
  82.     }
  83.     // Main method to redeem a code
  84.     function redeem()
  85.     {
  86.         // Check for required parameters
  87.         $json = file_get_contents("php://input");
  88.         $obj = json_decode($json,true);
  89.         echo $obj;
  90.         $rows = array();
  91.         //foreach($array[] as $key => $value)
  92.         foreach($obj as $item)
  93.         {
  94.             $rows[] = "('" . $key . "', '" . $value . "')";
  95.             $stmt = $this->db->prepare('INSERT INTO prueba (id,nombre)
  96.             VALUES (%d,%s)',$item->id_cliente,$item->nombre) or die(mysqli_error($this->db));
  97.             $stmt->execute();
  98.         }
  99.     }
  100. }
  101.     sendResponse(400, "Invalid request");
  102.     return false;
  103.  
  104.  
  105. // This is the first thing that gets called when this page is loaded
  106. // Creates a new instance of the RedeemAPI class and calls the redeem method
  107. $api = new RedeemAPI;
  108. $api->redeem();
  109.  
  110. ?>

Acostúmbrate a tabular las líneas para que no te pase eso.
__________________
Si te gustó la respuesta dale +1

HERNÁN G. SIABATO M.
[email protected]

Última edición por chronos682; 28/07/2015 a las 13:52
  #5 (permalink)  
Antiguo 28/07/2015, 14:39
 
Fecha de Ingreso: enero-2014
Mensajes: 17
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

Gracias Hernán, el error ya no se dispara.


Pero sigo sin insertar en la tabla, estoy agregando la línea


error_log(print_r($json,true));


Después de la línea de

$json = file_get_contents("php://input");

Para observar que datos se están recibiendo pero no logro tampoco hacer esto.
  #6 (permalink)  
Antiguo 28/07/2015, 15:05
Avatar de chronos682  
Fecha de Ingreso: febrero-2004
Ubicación: Tunja - Boyacá - Colombia
Mensajes: 627
Antigüedad: 20 años, 2 meses
Puntos: 69
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

En la noche que llegue a la casa reviso el código a ver que puede ser.
__________________
Si te gustó la respuesta dale +1

HERNÁN G. SIABATO M.
[email protected]
  #7 (permalink)  
Antiguo 29/07/2015, 23:00
Avatar de chronos682  
Fecha de Ingreso: febrero-2004
Ubicación: Tunja - Boyacá - Colombia
Mensajes: 627
Antigüedad: 20 años, 2 meses
Puntos: 69
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

Estuve revisando el código pero no entiendo exactamente qué es lo que quieres hacer con él. Además creo que falta toda la parte donde se recoge la información, entonces la varibale $json siempre va a ser NULL por lo que no puedo ver si funciona o no.
__________________
Si te gustó la respuesta dale +1

HERNÁN G. SIABATO M.
[email protected]
  #8 (permalink)  
Antiguo 30/07/2015, 07:40
 
Fecha de Ingreso: enero-2014
Mensajes: 17
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

En teoria, lo que pretendo es recibir un JSON y los datos que se tienen insertarlos en la tabla.

Como lo mencioné, soy nuevo en PHP.

Pensé que el código ...

$json = file_get_contents("php://input");

Recibia la información y el resto barre el contenido y lo inserta

$obj = json_decode($json,true);
echo $obj;
$rows = array();
//foreach($array[] as $key => $value)
foreach($obj as $item)
{
$rows[] = "('" . $key . "', '" . $value . "')";
$stmt = $this->db->prepare('INSERT INTO prueba (id,nombre)
VALUES (%d,%s)',$item->id_cliente,$item->nombre) or die(mysqli_error($this->db));
$stmt->execute();
}
  #9 (permalink)  
Antiguo 30/07/2015, 07:44
Avatar de chronos682  
Fecha de Ingreso: febrero-2004
Ubicación: Tunja - Boyacá - Colombia
Mensajes: 627
Antigüedad: 20 años, 2 meses
Puntos: 69
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

De dónde sacaste ese código? Para mirar el original.
__________________
Si te gustó la respuesta dale +1

HERNÁN G. SIABATO M.
[email protected]
  #10 (permalink)  
Antiguo 30/07/2015, 07:51
 
Fecha de Ingreso: enero-2014
Mensajes: 17
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

mmm buena pregunta ..... de tanto que he visto que la verdad no tengo el link .... lo lamento y muchas gracias por tus coemntarios y ayuda
  #11 (permalink)  
Antiguo 30/07/2015, 18:02
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Error unexpected T_STRING, expecting T_FUNCTION

Manual de PHP: http://php.net/manual/es/wrappers.php.php
__________________
- León, Guanajuato
- GV-Foto

Etiquetas: json
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:40.