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

不打扰是莪最后的温柔 提交于 2019-12-02 16:46:37

问题


I have stumbled to following code example:

$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!


回答1:


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);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7216920/path-to-a-file-in-php-what-does-it-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!