Ответы пользователя по тегу PHP
  • Как скачать изображение по FTP ссылке? FTP server reports 550 Permission denied?

    @Kerm Автор вопроса
    Сделал рабочий скрипт, если кому интересно:

    <?php
    declare(strict_types=1);
    error_reporting(E_ALL);
    ini_set('display_errors','1');
    
    
    function grab_image($url, $saveto){
        if (file_exists($saveto)){
            unlink($saveto);
        }
    
        $fp = fopen($saveto, 'w+b');
        if (false === $fp) {
            throw new RuntimeException ( 'fopen() failed.   last error: ' . return_var_dump ( error_get_last () ) );
        }
    
        $ch = curl_init($url);
        if (false === $ch) {
            throw new RuntimeException ( 'curl_init() failed.   last error: ' . return_var_dump ( error_get_last () ) );
        }
    
        ecurl_setopt($ch, CURLOPT_URL, $url);
        ecurl_setopt($ch, CURLOPT_FILE, $fp);
        ecurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        ecurl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        ecurl_setopt($ch, CURLOPT_TIMEOUT, 30);
        ecurl_setopt($ch, CURLOPT_VERBOSE, 1);
        ecurl_setopt($ch, CURLOPT_STDERR, $fp);
    
        ecurl_exec($ch);
        curl_close($ch);
    
        fclose($fp);
    }
    
    $file = file_get_contents('images.txt');
    $images = explode("\n", $file);
    $i = 0;
    
    foreach ($images as $image) {
        $i++;
    
        $image = str_replace(" ","%20", trim($image));
    
        echo "image number: " .$i. "<br>";
    
        $fileName = explode('/', $image);
        end($fileName);
        $key = key($fileName);
    
        $fp = 'images/'.$fileName[$key];
        grab_image($image, $fp);
    }
    
    function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
        $ret=curl_setopt($ch,$option,$value);
        if($ret!==true){
            //option should be obvious by stack trace
            throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
        }
        return true;
    }
    function ecurl_exec ( /*resource*/$ch)/*:mixed depending on CURLOPT_RETURNTRANSFER*/{
        $ret=curl_exec($ch);
        if($ret===false){
            throw new RuntimeException ( 'curl_exec() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
        }
        return $ret;
    }
    
    
    function return_var_dump(/*...*/){
        $args = func_get_args ();
        ob_start ();
        call_user_func_array ( 'var_dump', $args );
        return ob_get_clean ();
    }


    Ссылки на картинки находятся в txt файле, каждая ссылка на новой строке.
    Ответ написан
  • Как прикрепить вложение к форме?

    @Kerm
    Вам необходимо доработать Ваш PHP код так чтобы он принимал и обрабатывал файл, полученный из формы, а так же отправлял его вместе с письмом.

    Вот удачный пример реализации, подходящий к вашему коду:

    https://www.geeksforgeeks.org/php-send-attachment-...
    Ответ написан
  • Как сделать суффиксы (K, M, B) для больших чисел?

    @Kerm
    function number_name($number)
    {
        $count = array("", "k", "M", "G", "T");
    
        $i = 0;
        while (abs($number) > 1000) {
            $number /= 1000;
            $i++;
        }
    
        return $number.$count[$i];
    }
    
    echo number_name(5)."\n";
    echo number_name(5000)."\n";
    echo number_name(-5000)."\n";
    echo number_name(5000000)."\n";
    echo number_name(5000000000)."\n";
    echo number_name(5000000000000);


    5
    5k
    -5k
    5M
    5G
    5T
    Ответ написан
  • Parser php oracle не пишет в БД?

    @Kerm
    Попробуй вот так:

    require_once "simple_html_dom.php";
    
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    $conn = oci_connect('ddd', 'ddd', '127.0.0.1/orcl', 'AL32UTF8');
    
    
    $brands = array();
    
    $html = str_get_html(file_get_contents('https://kolesa.kz/cars/'));
    $i = 'INSERT INTO kolesa_brands (id, name) VALUES';
    $select = $html->find('select[id=auto-car-mm-0]', 0);
    
    foreach($select->find('option') as $opt)
    {
    	if($opt->value == '') continue;
    	$i .= ' ('.$opt->value.', \''.$opt->plaintext.'\'),';
    	$brands[$opt->value] = $opt->plaintext; 
    }
    
    $insert = oci_parse($conn, rtrim($i, ',').';');
    
    oci_execute($insert);
    Ответ написан
  • Как в php изменить select на input radio чекбоксы?

    @Kerm
    $group_select = '';
    $allow_group = array(6,4); // Группы доступные при регистрации
    foreach ( $allow_group as $id ) {
    $group = $user_group[$id];
    $group_select .= '<div class="radio"><label><input type="radio" value="'.$group['id'].'" name="'.$group['group_name'].'"/> '.$group['group_name'].'</label></div>';
    }
    $tpl->set( '{group}', $group_select);
    Ответ написан
  • Как сделать этот запрос в mysql через php?

    @Kerm
    В одну строчку нельзя?

    "set @i := -1;update tablename set id = (@i := @i+1 ) order by id;"
    Ответ написан
  • Как узнать пропущенные элементы массива?

    @Kerm
    foreach ($array as $key => $value) {
        $value = trim($value);
        if (empty($value))
            echo "$key empty <br/>";
        else
            echo "$key not empty <br/>";
    }
    Ответ написан
  • PHP SOAP интеграция с API Pony Express?

    @Kerm Автор вопроса
    Ой все такие умные, тех. поддержки на сайте Pony нет вообще, даже такого раздела и чего либо намекающего на суппорт, на сайте даже онлайн чате отвечают раз в день у них. Please contact service desk. это скорее всего стандартный текст какой ни будь софтиты. Нет и не было у них service desk этого.

    Я посылаю вот эти данные:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <ns1:SubmitRequest>
             <!--Optional:-->
             <ns1:accesskey>59ef638c-****-****-****-5da5a6080f8e</ns1:accesskey>
             <!--Optional:-->
             <ns1:requestBody>
             	<ns1:Request xsi:type="OrderRequest">
             		<ns1:Id>10174</Id>
             		<ns1:Mode>Status</Mode>
    				<ns1:OrderList>
    					<ns1:Order>
    						<ns1:ServiceList>
    							<ns1:Service xsi:type="DeliveryService">
    								<ns1:Waybill>
    									<ns1:Number>22-6762-0542</Number>
    								</ns1:Waybill>
    							</ns1:Service>
    						</ns1:ServiceList>
    					</ns1:Order>
    				</ns1:OrderList>
             	</ns1:Request>
             </ns1:requestBody>
          </ns1:SubmitRequest>
       </soapenv:Body>
    </soapenv:Envelope>


    Получаю вот такой ответ:

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
       <s:Body>
          <s:Fault>
             <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:DeserializationFailed</faultcode>
             <faultstring xml:lang="ru-RU">The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:requestBody. The InnerException message was 'There was an error deserializing the object of type System.String. End element 'requestBody' from namespace 'http://tempuri.org/' expected. Found element 'ns1:Request' from namespace 'http://tempuri.org/'. Line 9, position 48.'.  Please see InnerException for more details.</faultstring>
             <detail>
                <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                   <HelpLink i:nil="true"/>
                   <InnerException>
                      <HelpLink i:nil="true"/>
                      <InnerException>
                         <HelpLink i:nil="true"/>
                         <InnerException i:nil="true"/>
                         <Message>End element 'requestBody' from namespace 'http://tempuri.org/' expected. Found element 'ns1:Request' from namespace 'http://tempuri.org/'. Line 9, position 48.</Message>
                         <StackTrace>at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
       at System.Xml.XmlExceptionHelper.ThrowEndElementExpected(XmlDictionaryReader reader, String localName, String ns)
       at System.Xml.XmlBaseReader.ReadEndElement()
       at System.Xml.XmlBaseReader.ReadElementContentAsString()
       at System.Runtime.Serialization.XmlReaderDelegator.ReadElementContentAsString()
       at System.Runtime.Serialization.StringDataContract.ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
       at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)</StackTrace>
                         <Type>System.Xml.XmlException</Type>
                      </InnerException>
                      <Message>There was an error deserializing the object of type System.String. End element 'requestBody' from namespace 'http://tempuri.org/' expected. Found element 'ns1:Request' from namespace 'http://tempuri.org/'. Line 9, position 48.</Message>
                      <StackTrace>at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.PartInfo.ReadObject(XmlDictionaryReader reader, XmlObjectSerializer serializer)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)</StackTrace>
                      <Type>System.Runtime.Serialization.SerializationException</Type>
                   </InnerException>
                   <Message>The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:requestBody. The InnerException message was 'There was an error deserializing the object of type System.String. End element 'requestBody' from namespace 'http://tempuri.org/' expected. Found element 'ns1:Request' from namespace 'http://tempuri.org/'. Line 9, position 48.'.  Please see InnerException for more details.</Message>
                   <StackTrace><![CDATA[at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameter(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)
       at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)]]></StackTrace>
                   <Type>System.ServiceModel.Dispatcher.NetDispatcherFaultException</Type>
                </ExceptionDetail>
             </detail>
          </s:Fault>
       </s:Body>
    </s:Envelope>


    Не пойму что означает ошибка:

    End element 'requestBody' from namespace 'tempuri.org' expected. Found element 'ns1:Request' from namespace 'tempuri.org'. Line 9, position 48
    Ответ написан