1: <?php
2:
3: namespace Guzzle\Http\Message;
4:
5: use Guzzle\Common\Exception\InvalidArgumentException;
6: use Guzzle\Http\Mimetypes;
7:
8: /**
9: * POST file upload
10: */
11: class PostFile implements PostFileInterface
12: {
13: protected $fieldName;
14: protected $contentType;
15: protected $filename;
16:
17: /**
18: * @param string $fieldName Name of the field
19: * @param string $filename Path to the file
20: * @param string $contentType Content-Type of the upload
21: */
22: public function __construct($fieldName, $filename, $contentType = null)
23: {
24: $this->fieldName = $fieldName;
25: $this->setFilename($filename);
26: $this->contentType = $contentType ?: $this->guessContentType();
27: }
28:
29: /**
30: * {@inheritdoc}
31: */
32: public function setFieldName($name)
33: {
34: $this->fieldName = $name;
35:
36: return $this;
37: }
38:
39: /**
40: * {@inheritdoc}
41: */
42: public function getFieldName()
43: {
44: return $this->fieldName;
45: }
46:
47: /**
48: * {@inheritdoc}
49: */
50: public function setFilename($filename)
51: {
52: // Remove leading @ symbol
53: if (strpos($filename, '@') === 0) {
54: $filename = substr($filename, 1);
55: }
56:
57: if (!is_readable($filename)) {
58: throw new InvalidArgumentException("Unable to open {$filename} for reading");
59: }
60:
61: $this->filename = $filename;
62:
63: return $this;
64: }
65:
66: /**
67: * {@inheritdoc}
68: */
69: public function getFilename()
70: {
71: return $this->filename;
72: }
73:
74: /**
75: * {@inheritdoc}
76: */
77: public function setContentType($type)
78: {
79: $this->contentType = $type;
80:
81: return $this;
82: }
83:
84: /**
85: * {@inheritdoc}
86: */
87: public function getContentType()
88: {
89: return $this->contentType;
90: }
91:
92: /**
93: * {@inheritdoc}
94: */
95: public function getCurlValue()
96: {
97: // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
98: // See: https://wiki.php.net/rfc/curl-file-upload
99: if (function_exists('curl_file_create')) {
100: return curl_file_create($this->filename, $this->contentType, basename($this->filename));
101: }
102:
103: // Use the old style if using an older version of PHP
104: $value = "@{$this->filename};filename=" . basename($this->filename);
105: if ($this->contentType) {
106: $value .= ';type=' . $this->contentType;
107: }
108:
109: return $value;
110: }
111:
112: /**
113: * @deprecated
114: */
115: public function getCurlString()
116: {
117: return $this->getCurlValue();
118: }
119:
120: /**
121: * Determine the Content-Type of the file
122: */
123: protected function guessContentType()
124: {
125: return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream';
126: }
127: }
128: