开发者

"@/path/to/a/file" in PHP, what does it mean?

开发者 https://www.devze.com 2023-03-31 00:22 出处:网络
I have stumbled to following code example: 开发者_StackOverflow$image = \'file/path\'; $code = $tmhOAuth->request(\'POST\', \'https://upload.twitter.com/1/statuses/update_with_media.json\',

I have stumbled to following code example:

开发者_StackOverflow$image = 'file/path';
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
  array(
    'media[]'  => "@{$image}",
    'status'   => "Don't slip up" // Don't give up..
  ),
  true, // use auth
  true  // multipart
);

The confusing bit is "@{$image}", what that "at" sign does in front of the file path? Thanks!


I don't know what library you're using, but I assume it uses the PHP cURL extension internally, because that's how you specify to cURL the path to a file that you want to upload, i.e., by prepending the path with an @. See this example from the PHP manual:

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);


Looking at the code in the question, the '@' sign is just part of a string variable. It has no special meaning to PHP as a language.

It might have special meaning to the code which it is being passed to, but it isn't anything to PHP other than a simple string variable that happens to start with an '@' sign.

From the context, I guess presumably it's being passed to Twitter as part of a JSON object. In that case, it might have a special meaning to Twitter, but I don't know the API, so I couldn't tell you that for certain. In any case, it's not a PHP question.


The {$expression} syntax is one way to embed a variable or expression in a string in PHP, like the #{expression} syntax in Ruby.

So "@{$image}" is equivalent to '@'.$image.

The @ is used by the curl module to differenciate a regular POST variable value from a filename to upload. Your library must use the curl module internally or follow the same conventions.

When setting POST variables, if any value is prefixed with an @, it is considered to be a filename to upload:

curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'regular_variable' => 'value',
    'some_file' => '@/path/to/filename', // this is treated as a file to upload
));

This is not very well known and can lead to security issues if the programmer is not aware of this. This can be disabled by passing a query-string to CURLOPT_POSTFIELDS (http_build_query()).

This has no special meaning for PHP itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号